"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DidResolver = void 0;
var did_js_1 = require("./did.js");
var did_ion_resolver_js_1 = require("./did-ion-resolver.js");
var did_key_resolver_js_1 = require("./did-key-resolver.js");
var memory_cache_js_1 = require("../utils/memory-cache.js");
/**
 * A DID resolver that by default supports `did:key` and `did:ion` DIDs.
 */
var DidResolver = /** @class */ (function () {
    function DidResolver(resolvers, cache) {
        var e_1, _a;
        this.cache = cache || new memory_cache_js_1.MemoryCache(600);
        // construct default DID method resolvers if none given
        if (resolvers === undefined || resolvers.length === 0) {
            resolvers = [
                new did_ion_resolver_js_1.DidIonResolver(),
                new did_key_resolver_js_1.DidKeyResolver()
            ];
        }
        this.didResolvers = new Map();
        try {
            for (var resolvers_1 = __values(resolvers), resolvers_1_1 = resolvers_1.next(); !resolvers_1_1.done; resolvers_1_1 = resolvers_1.next()) {
                var resolver = resolvers_1_1.value;
                this.didResolvers.set(resolver.method(), resolver);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (resolvers_1_1 && !resolvers_1_1.done && (_a = resolvers_1.return)) _a.call(resolvers_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
    /**
     * attempt to resolve the DID provided
     * @throws {Error} if DID is invalid
     * @throws {Error} if DID method is not supported
     * @throws {Error} if resolving DID fails
     * @param did - the DID to resolve
     * @returns {DidResolutionResult}
     */
    DidResolver.prototype.resolve = function (did) {
        return __awaiter(this, void 0, void 0, function () {
            var splitDID, didMethod, didResolver, cachedResolutionResult, resolutionResult, _a, didDocument, didResolutionMetadata, error, errMsg;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        // naively validate author DID
                        did_js_1.Did.validate(did);
                        splitDID = did.split(':', 3);
                        didMethod = splitDID[1];
                        didResolver = this.didResolvers.get(didMethod);
                        if (!didResolver) {
                            throw new Error("".concat(didMethod, " DID method not supported"));
                        }
                        return [4 /*yield*/, this.cache.get(did)];
                    case 1:
                        cachedResolutionResult = _b.sent();
                        if (!(cachedResolutionResult !== null && cachedResolutionResult !== void 0)) return [3 /*break*/, 2];
                        _a = cachedResolutionResult;
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, didResolver.resolve(did)];
                    case 3:
                        _a = _b.sent();
                        _b.label = 4;
                    case 4:
                        resolutionResult = _a;
                        if (!(cachedResolutionResult === undefined)) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.cache.set(did, resolutionResult)];
                    case 5:
                        _b.sent();
                        _b.label = 6;
                    case 6:
                        didDocument = resolutionResult.didDocument, didResolutionMetadata = resolutionResult.didResolutionMetadata;
                        if (!didDocument || (didResolutionMetadata === null || didResolutionMetadata === void 0 ? void 0 : didResolutionMetadata.error)) {
                            error = didResolutionMetadata.error;
                            errMsg = "Failed to resolve DID ".concat(did, ".");
                            errMsg += error ? " Error: ".concat(error) : '';
                            throw new Error(errMsg);
                        }
                        return [2 /*return*/, resolutionResult];
                }
            });
        });
    };
    DidResolver.prototype.dump = function () {
        var _a, _b, _c;
        return __awaiter(this, void 0, void 0, function () {
            var _d, _e, _f, key, value, e_2_1;
            var e_2, _g;
            return __generator(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        console.group('didResolvers');
                        _h.label = 1;
                    case 1:
                        _h.trys.push([1, 6, 7, 8]);
                        _d = __values(this.didResolvers), _e = _d.next();
                        _h.label = 2;
                    case 2:
                        if (!!_e.done) return [3 /*break*/, 5];
                        _f = __read(_e.value, 2), key = _f[0], value = _f[1];
                        console.group(key);
                        // @ts-ignore
                        return [4 /*yield*/, ((_a = value['dump']) === null || _a === void 0 ? void 0 : _a.call(value))];
                    case 3:
                        // @ts-ignore
                        _h.sent();
                        console.groupEnd();
                        _h.label = 4;
                    case 4:
                        _e = _d.next();
                        return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        e_2_1 = _h.sent();
                        e_2 = { error: e_2_1 };
                        return [3 /*break*/, 8];
                    case 7:
                        try {
                            if (_e && !_e.done && (_g = _d.return)) _g.call(_d);
                        }
                        finally { if (e_2) throw e_2.error; }
                        return [7 /*endfinally*/];
                    case 8:
                        console.groupEnd();
                        console.group('didCache');
                        // @ts-ignore
                        return [4 /*yield*/, ((_c = (_b = this.cache)['dump']) === null || _c === void 0 ? void 0 : _c.call(_b))];
                    case 9:
                        // @ts-ignore
                        _h.sent();
                        console.groupEnd();
                        return [2 /*return*/];
                }
            });
        });
    };
    return DidResolver;
}());
exports.DidResolver = DidResolver;
//# sourceMappingURL=did-resolver.js.map