RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
import { lstat, readdir, readFile, mkdir, writeFile, realpath, link, unlink } from "node:fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { resolve, relative, isAbsolute, join, dirname } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { crc32, deflateRawSync } from "node:zlib";
|
||||
|
||||
const MiB = 1024 * 1024;
|
||||
const device = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
|
||||
function validPath(name) {
|
||||
return name.length <= 180 && name.split("/").every(part =>
|
||||
part.length > 0 && part.length <= 120 && /^[a-zA-Z0-9._-]+$/.test(part)
|
||||
&& !part.endsWith(".") && !device.test(part.split(".")[0]));
|
||||
}
|
||||
function requireValue(condition, message) {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
// ZIP32 with DEFLATE, fixed timestamps, and sorted paths gives repeatable release files.
|
||||
function zip(files) {
|
||||
const local = [], central = [];
|
||||
let offset = 0, centralSize = 0;
|
||||
for (const [path, bytes] of files) {
|
||||
const name = Buffer.from(path);
|
||||
const compressed = deflateRawSync(bytes, { level: 9 });
|
||||
const header = Buffer.alloc(30);
|
||||
header.writeUInt32LE(0x04034b50, 0);
|
||||
header.writeUInt16LE(20, 4);
|
||||
header.writeUInt16LE(8, 8);
|
||||
header.writeUInt16LE(33, 12); // January 1, 1980.
|
||||
header.writeUInt32LE(crc32(bytes), 14);
|
||||
header.writeUInt32LE(compressed.length, 18);
|
||||
header.writeUInt32LE(bytes.length, 22);
|
||||
header.writeUInt16LE(name.length, 26);
|
||||
local.push(header, name, compressed);
|
||||
const record = Buffer.alloc(46);
|
||||
record.writeUInt32LE(0x02014b50, 0);
|
||||
record.writeUInt16LE(20, 4);
|
||||
header.copy(record, 6, 4, 30);
|
||||
record.writeUInt32LE(offset, 42);
|
||||
central.push(record, name);
|
||||
offset += header.length + name.length + compressed.length;
|
||||
centralSize += record.length + name.length;
|
||||
}
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(centralSize, 12);
|
||||
end.writeUInt32LE(offset, 16);
|
||||
return Buffer.concat([...local, ...central, end]);
|
||||
}
|
||||
|
||||
export async function packagePlugin(source, destination) {
|
||||
const input = resolve(source);
|
||||
let project = input;
|
||||
if (!destination) {
|
||||
while (true) {
|
||||
try { await readFile(join(project, "package.json")); break; }
|
||||
catch (error) {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
const parent = dirname(project);
|
||||
requireValue(parent !== project, "Pass an output folder when the compiled folder has no project root.");
|
||||
project = parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
const output = resolve(destination ?? join(project, "releases"));
|
||||
const inputMeta = await lstat(input);
|
||||
requireValue(inputMeta.isDirectory() && !inputMeta.isSymbolicLink(), "Select a compiled plugin folder.");
|
||||
const files = [], names = new Set();
|
||||
let total = 0, count = 0;
|
||||
async function walk(directory, prefix = "") {
|
||||
for (const entry of (await readdir(directory)).sort()) {
|
||||
const name = prefix + entry;
|
||||
requireValue(validPath(name), `Invalid package path: ${name}`);
|
||||
requireValue(!names.has(name.toLowerCase()), `Duplicate package path: ${name}`);
|
||||
names.add(name.toLowerCase());
|
||||
requireValue(++count <= 5000, "The package exceeds 5,000 entries.");
|
||||
const path = join(directory, entry), meta = await lstat(path);
|
||||
requireValue(!meta.isSymbolicLink(), `Remove the link from the package: ${name}`);
|
||||
if (meta.isDirectory()) await walk(path, name + "/");
|
||||
else {
|
||||
requireValue(meta.isFile() && meta.size <= 25 * MiB, `Invalid or oversized package file: ${name}`);
|
||||
const bytes = await readFile(path);
|
||||
requireValue(bytes.length <= 25 * MiB, `The file exceeds 25 MiB: ${name}`);
|
||||
total += bytes.length;
|
||||
requireValue(total <= 100 * MiB, "The package exceeds 100 MiB of expanded data.");
|
||||
files.push([name, bytes]);
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(input);
|
||||
const manifestBytes = files.find(([name]) => name === "plugin.json")?.[1];
|
||||
requireValue(manifestBytes && manifestBytes.length <= 64 * 1024, "The package needs plugin.json at its root, within 64 KiB.");
|
||||
const manifest = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(manifestBytes));
|
||||
requireValue(typeof manifest.id === "string" && validPath(manifest.id) && /^[a-z][a-z0-9.-]*$/.test(manifest.id), "The plugin ID is invalid.");
|
||||
requireValue(manifest.schemaVersion === 1 && manifest.apiVersion === 1 && manifest.access === "full-app", "Unsupported schema, API version, or access mode.");
|
||||
for (const key of ["name", "author", "description", "version"]) {
|
||||
requireValue(typeof manifest[key] === "string" && manifest[key].trim() && Buffer.byteLength(manifest[key]) <= 1000, `The manifest needs a valid ${key}.`);
|
||||
}
|
||||
requireValue(/^\d+\.\d+\.\d+[a-z]*$/.test(manifest.version), "Use a plugin version such as 1.0.0 or 1.0.0a.");
|
||||
requireValue(typeof manifest.entry === "string" && validPath(manifest.entry) && /\.m?js$/.test(manifest.entry), "The entry must be a compiled JavaScript module.");
|
||||
const entry = files.find(([name]) => name === manifest.entry)?.[1];
|
||||
requireValue(entry, "The entry module is missing.");
|
||||
new TextDecoder("utf-8", { fatal: true }).decode(entry);
|
||||
const filename = `${manifest.id}-${manifest.version}.zip`;
|
||||
requireValue(filename.length <= 240, "The release filename is too long.");
|
||||
await mkdir(output, { recursive: true });
|
||||
const target = join(await realpath(output), filename);
|
||||
const within = relative(await realpath(input), target);
|
||||
requireValue(isAbsolute(within) || within === ".." || within.startsWith("../") || within.startsWith("..\\"), "Choose an output folder outside the plugin folder.");
|
||||
const archive = zip(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
||||
requireValue(archive.length <= 100 * MiB, "The archive exceeds 100 MiB.");
|
||||
const temporary = `${target}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, archive, { flag: "wx" });
|
||||
try {
|
||||
await link(temporary, target);
|
||||
} catch (error) {
|
||||
if (error.code !== "EEXIST") throw error;
|
||||
requireValue((await readFile(target)).equals(archive), "The release file already contains different contents: " + target);
|
||||
}
|
||||
} finally {
|
||||
await unlink(temporary).catch(error => { if (error.code !== "ENOENT") throw error; });
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||
try {
|
||||
requireValue(process.argv[2] && process.argv.length <= 4, "Usage: node scripts/packagePlugin.mjs <compiled-folder> [output-folder]");
|
||||
console.log(await packagePlugin(process.argv[2], process.argv[3]));
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user