"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makePartialBundle = exports.getAppUUID = void 0;
const tslib_1 = require("tslib");
const simpleSHA256 = require("simple-sha256");
function getAppUUID(zipFile) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const manifestFile = zipFile.file('manifest.json');
        if (manifestFile == null) {
            throw new Error('Not a valid component bundle: manifest.json not present');
        }
        const manifest = JSON.parse(yield manifestFile.async('text'));
        if (typeof manifest.uuid !== 'string') {
            throw new Error('Not a valid component bundle: "uuid" field in manifest.json is missing or not a string');
        }
        return manifest.uuid;
    });
}
exports.getAppUUID = getAppUUID;
function makePartialBundle(zipFile, existing) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        if (zipFile.file('.partial.json')) {
            throw new Error('Component bundle already contains .partial.json');
        }
        const deleteList = [];
        let manifestIsIdentical = false;
        let filesArePruned = false;
        for (const [path, { sha256 }] of Object.entries(existing.files)) {
            const file = zipFile.file(path);
            if (file == null) {
                deleteList.push(path);
            }
            else {
                const zipdigest = yield file.async('uint8array').then(simpleSHA256);
                if (sha256.toLowerCase() === zipdigest.toLowerCase()) {
                    if (path === 'manifest.json') {
                        manifestIsIdentical = true;
                    }
                    else {
                        zipFile.remove(path);
                        filesArePruned = true;
                    }
                }
            }
        }
        if (manifestIsIdentical &&
            deleteList.length === 0 &&
            zipFile.filter((path, file) => path !== 'manifest.json' && !file.dir).length === 0) {
            return null;
        }
        if (!filesArePruned) {
            throw new Error('No files can be reused for partial app install');
        }
        const partialManifest = {
            delete: deleteList,
        };
        zipFile.file('.partial.json', JSON.stringify(partialManifest));
        return zipFile.generateAsync({
            type: 'nodebuffer',
            compression: 'DEFLATE',
        });
    });
}
exports.makePartialBundle = makePartialBundle;
//# sourceMappingURL=componentBundle.js.map