"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.S9pk = void 0;
exports.compare = compare;
const merkleArchive_1 = require("./merkleArchive");
const mime_1 = __importDefault(require("mime"));
const directoryContents_1 = require("./merkleArchive/directoryContents");
const fileContents_1 = require("./merkleArchive/fileContents");
const magicAndVersion = new Uint8Array([59, 59, 2]);
/**
 * Compares two `Uint8Array` instances byte-by-byte for equality.
 *
 * @returns `true` if both arrays have the same length and identical bytes
 */
function compare(a, b) {
    if (a.length !== b.length)
        return false;
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i])
            return false;
    }
    return true;
}
/**
 * Represents a parsed `.s9pk` package archive — the binary distribution format for StartOS services.
 *
 * An `S9pk` wraps a verified {@link Manifest}, a {@link MerkleArchive} containing the package's
 * assets (icon, license, dependency metadata), and the total archive size in bytes.
 *
 * @example
 * ```ts
 * const s9pk = await S9pk.deserialize(file, null)
 * console.log(s9pk.manifest.id)    // e.g. "bitcoind"
 * console.log(s9pk.size)           // archive size in bytes
 * const icon = await s9pk.icon()   // base64 data URL
 * const license = await s9pk.license()
 * ```
 */
class S9pk {
    constructor(
    /** The parsed package manifest containing metadata, dependencies, and interface definitions. */
    manifest, 
    /** The Merkle-verified archive containing the package's files. */
    archive, 
    /** The total size of the archive in bytes. */
    size) {
        this.manifest = manifest;
        this.archive = archive;
        this.size = size;
    }
    /**
     * Deserializes an `S9pk` from a `Blob` (e.g. a `File` from a browser file input).
     *
     * Validates the magic bytes and version header, then parses the Merkle archive structure.
     * If a `commitment` is provided, the archive is cryptographically verified against it.
     *
     * @param source - The raw `.s9pk` file as a `Blob`
     * @param commitment - An optional Merkle commitment to verify the archive against, or `null` to skip verification
     * @returns A fully parsed `S9pk` instance
     * @throws If the magic bytes are invalid or the archive fails verification
     */
    static async deserialize(source, commitment) {
        const header = new merkleArchive_1.ArrayBufferReader(await source
            .slice(0, magicAndVersion.length + merkleArchive_1.MerkleArchive.headerSize)
            .arrayBuffer());
        const magicVersion = new Uint8Array(header.next(magicAndVersion.length));
        if (!compare(magicVersion, magicAndVersion)) {
            throw new Error('Invalid Magic or Unexpected Version');
        }
        const archive = await merkleArchive_1.MerkleArchive.deserialize(source, 's9pk', header, commitment);
        const manifest = JSON.parse(new TextDecoder().decode(await archive.contents
            .getPath(['manifest.json'])
            ?.verifiedFileContents()));
        return new S9pk(manifest, archive, source.size);
    }
    /**
     * Extracts the package icon from the archive and returns it as a base64-encoded data URL.
     *
     * Looks for a file named `icon.*` with an image MIME type (e.g. `icon.png`, `icon.svg`).
     *
     * @returns A data URL string like `"data:image/png;base64,..."` suitable for use in `<img src>`.
     * @throws If no icon file is found in the archive
     */
    async icon() {
        const iconName = Object.keys(this.archive.contents.contents).find((name) => name.startsWith('icon.') && mime_1.default.getType(name)?.startsWith('image/'));
        if (!iconName) {
            throw new Error('no icon found in archive');
        }
        return (`data:${mime_1.default.getType(iconName)};base64,` +
            Buffer.from(await this.archive.contents.getPath([iconName]).verifiedFileContents()).toString('base64'));
    }
    /**
     * Returns the metadata (e.g. `{ title }`) for a specific dependency by its package ID.
     *
     * @param id - The dependency's package identifier (e.g. `"bitcoind"`)
     * @returns The dependency metadata object, or `null` if the dependency is not present in the archive
     */
    async dependencyMetadataFor(id) {
        const entry = this.archive.contents.getPath([
            'dependencies',
            id,
            'metadata.json',
        ]);
        if (!entry)
            return null;
        return JSON.parse(new TextDecoder().decode(await entry.verifiedFileContents()));
    }
    /**
     * Returns the icon for a specific dependency as a base64 data URL.
     *
     * @param id - The dependency's package identifier
     * @returns A data URL string, or `null` if the dependency or its icon is not present
     */
    async dependencyIconFor(id) {
        const dir = this.archive.contents.getPath(['dependencies', id]);
        if (!dir || !(dir.contents instanceof directoryContents_1.DirectoryContents))
            return null;
        const iconName = Object.keys(dir.contents.contents).find((name) => name.startsWith('icon.') && mime_1.default.getType(name)?.startsWith('image/'));
        if (!iconName)
            return null;
        return (`data:${mime_1.default.getType(iconName)};base64,` +
            Buffer.from(await dir.contents.getPath([iconName]).verifiedFileContents()).toString('base64'));
    }
    /**
     * Returns a merged record of all dependency metadata (title, icon, description, optional flag)
     * for every dependency declared in the manifest.
     *
     * @returns A record keyed by package ID, each containing `{ title, icon, description, optional }`
     */
    async dependencyMetadata() {
        return Object.fromEntries(await Promise.all(Object.entries(this.manifest.dependencies)
            .filter(([_, info]) => !!info)
            .map(async ([id, info]) => [
            id,
            {
                ...(await this.dependencyMetadataFor(id)),
                icon: await this.dependencyIconFor(id),
                description: info.description,
                optional: info.optional,
            },
        ])));
    }
    /**
     * Reads and returns the `LICENSE.md` file from the archive as a UTF-8 string.
     *
     * @returns The full license text
     * @throws If `LICENSE.md` is not found in the archive
     */
    async license() {
        const file = this.archive.contents.getPath(['LICENSE.md']);
        if (!file || !(file.contents instanceof fileContents_1.FileContents))
            throw new Error('license.md not found in archive');
        return new TextDecoder().decode(await file.verifiedFileContents());
    }
}
exports.S9pk = S9pk;
//# sourceMappingURL=index.js.map