"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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 __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cid = void 0;
const cbor = __importStar(require("@ipld/dag-cbor"));
const cid_1 = require("multiformats/cid");
const ipfs_unixfs_importer_1 = require("ipfs-unixfs-importer");
const blockstore_core_1 = require("blockstore-core");
const sha2_1 = require("multiformats/hashes/sha2");
// a map of all supported CID hashing algorithms. This map is used to select the appropriate hasher
// when generating a CID to compare against a provided CID
const hashers = {
    [sha2_1.sha256.code]: sha2_1.sha256,
};
// a map of all support codecs.This map is used to select the appropriate codec
// when generating a CID to compare against a provided CID
const codecs = {
    [cbor.code]: cbor
};
/**
 * Utility class for creating CIDs. Exported for the convenience of developers.
 */
class Cid {
    /**
     * Computes a V1 CID for the provided payload
     * @param codecCode - the codec to use. Defaults to cbor
     * @param multihashCode - the multihasher to use. Defaults to sha256
     * @returns payload CID
     * @throws {Error} codec is not supported
     * @throws {Error} encoding fails
     * @throws {Error} if hasher is not supported
     */
    static computeCid(payload, codecCode = cbor.code, multihashCode = sha2_1.sha256.code) {
        return __awaiter(this, void 0, void 0, function* () {
            const codec = codecs[codecCode];
            if (!codec) {
                throw new Error(`codec [${codecCode}] not supported`);
            }
            const hasher = hashers[multihashCode];
            if (!hasher) {
                throw new Error(`multihash code [${multihashCode}] not supported`);
            }
            const payloadBytes = codec.encode(payload);
            const payloadHash = yield hasher.digest(payloadBytes);
            const cid = yield cid_1.CID.createV1(codec.code, payloadHash);
            return cid.toString();
        });
    }
    /**
     * Parses the given CID string into a {CID}.
     */
    static parseCid(str) {
        const cid = cid_1.CID.parse(str).toV1();
        if (!codecs[cid.code]) {
            throw new Error(`codec [${cid.code}] not supported`);
        }
        if (!hashers[cid.multihash.code]) {
            throw new Error(`multihash code [${cid.multihash.code}] not supported`);
        }
        return cid;
    }
    /**
     * @returns V1 CID of the DAG comprised by chunking data into unixfs DAG-PB encoded blocks
     */
    static computeDagPbCidFromBytes(content) {
        var e_1, _a;
        return __awaiter(this, void 0, void 0, function* () {
            const asyncDataBlocks = (0, ipfs_unixfs_importer_1.importer)([{ content }], new blockstore_core_1.MemoryBlockstore(), { cidVersion: 1 });
            // NOTE: the last block contains the root CID
            let block;
            try {
                for (var asyncDataBlocks_1 = __asyncValues(asyncDataBlocks), asyncDataBlocks_1_1; asyncDataBlocks_1_1 = yield asyncDataBlocks_1.next(), !asyncDataBlocks_1_1.done;) {
                    block = asyncDataBlocks_1_1.value;
                    ;
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (asyncDataBlocks_1_1 && !asyncDataBlocks_1_1.done && (_a = asyncDataBlocks_1.return)) yield _a.call(asyncDataBlocks_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return block ? block.cid.toString() : '';
        });
    }
    /**
     * @returns V1 CID of the DAG comprised by chunking data into unixfs DAG-PB encoded blocks
     */
    static computeDagPbCidFromStream(dataStream) {
        var e_2, _a;
        return __awaiter(this, void 0, void 0, function* () {
            const asyncDataBlocks = (0, ipfs_unixfs_importer_1.importer)([{ content: dataStream }], new blockstore_core_1.MemoryBlockstore(), { cidVersion: 1 });
            // NOTE: the last block contains the root CID
            let block;
            try {
                for (var asyncDataBlocks_2 = __asyncValues(asyncDataBlocks), asyncDataBlocks_2_1; asyncDataBlocks_2_1 = yield asyncDataBlocks_2.next(), !asyncDataBlocks_2_1.done;) {
                    block = asyncDataBlocks_2_1.value;
                    ;
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (asyncDataBlocks_2_1 && !asyncDataBlocks_2_1.done && (_a = asyncDataBlocks_2.return)) yield _a.call(asyncDataBlocks_2);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return block ? block.cid.toString() : '';
        });
    }
}
exports.Cid = Cid;
//# sourceMappingURL=cid.js.map