"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RegistryMeta = exports.PackagistFile = exports.PackagesResponse = exports.RegistryFile = exports.HashSpec = exports.parsePackagesResponses = exports.extractDepReleases = exports.extractReleaseResult = exports.parsePackagesResponse = exports.ComposerPackagesResponse = exports.ComposerReleases = exports.ComposerRelease = exports.MinifiedArray = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const zod_1 = require("zod");
const logger_1 = require("../../../logger");
const schema_utils_1 = require("../../../util/schema-utils");
exports.MinifiedArray = zod_1.z.array(zod_1.z.record(zod_1.z.unknown())).transform((xs) => {
    // Ported from: https://github.com/composer/metadata-minifier/blob/main/src/MetadataMinifier.php#L17
    if (xs.length === 0) {
        return xs;
    }
    const prevVals = {};
    for (const x of xs) {
        for (const key of Object.keys(x)) {
            prevVals[key] ??= undefined;
        }
        for (const key of Object.keys(prevVals)) {
            const val = x[key];
            if (val === '__unset') {
                delete x[key];
                prevVals[key] = undefined;
                continue;
            }
            if (!is_1.default.undefined(val)) {
                prevVals[key] = val;
                continue;
            }
            if (!is_1.default.undefined(prevVals[key])) {
                x[key] = prevVals[key];
                continue;
            }
        }
    }
    return xs;
});
exports.ComposerRelease = zod_1.z.object({
    version: zod_1.z.string(),
    homepage: zod_1.z.string().nullable().catch(null),
    source: zod_1.z.object({ url: zod_1.z.string() }).nullable().catch(null),
    time: zod_1.z.string().nullable().catch(null),
    require: zod_1.z.object({ php: zod_1.z.string() }).nullable().catch(null),
});
exports.ComposerReleases = zod_1.z
    .union([
    exports.MinifiedArray.pipe((0, schema_utils_1.LooseArray)(exports.ComposerRelease)),
    (0, schema_utils_1.LooseRecord)(exports.ComposerRelease).transform((map) => Object.values(map)),
])
    .catch([]);
exports.ComposerPackagesResponse = zod_1.z
    .object({
    packageName: zod_1.z.string(),
    packagesResponse: zod_1.z.object({
        packages: zod_1.z.record(zod_1.z.unknown()),
    }),
})
    .transform(({ packageName, packagesResponse }) => packagesResponse.packages[packageName])
    .transform((xs) => exports.ComposerReleases.parse(xs));
function parsePackagesResponse(packageName, packagesResponse) {
    try {
        return exports.ComposerPackagesResponse.parse({ packageName, packagesResponse });
    }
    catch (err) {
        logger_1.logger.debug({ packageName, err }, `Error parsing packagist response for ${packageName}`);
        return [];
    }
}
exports.parsePackagesResponse = parsePackagesResponse;
function extractReleaseResult(...composerReleasesArrays) {
    const releases = [];
    let homepage;
    let sourceUrl;
    for (const composerReleasesArray of composerReleasesArrays) {
        for (const composerRelease of composerReleasesArray) {
            const version = composerRelease.version.replace(/^v/, '');
            const gitRef = composerRelease.version;
            const dep = { version, gitRef };
            if (composerRelease.time) {
                dep.releaseTimestamp = composerRelease.time;
            }
            if (composerRelease.require?.php) {
                dep.constraints = { php: [composerRelease.require.php] };
            }
            releases.push(dep);
            if (!homepage && composerRelease.homepage) {
                homepage = composerRelease.homepage;
            }
            if (!sourceUrl && composerRelease.source?.url) {
                sourceUrl = composerRelease.source.url;
            }
        }
    }
    if (releases.length === 0) {
        return null;
    }
    const result = { releases };
    if (homepage) {
        result.homepage = homepage;
    }
    if (sourceUrl) {
        result.sourceUrl = sourceUrl;
    }
    return result;
}
exports.extractReleaseResult = extractReleaseResult;
function extractDepReleases(composerReleases) {
    const parsedReleases = exports.ComposerReleases.parse(composerReleases);
    return extractReleaseResult(parsedReleases);
}
exports.extractDepReleases = extractDepReleases;
function parsePackagesResponses(packageName, packagesResponses) {
    const releaseArrays = packagesResponses.map((pkgResp) => parsePackagesResponse(packageName, pkgResp));
    return extractReleaseResult(...releaseArrays);
}
exports.parsePackagesResponses = parsePackagesResponses;
exports.HashSpec = zod_1.z.union([
    zod_1.z
        .object({ sha256: zod_1.z.string().nullable() })
        .transform(({ sha256 }) => ({ hash: sha256 })),
    zod_1.z
        .object({ sha1: zod_1.z.string().nullable() })
        .transform(({ sha1 }) => ({ hash: sha1 })),
]);
exports.RegistryFile = zod_1.z.intersection(exports.HashSpec, zod_1.z.object({ key: zod_1.z.string() }));
exports.PackagesResponse = zod_1.z.object({
    packages: (0, schema_utils_1.LooseRecord)(exports.ComposerReleases).catch({}),
});
exports.PackagistFile = exports.PackagesResponse.merge(zod_1.z.object({
    providers: (0, schema_utils_1.LooseRecord)(exports.HashSpec)
        .transform((x) => Object.fromEntries(Object.entries(x).map(([key, { hash }]) => [key, hash])))
        .catch({}),
}));
exports.RegistryMeta = zod_1.z
    .record(zod_1.z.unknown())
    .catch({})
    .pipe(exports.PackagistFile.merge(zod_1.z.object({
    ['includes']: (0, schema_utils_1.LooseRecord)(exports.HashSpec)
        .transform((x) => Object.entries(x).map(([name, { hash }]) => ({ key: name, hash })))
        .catch([]),
    ['provider-includes']: (0, schema_utils_1.LooseRecord)(exports.HashSpec)
        .transform((x) => Object.entries(x).map(([key, { hash }]) => ({ key, hash })))
        .catch([]),
    ['providers-lazy-url']: zod_1.z.string().nullable().catch(null),
    ['providers-url']: zod_1.z.string().nullable().catch(null),
    ['metadata-url']: zod_1.z.string().nullable().catch(null),
    ['available-packages']: zod_1.z
        .array(zod_1.z.string())
        .transform((xs) => new Set(xs))
        .nullable()
        .catch(null),
})))
    .transform(({ ['includes']: includesFiles, ['packages']: packages, ['provider-includes']: files, ['providers']: providerPackages, ['providers-lazy-url']: providersLazyUrl, ['providers-url']: providersUrl, ['metadata-url']: metadataUrl, ['available-packages']: availablePackages, }) => ({
    packages,
    includesFiles,
    providerPackages,
    files,
    providersUrl,
    providersLazyUrl,
    metadataUrl,
    includesPackages: {},
    availablePackages,
}));
//# sourceMappingURL=schema.js.map