"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTargetsMeta = createTargetsMeta;
exports.createSnapshotMeta = createSnapshotMeta;
exports.createTimestampMeta = createTimestampMeta;
exports.createRootMeta = createRootMeta;
const models_1 = require("@tufjs/models");
const crypto_1 = require("./crypto");
function createTargetsMeta(targetFiles, keyPair) {
    const targets = new models_1.Metadata(new models_1.Targets({
        version: 1,
        specVersion: '1.0.0',
        expires: getExpires(),
    }));
    targetFiles.forEach((targetFile) => targets.signed.addTarget(targetFile));
    targets.sign((data) => keyPair.sign(data));
    return targets;
}
function createSnapshotMeta(targets, keyPair) {
    const snapshot = new models_1.Metadata(new models_1.Snapshot({
        version: 1,
        specVersion: '1.0.0',
        expires: getExpires(),
        meta: { 'targets.json': toMetaFile(targets) },
    }));
    snapshot.sign((data) => keyPair.sign(data));
    return snapshot;
}
function createTimestampMeta(snapshot, keyPair) {
    const timestamp = new models_1.Metadata(new models_1.Timestamp({
        version: 1,
        specVersion: '1.0.0',
        expires: getExpires(),
        snapshotMeta: toMetaFile(snapshot),
    }));
    timestamp.sign((data) => keyPair.sign(data));
    return timestamp;
}
function createRootMeta(keyPair) {
    const root = new models_1.Metadata(new models_1.Root({
        version: 1,
        specVersion: '1.0.0',
        expires: getExpires(),
        consistentSnapshot: false,
    }));
    root.signed.addKey(keyPair.publicKey, 'root');
    root.signed.addKey(keyPair.publicKey, 'snapshot');
    root.signed.addKey(keyPair.publicKey, 'targets');
    root.signed.addKey(keyPair.publicKey, 'timestamp');
    root.sign((data) => keyPair.sign(data));
    return root;
}
function toMetaFile(metadata) {
    const meta = JSON.stringify(metadata);
    return new models_1.MetaFile({
        version: 1,
        length: meta.length,
        hashes: { sha256: (0, crypto_1.digestSHA256)(meta) },
    });
}
function getExpires() {
    const expires = new Date();
    expires.setFullYear(expires.getFullYear() + 1);
    return expires.toISOString();
}
