"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.scaffoldFromTemplatePackage = scaffoldFromTemplatePackage;
exports.isTemplatePackageAvailable = isTemplatePackageAvailable;
const sdk_build_core_1 = require("@servicenow/sdk-build-core");
async function fetchPackageTarball(config, registry) {
    const packageName = config.name;
    const packumentUrl = `${registry.replace(/\/$/, '')}/${packageName}`;
    const packumentRes = await fetch(packumentUrl);
    if (!packumentRes.ok) {
        throw new Error(`Failed to fetch package metadata for ${packageName}: ${packumentRes.status} ${packumentRes.statusText}`);
    }
    const packument = (await packumentRes.json());
    const version = config.version ?? packument['dist-tags']?.['latest'];
    if (!version) {
        throw new Error(`No version resolved for ${packageName}`);
    }
    const tarballUrl = packument.versions?.[version]?.dist?.tarball;
    if (!tarballUrl) {
        throw new Error(`No tarball URL found for ${packageName}@${version}`);
    }
    const tarRes = await fetch(tarballUrl);
    if (!tarRes.ok) {
        throw new Error(`Failed to download ${packageName}@${version}: ${tarRes.status} ${tarRes.statusText}`);
    }
    return new Uint8Array(await tarRes.arrayBuffer());
}
async function scaffoldFromTemplatePackage(directory, fileSystem, config, registry) {
    const tgzData = await fetchPackageTarball(config, registry);
    const prefix = config.templatePath ? `package/${config.templatePath}/` : 'package/';
    return (0, sdk_build_core_1.extractTarGz)(tgzData, directory, fileSystem, { prefix });
}
async function isTemplatePackageAvailable(config, registry) {
    try {
        const packageName = config.name;
        const packumentUrl = `${registry.replace(/\/$/, '')}/${packageName}`;
        const res = await fetch(packumentUrl, { method: 'HEAD' });
        return res.ok;
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=template-package.js.map