185 lines
6.2 KiB
JavaScript
185 lines
6.2 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
const crypto = require("node:crypto");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const { spawnSync } = require("node:child_process");
|
|
|
|
const root = path.resolve(__dirname, "..");
|
|
const packagesRoot = path.join(root, "packages");
|
|
const ignoredNames = new Set(["node_modules", ".turbo", "dist", ".git"]);
|
|
|
|
function fail(message) {
|
|
console.error(message);
|
|
process.exitCode = 1;
|
|
}
|
|
|
|
function usage() {
|
|
console.error("Usage: node scripts/template-pack.cjs --template <packageKey> --out <directory>");
|
|
}
|
|
|
|
function parseArgs(argv) {
|
|
const values = {};
|
|
const argumentsWithoutSeparator = argv[0] === "--" ? argv.slice(1) : argv;
|
|
for (let index = 0; index < argumentsWithoutSeparator.length; index += 1) {
|
|
const argument = argumentsWithoutSeparator[index];
|
|
if (!argument.startsWith("--")) throw new Error(`Unknown argument: ${argument}`);
|
|
const key = argument.slice(2);
|
|
const value = argumentsWithoutSeparator[index + 1];
|
|
if (!value || value.startsWith("--")) throw new Error(`Missing value for --${key}`);
|
|
values[key] = value;
|
|
index += 1;
|
|
}
|
|
return values;
|
|
}
|
|
|
|
function canonical(value) {
|
|
if (Array.isArray(value)) return value.map(canonical);
|
|
if (!value || typeof value !== "object") return value;
|
|
return Object.fromEntries(
|
|
Object.keys(value)
|
|
.sort()
|
|
.map((key) => [key, canonical(value[key])]),
|
|
);
|
|
}
|
|
|
|
function sha256(value) {
|
|
return crypto.createHash("sha256").update(value).digest("hex");
|
|
}
|
|
|
|
function toPosix(value) {
|
|
return value.split(path.sep).join("/");
|
|
}
|
|
|
|
function listFiles(directory, relative = "") {
|
|
const files = [];
|
|
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
if (ignoredNames.has(entry.name)) continue;
|
|
const entryRelative = relative ? path.join(relative, entry.name) : entry.name;
|
|
const entryPath = path.join(directory, entry.name);
|
|
if (entry.isSymbolicLink())
|
|
throw new Error(`Template package cannot contain symlink: ${entryRelative}`);
|
|
if (entry.isDirectory()) files.push(...listFiles(entryPath, entryRelative));
|
|
else if (entry.isFile()) files.push(toPosix(entryRelative));
|
|
else throw new Error(`Unsupported template package entry: ${entryRelative}`);
|
|
}
|
|
return files.sort();
|
|
}
|
|
|
|
function copyFiles(source, target, files) {
|
|
for (const relative of files) {
|
|
const destination = path.join(target, relative);
|
|
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
fs.copyFileSync(path.join(source, relative), destination);
|
|
}
|
|
}
|
|
|
|
function runTemplateValidation() {
|
|
const result = spawnSync(
|
|
process.execPath,
|
|
[path.join(root, "scripts/validate-template-packages.cjs")],
|
|
{
|
|
cwd: root,
|
|
encoding: "utf8",
|
|
stdio: "inherit",
|
|
},
|
|
);
|
|
if (result.status !== 0) throw new Error("Template package validation failed");
|
|
}
|
|
|
|
function createArchive(directory, archive) {
|
|
const parent = path.dirname(directory);
|
|
const name = path.basename(directory);
|
|
const result = spawnSync(
|
|
"tar",
|
|
[
|
|
"--create",
|
|
"--gzip",
|
|
"--file",
|
|
archive,
|
|
"--sort=name",
|
|
"--mtime=UTC 1970-01-01",
|
|
"--owner=0",
|
|
"--group=0",
|
|
"--numeric-owner",
|
|
"--directory",
|
|
parent,
|
|
name,
|
|
],
|
|
{ cwd: root, stdio: "inherit" },
|
|
);
|
|
if (result.status !== 0) throw new Error("Could not create deterministic template archive");
|
|
}
|
|
|
|
function main() {
|
|
const values = parseArgs(process.argv.slice(2));
|
|
const packageKey = values.template;
|
|
const outputRoot = values.out;
|
|
if (!packageKey || !outputRoot) {
|
|
usage();
|
|
return 1;
|
|
}
|
|
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(packageKey))
|
|
throw new Error(`Invalid template package key: ${packageKey}`);
|
|
|
|
runTemplateValidation();
|
|
const source = path.join(packagesRoot, `template-${packageKey}`);
|
|
const manifestPath = path.join(source, "template.json");
|
|
const packageJsonPath = path.join(source, "package.json");
|
|
if (!fs.existsSync(manifestPath) || !fs.existsSync(packageJsonPath))
|
|
throw new Error(`Template package not found: ${packageKey}`);
|
|
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
|
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
|
|
if (manifest.packageKey !== packageKey)
|
|
throw new Error("template.json packageKey does not match request");
|
|
if (packageJson.version !== manifest.version)
|
|
throw new Error("package.json version does not match template.json version");
|
|
|
|
const destinationRoot = path.resolve(root, outputRoot);
|
|
const packageName = `${packageKey}-${manifest.version}`;
|
|
const destination = path.join(destinationRoot, packageName);
|
|
const archive = path.join(destinationRoot, `${packageName}.tar.gz`);
|
|
const sourceRelative = path.relative(source, destination);
|
|
if (!sourceRelative.startsWith(".." + path.sep) && sourceRelative !== "..")
|
|
throw new Error("Output directory cannot be inside the source template package");
|
|
|
|
fs.mkdirSync(destinationRoot, { recursive: true });
|
|
fs.rmSync(destination, { recursive: true, force: true });
|
|
fs.rmSync(archive, { force: true });
|
|
fs.mkdirSync(destination, { recursive: true });
|
|
|
|
const files = listFiles(source);
|
|
copyFiles(source, destination, files);
|
|
const entries = files.map((relative) => {
|
|
const content = fs.readFileSync(path.join(destination, relative));
|
|
return { path: relative, bytes: content.byteLength, sha256: sha256(content) };
|
|
});
|
|
const contentChecksum = sha256(JSON.stringify(canonical(entries)));
|
|
const checksums = {
|
|
formatVersion: "1",
|
|
packageKey,
|
|
version: manifest.version,
|
|
contentChecksum,
|
|
files: entries,
|
|
};
|
|
fs.writeFileSync(
|
|
path.join(destination, "checksums.json"),
|
|
JSON.stringify(checksums, null, 2) + "\n",
|
|
"utf8",
|
|
);
|
|
createArchive(destination, archive);
|
|
const archiveChecksum = sha256(fs.readFileSync(archive));
|
|
console.log(`template package: ${packageKey}@${manifest.version}`);
|
|
console.log(`content checksum: ${contentChecksum}`);
|
|
console.log(`archive checksum: ${archiveChecksum}`);
|
|
console.log(`directory: ${path.relative(root, destination)}`);
|
|
console.log(`archive: ${path.relative(root, archive)}`);
|
|
return 0;
|
|
}
|
|
|
|
try {
|
|
process.exitCode = main();
|
|
} catch (error) {
|
|
fail(error instanceof Error ? error.message : String(error));
|
|
}
|