'use strict';

var modules_abstract_did_errors = require('../../modules/abstract/did/errors.cjs');
var resolver_generic_resolver = require('../generic/resolver.cjs');
require('../../utils/types/array.cjs');
require('crypto');
var utils_jsonFetch = require('../../utils/json-fetch.cjs');
require('bs58');
require('multiformats/bases/base58');
require('varint');
require('../../utils/encoding/ss-58.cjs');
var resolver_generic_const = require('../generic/const.cjs');
require('../../utils/types/string.cjs');
require('../../utils/inheritance.cjs');
require('../../utils/types/object.cjs');
require('../../utils/types/iterable.cjs');
require('../../utils/types/set.cjs');
require('blake2b');
require('../../utils/types/bytes.cjs');
require('../../utils/interfaces.cjs');
require('../../utils/assert.cjs');
require('../../utils/error.cjs');

/**
 * Resolves `DID`s with wildcard method: `did:*:`.
 */
class UniversalResolver extends resolver_generic_resolver {
  prefix = 'did';

  method = resolver_generic_const.WILDCARD;

  /**
   * Create an adapter to a
   * [universal-resolver](https://github.com/decentralized-identity/universal-resolver) instance. The
   * adapter has type
   * [DIDResolver](https://github.com/decentralized-identity/did-resolver/blob/02bdaf1687151bb934b10093042e576ed54b229c/src/resolver.ts#L73).
   * @constructor
   * @param {string} url - address of an instance of universal-resolver.
   */
  constructor(url) {
    super();
    this.url = new URL(url);

    // Remove trailing slash if any and append the string `/1.0/identifiers/`
    this.idUrl = `${url.replace(/\/$/, '')}/1.0/identifiers/`;
  }

  /**
   * Fetch the DID from the universal resolver.
   * @param {string} did - A full DID (with method, like did:uport:2nQtiQG....)
   * @returns {Promise<object>}
   */
  async resolve(did) {
    const hashIndex = did.indexOf('#');
    const encodedDid = encodeURIComponent(
      hashIndex === -1 ? did : did.slice(0, hashIndex).trim(),
    );
    try {
      const resp = await utils_jsonFetch.default(`${this.idUrl}${encodedDid}`, {
        headers: {
          Accept:
            'application/ld+json;profile="https://w3id.org/did-resolution"',
        },
      });

      // Sometimes didDocument doesnt exist, if so return data as document
      return resp.didDocument || resp;
    } catch (error) {
      if (error.statusCode === 404) {
        throw new modules_abstract_did_errors.NoDIDError(did);
      }

      throw error;
    }
  }
}

module.exports = UniversalResolver;
//# sourceMappingURL=universal-resolver.cjs.map
