"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const AUDIT_ALLOWLIST = [
    'minimatch',
    'picomatch',
    'koa',
    'serialize-javascript',
    'esbuild',
];
const AUDIT_STEP = `
      - name: Security Audit
        run: npx unisphere tools audit
        env: 
          KALTURA_JFROG_TOKEN: $\{\{ steps.setup-jfrog.outputs.oidc-token }}`;
async function update(tree) {
    devkit_1.logger.info('🔄 Adding security audit gate...');
    seedAllowlist(tree);
    addCicdStep(tree);
}
function seedAllowlist(tree) {
    const packageJsonPath = 'package.json';
    if (!tree.exists(packageJsonPath)) {
        devkit_1.logger.warn('⚠️ No package.json found, skipping allowlist seed');
        return;
    }
    (0, devkit_1.updateJson)(tree, packageJsonPath, (packageJson) => {
        if (!packageJson.unisphere) {
            packageJson.unisphere = {};
        }
        if (!packageJson.unisphere.audit) {
            packageJson.unisphere.audit = {};
        }
        packageJson.unisphere.audit.allowlist = [...AUDIT_ALLOWLIST];
        return packageJson;
    });
    devkit_1.logger.info('✅ Seeded audit allowlist in package.json');
}
function addCicdStep(tree) {
    const cicdPath = '.github/workflows/cicd.yml';
    if (!tree.exists(cicdPath)) {
        devkit_1.logger.warn('⚠️ No cicd.yml found');
        throw new Error('No cicd.yml found');
    }
    let content = tree.read(cicdPath, 'utf-8');
    if (!content) {
        devkit_1.logger.warn('⚠️ Could not read cicd.yml');
        throw new Error('Could not read cicd.yml');
    }
    if (content.includes('Security Audit')) {
        devkit_1.logger.info('ℹ️ Security Audit step already exists in cicd.yml, skipping');
        return;
    }
    const installDepsMatch = content.match(/( *- name: Install Dependencies[ \t]*\n(?:.*\n)*?)([ \t]*- name: )/);
    if (!installDepsMatch) {
        devkit_1.logger.warn('⚠️ Could not find Install Dependencies step in cicd.yml');
        throw new Error('Could not find Install Dependencies step in cicd.yml');
    }
    const insertIndex = installDepsMatch.index + installDepsMatch[1].length;
    content =
        content.slice(0, insertIndex) +
            AUDIT_STEP +
            '\n\n' +
            content.slice(insertIndex);
    tree.write(cicdPath, content);
    devkit_1.logger.info('✅ Added Security Audit step to cicd.yml');
}
