@zaisma/cli 0.70.0 → 0.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/package.json +3 -1
- package/pieces.d.mts +201 -0
- package/pieces.mjs +1162 -0
- package/skill/SKILL.md +2 -0
- package/skill/references/developer-api.md +47 -6
- package/skill/references/naming.md +8 -0
- package/skill/references/pieces.md +251 -0
- package/skill/references/sdk.md +19 -3
- package/zaisma.mjs +148 -3
package/pieces.mjs
ADDED
|
@@ -0,0 +1,1162 @@
|
|
|
1
|
+
// Pieces: shared building blocks a game is made from (docs/PIECES.md). This is the frame every piece stands on:
|
|
2
|
+
// what a piece states about itself (its piece.json: its kind, the standard it's built on, what it needs and the
|
|
3
|
+
// versions it accepts, its settings and hooks), how it's added to a game, how its versions move, and the check a
|
|
4
|
+
// maker runs before publishing. Anyone publishes a piece, for any engine. Nothing here knows any piece, standard
|
|
5
|
+
// or publisher by name, and adding never runs a piece's code: every piece goes through exactly the same steps.
|
|
6
|
+
//
|
|
7
|
+
// The rules of adding (planAdd): a piece's needs come with it; one the game already has, at a version the new
|
|
8
|
+
// piece accepts, is left exactly as it is (never a second copy, never moved to another version); one at a version
|
|
9
|
+
// it doesn't accept stops everything, saying both versions and the ways out; and nothing is written unless the
|
|
10
|
+
// whole set fits. A version moves only in updatePiece, for the one piece named.
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { lstat, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
13
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
14
|
+
import { gunzipSync } from "node:zlib";
|
|
15
|
+
import { parse as parseJavaScript } from "acorn";
|
|
16
|
+
import { GAME_FILE_EXTENSIONS, extensionOf } from "./check.mjs";
|
|
17
|
+
|
|
18
|
+
/** The format of a piece.json this command reads. A statement with a higher number is from a newer command. */
|
|
19
|
+
export const STATEMENT_VERSION_NUMBER = 1;
|
|
20
|
+
/** The format of a game's pieces/pieces.json this command reads and writes. */
|
|
21
|
+
export const RECORD_VERSION_NUMBER = 1;
|
|
22
|
+
/** The kinds of piece, from the standards everything fits to the thing copied once. */
|
|
23
|
+
export const PIECE_KINDS = ["foundation", "extension", "game_system", "template"];
|
|
24
|
+
/** What a piece can need: another piece, a library from npm that isn't a piece, or an engine the game must already be on. */
|
|
25
|
+
export const NEED_KINDS = ["piece", "library", "engine"];
|
|
26
|
+
/** The kinds of value a setting holds. */
|
|
27
|
+
export const SETTING_VALUE_KINDS = ["number", "integer", "boolean", "choice", "text", "color"];
|
|
28
|
+
/** The kinds of hook: the piece tells the game something happened, or asks it before something does. */
|
|
29
|
+
export const HOOK_KINDS = ["event", "decision"];
|
|
30
|
+
/** Where a piece can come from. */
|
|
31
|
+
export const SOURCE_KINDS = ["folder", "tarball", "npm"];
|
|
32
|
+
/** A piece's statement, at the top of its folder. */
|
|
33
|
+
export const STATEMENT_PATH = "piece.json";
|
|
34
|
+
/** The statement as a module, for a piece's own code to read: always exactly what statementModuleText makes of piece.json. */
|
|
35
|
+
export const STATEMENT_MODULE_PATH = "piece.json.js";
|
|
36
|
+
/** The game's record of its pieces, in its pieces folder. */
|
|
37
|
+
export const RECORD_PATH = "pieces/pieces.json";
|
|
38
|
+
/** Where pieces go in a game, and where their game server files go: a game server on Zaisma imports only from its own folder. */
|
|
39
|
+
export const PIECES_FOLDER = "pieces";
|
|
40
|
+
export const SERVER_PIECES_FOLDER = "zaisma-server/pieces";
|
|
41
|
+
/** What a piece may hold and state; past these it's refused. */
|
|
42
|
+
export const PIECE_LIMITS = {
|
|
43
|
+
maximumFileCount: 5000,
|
|
44
|
+
maximumArchiveSizeBytes: 200_000_000,
|
|
45
|
+
maximumUnpackedSizeBytes: 500_000_000,
|
|
46
|
+
maximumStatementSizeBytes: 500_000,
|
|
47
|
+
maximumNeedCount: 50,
|
|
48
|
+
maximumSettingCount: 200,
|
|
49
|
+
maximumHookCount: 200,
|
|
50
|
+
maximumSummaryCharacterCount: 400,
|
|
51
|
+
maximumChoiceCount: 50,
|
|
52
|
+
maximumTextCharacterCount: 10_000,
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** Every field of a piece.json, of one of its needs, settings and hooks: each is there every time, and nothing else is. */
|
|
56
|
+
export const STATEMENT_FIELDS = ["statement_version_number", "name", "piece_version", "kind", "standard", "summary", "license", "entry_path", "server_entry_path", "file_paths", "server_file_paths", "needs", "settings", "hooks"];
|
|
57
|
+
export const NEED_FIELDS = ["name", "version_range", "kind"];
|
|
58
|
+
export const SETTING_FIELDS = ["name", "value_kind", "default_value", "minimum_number", "maximum_number", "maximum_character_count", "choices", "summary"];
|
|
59
|
+
export const HOOK_FIELDS = ["name", "hook_kind", "summary"];
|
|
60
|
+
const NAME_PATTERN = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
|
|
61
|
+
const MAXIMUM_NAME_CHARACTER_COUNT = 100;
|
|
62
|
+
const STATED_NAME_PATTERN = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;
|
|
63
|
+
const MAXIMUM_STATED_NAME_CHARACTER_COUNT = 64;
|
|
64
|
+
const CHOICE_PATTERN = /^[a-z0-9]+([_-][a-z0-9]+)*$/;
|
|
65
|
+
const COLOR_PATTERN = /^#[0-9a-f]{6}$/;
|
|
66
|
+
const LICENSE_PATTERN = /^[A-Za-z0-9.+()-]+( [A-Za-z0-9.+()-]+)*$/;
|
|
67
|
+
const VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z.-]+)?$/;
|
|
68
|
+
const FETCH_TIMEOUT_MS = 30000;
|
|
69
|
+
const NEWEST_COMMAND = "npx @zaisma/cli@latest";
|
|
70
|
+
|
|
71
|
+
/** A failure in the API's error shape (docs/NAMING.md, Errors). */
|
|
72
|
+
export class PiecesError extends Error {
|
|
73
|
+
constructor(code, { message, field = null, fix }) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.error = { code, message, field, fix, retry_after_sec: null };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const refuse = (code, details) => {
|
|
79
|
+
throw new PiecesError(code, details);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// ---- Versions and ranges (semver) ----
|
|
83
|
+
|
|
84
|
+
/** A version like "1.4.2" or "2.0.0-beta.1" in its parts, or null when it isn't one. */
|
|
85
|
+
export function parseVersion(text) {
|
|
86
|
+
const match = VERSION_PATTERN.exec(String(text).trim());
|
|
87
|
+
return match ? { majorNumber: Number(match[1]), minorNumber: Number(match[2]), patchNumber: Number(match[3]), prerelease: match[4] ? match[4].slice(1) : null } : null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Semver's order for two pre-release tags: numbers by size, words by letters, a number before a word, the shorter first. */
|
|
91
|
+
function comparePrereleases(first, second) {
|
|
92
|
+
const [firstParts, secondParts] = [first.split("."), second.split(".")];
|
|
93
|
+
for (let i = 0; i < Math.max(firstParts.length, secondParts.length); i++) {
|
|
94
|
+
if (firstParts[i] === undefined) return -1;
|
|
95
|
+
if (secondParts[i] === undefined) return 1;
|
|
96
|
+
const [isFirstNumber, isSecondNumber] = [/^\d+$/.test(firstParts[i]), /^\d+$/.test(secondParts[i])];
|
|
97
|
+
if (isFirstNumber && isSecondNumber && Number(firstParts[i]) !== Number(secondParts[i])) return Number(firstParts[i]) - Number(secondParts[i]);
|
|
98
|
+
if (isFirstNumber !== isSecondNumber) return isFirstNumber ? -1 : 1;
|
|
99
|
+
if (!isFirstNumber && firstParts[i] !== secondParts[i]) return firstParts[i] < secondParts[i] ? -1 : 1;
|
|
100
|
+
}
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Negative when first is older than second, positive when newer, 0 when the same. */
|
|
105
|
+
export function compareVersions(first, second) {
|
|
106
|
+
const [firstVersion, secondVersion] = [parseVersion(first), parseVersion(second)];
|
|
107
|
+
for (const part of ["majorNumber", "minorNumber", "patchNumber"]) if (firstVersion[part] !== secondVersion[part]) return firstVersion[part] - secondVersion[part];
|
|
108
|
+
if (firstVersion.prerelease === secondVersion.prerelease) return 0;
|
|
109
|
+
if (firstVersion.prerelease === null) return 1;
|
|
110
|
+
if (secondVersion.prerelease === null) return -1;
|
|
111
|
+
return comparePrereleases(firstVersion.prerelease, secondVersion.prerelease);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** One comparator like ">=1.2.0", "^1.2.0", "~1.2", "1.x" or "*" as the versions it lets through: [{ operator, version }], all of which must hold. */
|
|
115
|
+
function comparatorBounds(text) {
|
|
116
|
+
const match = /^(\^|~|>=|<=|>|<|=)?\s*v?(\*|x|X|\d+)(?:\.(\*|x|X|\d+))?(?:\.(\*|x|X|\d+))?(-[0-9A-Za-z.-]+)?$/.exec(text);
|
|
117
|
+
if (!match) return null;
|
|
118
|
+
const [, operator = "", majorText, minorText, patchText, prerelease = ""] = match;
|
|
119
|
+
const isWild = (part) => part === undefined || part === "*" || part === "x" || part === "X";
|
|
120
|
+
if (isWild(majorText)) return [];
|
|
121
|
+
const majorNumber = Number(majorText);
|
|
122
|
+
const minorNumber = isWild(minorText) ? null : Number(minorText);
|
|
123
|
+
const patchNumber = isWild(patchText) ? null : Number(patchText);
|
|
124
|
+
const floor = `${majorNumber}.${minorNumber ?? 0}.${patchNumber ?? 0}${prerelease}`;
|
|
125
|
+
const nextMajor = `${majorNumber + 1}.0.0`;
|
|
126
|
+
const nextMinor = `${majorNumber}.${(minorNumber ?? 0) + 1}.0`;
|
|
127
|
+
if (operator === "^") {
|
|
128
|
+
// ^ keeps the leftmost number that isn't zero.
|
|
129
|
+
const ceiling = majorNumber > 0 || minorNumber === null ? nextMajor : minorNumber > 0 || patchNumber === null ? nextMinor : `${majorNumber}.${minorNumber}.${patchNumber + 1}`;
|
|
130
|
+
return [{ operator: ">=", version: floor }, { operator: "<", version: ceiling }];
|
|
131
|
+
}
|
|
132
|
+
if (operator === "~") return [{ operator: ">=", version: floor }, { operator: "<", version: minorNumber === null ? nextMajor : nextMinor }];
|
|
133
|
+
if (operator === "" || operator === "=") {
|
|
134
|
+
if (minorNumber === null) return [{ operator: ">=", version: floor }, { operator: "<", version: nextMajor }];
|
|
135
|
+
if (patchNumber === null) return [{ operator: ">=", version: floor }, { operator: "<", version: nextMinor }];
|
|
136
|
+
return [{ operator: "=", version: floor }];
|
|
137
|
+
}
|
|
138
|
+
// A bare ">1" means past every 1.x, and "<=1" means up to the last 1.x.
|
|
139
|
+
if (operator === ">" && patchNumber === null) return [{ operator: ">=", version: minorNumber === null ? nextMajor : nextMinor }];
|
|
140
|
+
if (operator === "<=" && patchNumber === null) return [{ operator: "<", version: minorNumber === null ? nextMajor : nextMinor }];
|
|
141
|
+
return [{ operator, version: floor }];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A range like "^1.0.0", ">=0.160.0 <1.0.0" or "1.x || 2.x" as its alternatives, each a list of bounds; null when it isn't a range. */
|
|
145
|
+
export function parseRange(rangeText) {
|
|
146
|
+
if (typeof rangeText !== "string" || !rangeText.trim() || rangeText.length > 200) return null;
|
|
147
|
+
const alternatives = [];
|
|
148
|
+
for (const alternative of rangeText.split("||")) {
|
|
149
|
+
const bounds = [];
|
|
150
|
+
for (const word of alternative.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
|
|
151
|
+
const parsed = comparatorBounds(word);
|
|
152
|
+
if (!parsed) return null;
|
|
153
|
+
bounds.push(...parsed);
|
|
154
|
+
}
|
|
155
|
+
alternatives.push(bounds);
|
|
156
|
+
}
|
|
157
|
+
return alternatives;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Whether a version is one a range accepts. A pre-release version is accepted only by a range that names it exactly. */
|
|
161
|
+
export function satisfies(version, rangeText) {
|
|
162
|
+
const alternatives = parseRange(rangeText);
|
|
163
|
+
if (!alternatives || !parseVersion(version)) return false;
|
|
164
|
+
const isPrerelease = parseVersion(version).prerelease !== null;
|
|
165
|
+
return alternatives.some((bounds) => {
|
|
166
|
+
if (isPrerelease && !bounds.some((bound) => bound.version === version)) return false;
|
|
167
|
+
return bounds.every(({ operator, version: bound }) => {
|
|
168
|
+
const isNewer = compareVersions(version, bound) > 0;
|
|
169
|
+
const isSame = compareVersions(version, bound) === 0;
|
|
170
|
+
return operator === ">=" ? isNewer || isSame : operator === "<=" ? !isNewer : operator === ">" ? isNewer : operator === "<" ? !isNewer && !isSame : isSame;
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The newest of some versions that every one of the ranges accepts, or null. */
|
|
176
|
+
export function newestSatisfying(versions, ranges) {
|
|
177
|
+
const everyRange = Array.isArray(ranges) ? ranges : [ranges];
|
|
178
|
+
return versions.filter((version) => everyRange.every((rangeText) => satisfies(version, rangeText))).sort(compareVersions).pop() ?? null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ---- A piece's statement (piece.json) ----
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* A path inside a piece: forward slashes, no "..", never absolute. No part is hidden (".git", ".github") or
|
|
185
|
+
* node_modules either: a template's files land in the game's own folder, where those run without being asked.
|
|
186
|
+
*/
|
|
187
|
+
function isSafePath(path) {
|
|
188
|
+
return typeof path === "string" && path.length > 0 && path.length <= 200 && !path.startsWith("/") && !/^[A-Za-z]:/.test(path) && !path.includes("\\") && !/[\0-\x1f]/.test(path) && !path.split("/").some((part) => part === "" || part.startsWith(".") || part === "node_modules");
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** A stated name in a JavaScript piece's own style: jump_height_m is jumpHeightM. */
|
|
192
|
+
export function camelName(statedName) {
|
|
193
|
+
return statedName.replace(/_([a-z0-9])/g, (whole, letter) => letter.toUpperCase());
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const isPlainObject = (given) => given !== null && typeof given === "object" && !Array.isArray(given);
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* A piece.json, checked: every field there and of its shape, nothing unknown (docs/PIECES.md, "What a piece
|
|
200
|
+
* states"). Throws bad_piece_statement naming the field at fault, or piece_statement_newer for a statement
|
|
201
|
+
* written for a newer command than this one.
|
|
202
|
+
*/
|
|
203
|
+
export function readStatement(statementText, whereFrom = STATEMENT_PATH) {
|
|
204
|
+
const bad = (field, message, fix) => refuse("bad_piece_statement", { message: `${whereFrom}: ${message}`, field, fix });
|
|
205
|
+
let statement;
|
|
206
|
+
try {
|
|
207
|
+
statement = JSON.parse(statementText);
|
|
208
|
+
} catch {
|
|
209
|
+
statement = null;
|
|
210
|
+
}
|
|
211
|
+
if (!isPlainObject(statement)) bad(null, "it isn't a JSON object.", `A piece.json is an object with ${STATEMENT_FIELDS.join(", ")} (docs/PIECES.md).`);
|
|
212
|
+
const formatNumber = statement.statement_version_number;
|
|
213
|
+
if (!Number.isInteger(formatNumber) || formatNumber < 1) bad("statement_version_number", "its statement_version_number isn't a whole number from 1.", `Give ${STATEMENT_VERSION_NUMBER}: the format this piece.json is written in.`);
|
|
214
|
+
if (formatNumber > STATEMENT_VERSION_NUMBER) {
|
|
215
|
+
refuse("piece_statement_newer", { message: `${whereFrom} is written in format ${formatNumber}, and this command reads up to ${STATEMENT_VERSION_NUMBER}.`, field: "statement_version_number", fix: `Run the newest command: ${NEWEST_COMMAND} pieces.` });
|
|
216
|
+
}
|
|
217
|
+
for (const field of Object.keys(statement)) if (!STATEMENT_FIELDS.includes(field)) bad(field, `it has an unknown field "${field}".`, `A piece.json holds only: ${STATEMENT_FIELDS.join(", ")}.`);
|
|
218
|
+
for (const field of STATEMENT_FIELDS) if (!(field in statement)) bad(field, `it has no ${field}.`, `Give every field: ${STATEMENT_FIELDS.join(", ")}.`);
|
|
219
|
+
const isName = (name) => typeof name === "string" && NAME_PATTERN.test(name) && name.length <= MAXIMUM_NAME_CHARACTER_COUNT;
|
|
220
|
+
if (!isName(statement.name)) bad("name", `its name "${statement.name}" isn't a piece's name.`, 'Give a name as npm takes them, like "@studio/dash-move".');
|
|
221
|
+
if (!parseVersion(statement.piece_version)) bad("piece_version", `its piece_version "${statement.piece_version}" isn't a version.`, 'Give three numbers, like "1.0.0".');
|
|
222
|
+
if (!PIECE_KINDS.includes(statement.kind)) bad("kind", `its kind "${statement.kind}" isn't a kind of piece.`, `Use one of: ${PIECE_KINDS.join(", ")}.`);
|
|
223
|
+
if (!isName(statement.standard)) bad("standard", `its standard "${statement.standard}" isn't a standard's name.`, 'Name the standard the piece is built on, as its keeper holds it on npm, like "@studio/standard".');
|
|
224
|
+
const isSummary = (summary) => typeof summary === "string" && summary.trim().length > 0 && summary.length <= PIECE_LIMITS.maximumSummaryCharacterCount;
|
|
225
|
+
if (!isSummary(statement.summary)) bad("summary", `its summary is missing or over ${PIECE_LIMITS.maximumSummaryCharacterCount} characters.`, "Say in a sentence or two what the piece gives a game.");
|
|
226
|
+
if (typeof statement.license !== "string" || !LICENSE_PATTERN.test(statement.license) || statement.license.length > 100) bad("license", `its license "${statement.license}" isn't a licence's name.`, 'Name the licence the piece is under, as SPDX does, like "MIT" or "Apache-2.0".');
|
|
227
|
+
for (const field of ["file_paths", "server_file_paths"]) {
|
|
228
|
+
const paths = statement[field];
|
|
229
|
+
if (!Array.isArray(paths) || !paths.every(isSafePath) || new Set(paths).size !== paths.length) bad(field, `its ${field} isn't a list of the piece's own files.`, 'List each file once by its path inside the piece, like "index.js" or "sounds/step.ogg".');
|
|
230
|
+
if (paths.includes(STATEMENT_PATH)) bad(field, `its ${field} lists ${STATEMENT_PATH}.`, `Take it out: a piece's ${STATEMENT_PATH} always comes with it.`);
|
|
231
|
+
}
|
|
232
|
+
if (statement.file_paths.length + statement.server_file_paths.length > PIECE_LIMITS.maximumFileCount) bad("file_paths", `it lists more than ${PIECE_LIMITS.maximumFileCount} files.`, "Split the piece, or pack small files together.");
|
|
233
|
+
if (!statement.file_paths.length && !statement.server_file_paths.length) bad("file_paths", "it lists no files.", "List the piece's files in file_paths, and its game server files in server_file_paths.");
|
|
234
|
+
for (const [entryField, pathsField] of [["entry_path", "file_paths"], ["server_entry_path", "server_file_paths"]]) {
|
|
235
|
+
const [entryPath, paths] = [statement[entryField], statement[pathsField]];
|
|
236
|
+
if (!paths.length && entryPath !== null) bad(entryField, `its ${entryField} names a file, and its ${pathsField} is empty.`, `Give null, or list the file in ${pathsField}.`);
|
|
237
|
+
if (paths.length && !paths.includes(entryPath)) bad(entryField, `its ${entryField} isn't one of its ${pathsField}.`, `Name the file ${entryField === "entry_path" ? "a game" : "a game server"} starts from, one of ${pathsField}.`);
|
|
238
|
+
}
|
|
239
|
+
if (statement.kind === "template") {
|
|
240
|
+
// A template's files become the game's own, its game server's among them, so there's nothing to open or keep apart.
|
|
241
|
+
if (statement.server_file_paths.length) bad("server_file_paths", "it's a template with server_file_paths.", "A template's files are copied into the game's own folder: list them all in file_paths, its game server's under zaisma-server/.");
|
|
242
|
+
if (statement.file_paths.some((path) => path === RECORD_PATH || path.startsWith(`${PIECES_FOLDER}/`) || path.startsWith(`${SERVER_PIECES_FOLDER}/`))) bad("file_paths", `it's a template that writes into ${PIECES_FOLDER}/.`, `Pieces a template uses go in its needs; ${PIECES_FOLDER}/ and ${SERVER_PIECES_FOLDER}/ hold only what the command adds.`);
|
|
243
|
+
if (!Array.isArray(statement.settings) || !Array.isArray(statement.hooks) || statement.settings.length || statement.hooks.length) bad("settings", "it's a template with settings or hooks.", "Give empty lists: a template is copied once and is then the game's own to change.");
|
|
244
|
+
}
|
|
245
|
+
if (!Array.isArray(statement.needs) || statement.needs.length > PIECE_LIMITS.maximumNeedCount) bad("needs", `its needs isn't a list of at most ${PIECE_LIMITS.maximumNeedCount}.`, "Give a list, empty when the piece needs nothing.");
|
|
246
|
+
for (const need of statement.needs) {
|
|
247
|
+
if (!isPlainObject(need)) bad("needs", "one of its needs isn't an object.", `Each need is { ${NEED_FIELDS.join(", ")} }.`);
|
|
248
|
+
for (const field of Object.keys(need)) if (!NEED_FIELDS.includes(field)) bad("needs", `a need has an unknown field "${field}".`, `A need holds only: ${NEED_FIELDS.join(", ")}.`);
|
|
249
|
+
if (!isName(need.name)) bad("needs", `a need's name "${need.name}" isn't a name.`, "Name the piece or library needed as npm names it, or the engine in lowercase.");
|
|
250
|
+
if (!parseRange(need.version_range)) bad("needs", `the need for ${need.name} has a version_range "${need.version_range}" that isn't a range.`, 'Give the versions accepted, like "^1.0.0" or ">=0.160.0 <1.0.0".');
|
|
251
|
+
if (!NEED_KINDS.includes(need.kind)) bad("needs", `the need for ${need.name} has kind "${need.kind}".`, `Use one of: ${NEED_KINDS.join(", ")}.`);
|
|
252
|
+
}
|
|
253
|
+
if (new Set(statement.needs.map((need) => need.name)).size !== statement.needs.length) bad("needs", "it needs the same thing twice.", "List each need once.");
|
|
254
|
+
if (statement.needs.some((need) => need.name === statement.name)) bad("needs", "it needs itself.", "Take the piece's own name out of its needs.");
|
|
255
|
+
if (!Array.isArray(statement.settings) || statement.settings.length > PIECE_LIMITS.maximumSettingCount) bad("settings", `its settings isn't a list of at most ${PIECE_LIMITS.maximumSettingCount}.`, "Give a list, empty when the piece has no settings.");
|
|
256
|
+
const isStatedName = (name) => typeof name === "string" && STATED_NAME_PATTERN.test(name) && name.length <= MAXIMUM_STATED_NAME_CHARACTER_COUNT;
|
|
257
|
+
for (const setting of statement.settings) {
|
|
258
|
+
if (!isPlainObject(setting)) bad("settings", "one of its settings isn't an object.", `Each setting is { ${SETTING_FIELDS.join(", ")} }.`);
|
|
259
|
+
const badSetting = (message, fix) => bad("settings", `the setting ${setting.name}: ${message}`, fix);
|
|
260
|
+
for (const field of Object.keys(setting)) if (!SETTING_FIELDS.includes(field)) bad("settings", `a setting has an unknown field "${field}".`, `A setting holds only: ${SETTING_FIELDS.join(", ")}.`);
|
|
261
|
+
for (const field of SETTING_FIELDS) if (!(field in setting)) bad("settings", `a setting has no ${field}.`, `Give every field, null where it doesn't apply: ${SETTING_FIELDS.join(", ")}.`);
|
|
262
|
+
if (!isStatedName(setting.name)) bad("settings", `a setting's name "${setting.name}" isn't a name.`, 'Name it in lowercase with underscores, saying what it holds and its unit, like "jump_height_m" (docs/NAMING.md).');
|
|
263
|
+
if (!SETTING_VALUE_KINDS.includes(setting.value_kind)) badSetting(`its value_kind "${setting.value_kind}" isn't a kind of value.`, `Use one of: ${SETTING_VALUE_KINDS.join(", ")}.`);
|
|
264
|
+
if (!isSummary(setting.summary)) badSetting(`its summary is missing or over ${PIECE_LIMITS.maximumSummaryCharacterCount} characters.`, "Say in a sentence what the setting changes.");
|
|
265
|
+
const isNumeric = setting.value_kind === "number" || setting.value_kind === "integer";
|
|
266
|
+
const isNumber = (given) => typeof given === "number" && Number.isFinite(given) && (setting.value_kind !== "integer" || Number.isInteger(given));
|
|
267
|
+
if (isNumeric) {
|
|
268
|
+
if (![setting.default_value, setting.minimum_number, setting.maximum_number].every(isNumber)) badSetting(`its default_value, minimum_number and maximum_number aren't all ${setting.value_kind === "integer" ? "whole numbers" : "numbers"}.`, "Give all three: every number has a range.");
|
|
269
|
+
if (setting.minimum_number > setting.default_value || setting.default_value > setting.maximum_number) badSetting("its default_value isn't between its minimum_number and maximum_number.", "Give a default within the range.");
|
|
270
|
+
} else if (setting.minimum_number !== null || setting.maximum_number !== null) badSetting(`it's a ${setting.value_kind} with a minimum_number or maximum_number.`, "Give null for both: only a number or an integer has a range.");
|
|
271
|
+
if (setting.value_kind === "boolean" && typeof setting.default_value !== "boolean") badSetting("its default_value isn't true or false.", "Give true or false.");
|
|
272
|
+
if (setting.value_kind === "color" && (typeof setting.default_value !== "string" || !COLOR_PATTERN.test(setting.default_value))) badSetting("its default_value isn't a colour.", 'Give six hex digits in lowercase, like "#3fa9f5".');
|
|
273
|
+
if (setting.value_kind === "choice") {
|
|
274
|
+
const choices = setting.choices;
|
|
275
|
+
if (!Array.isArray(choices) || choices.length < 2 || choices.length > PIECE_LIMITS.maximumChoiceCount || !choices.every((choice) => typeof choice === "string" && CHOICE_PATTERN.test(choice) && choice.length <= MAXIMUM_STATED_NAME_CHARACTER_COUNT) || new Set(choices).size !== choices.length) badSetting(`its choices isn't a list of 2 to ${PIECE_LIMITS.maximumChoiceCount} different lowercase words.`, 'List each choice once, like ["low", "medium", "high"].');
|
|
276
|
+
if (!choices.includes(setting.default_value)) badSetting("its default_value isn't one of its choices.", "Give one of the choices.");
|
|
277
|
+
} else if (setting.choices !== null) badSetting(`it's a ${setting.value_kind} with choices.`, "Give null: only a choice has choices.");
|
|
278
|
+
if (setting.value_kind === "text") {
|
|
279
|
+
if (!Number.isInteger(setting.maximum_character_count) || setting.maximum_character_count < 1 || setting.maximum_character_count > PIECE_LIMITS.maximumTextCharacterCount) badSetting(`its maximum_character_count isn't a whole number from 1 to ${PIECE_LIMITS.maximumTextCharacterCount}.`, "Say how long the text may be.");
|
|
280
|
+
if (typeof setting.default_value !== "string" || setting.default_value.length > setting.maximum_character_count) badSetting("its default_value isn't text within its maximum_character_count.", "Give text that fits.");
|
|
281
|
+
} else if (setting.maximum_character_count !== null) badSetting(`it's a ${setting.value_kind} with a maximum_character_count.`, "Give null: only text has a length.");
|
|
282
|
+
}
|
|
283
|
+
for (const [field, entries] of [["settings", statement.settings], ["hooks", statement.hooks]]) {
|
|
284
|
+
if (!Array.isArray(entries)) continue;
|
|
285
|
+
// Two names that read the same in a JavaScript piece (jump_2x and jump2x) would be one there.
|
|
286
|
+
const names = entries.map((entry) => (isPlainObject(entry) && typeof entry.name === "string" ? camelName(entry.name) : entry));
|
|
287
|
+
if (new Set(names).size !== names.length) bad(field, `it has two ${field} of the same name.`, `Name each of its ${field} once.`);
|
|
288
|
+
}
|
|
289
|
+
if (!Array.isArray(statement.hooks) || statement.hooks.length > PIECE_LIMITS.maximumHookCount) bad("hooks", `its hooks isn't a list of at most ${PIECE_LIMITS.maximumHookCount}.`, "Give a list, empty when the piece has no hooks.");
|
|
290
|
+
for (const hook of statement.hooks) {
|
|
291
|
+
if (!isPlainObject(hook)) bad("hooks", "one of its hooks isn't an object.", `Each hook is { ${HOOK_FIELDS.join(", ")} }.`);
|
|
292
|
+
for (const field of Object.keys(hook)) if (!HOOK_FIELDS.includes(field)) bad("hooks", `a hook has an unknown field "${field}".`, `A hook holds only: ${HOOK_FIELDS.join(", ")}.`);
|
|
293
|
+
if (!isStatedName(hook.name)) bad("hooks", `a hook's name "${hook.name}" isn't a name.`, 'Name it in lowercase with underscores, like "before_jump" or "landed".');
|
|
294
|
+
if (!HOOK_KINDS.includes(hook.hook_kind)) bad("hooks", `the hook ${hook.name} has hook_kind "${hook.hook_kind}".`, `Use one of: ${HOOK_KINDS.join(", ")}.`);
|
|
295
|
+
if (!isSummary(hook.summary)) bad("hooks", `the hook ${hook.name} has a summary that's missing or over ${PIECE_LIMITS.maximumSummaryCharacterCount} characters.`, "Say in a sentence when it's called and what the game can do there.");
|
|
296
|
+
}
|
|
297
|
+
return statement;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Whether a piece.json.js is its piece.json as a module, whatever line endings a checkout gave it. */
|
|
301
|
+
const isStatementModule = (moduleBytes, statementText) => moduleBytes.toString("utf8").replace(/\r\n/g, "\n") === statementModuleText(statementText);
|
|
302
|
+
|
|
303
|
+
/** piece.json as a module (piece.json.js), so a piece's own code reads the one statement and never a second copy of it. */
|
|
304
|
+
export function statementModuleText(statementText) {
|
|
305
|
+
return `// This piece's statement, piece.json, as a module for its own code to read. "zaisma pieces check --fix" writes it: never edit it.\nexport default ${JSON.stringify(JSON.parse(statementText), null, 2)};\n`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ---- What adding a piece brings ----
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* One thing a game can hold in its pieces folder, as the rest of this file passes it round: a piece (with its
|
|
312
|
+
* statement) or a library that isn't a piece (kind "library", no statement). files is { path: bytes } when its
|
|
313
|
+
* files were read, and its game server's files are among them under the same paths.
|
|
314
|
+
*/
|
|
315
|
+
function unitOf({ statement = null, library = null, files = null, sourceKind, source = null }) {
|
|
316
|
+
if (statement) return { name: statement.name, version: statement.piece_version, kind: statement.kind, needs: statement.needs, statement, library: null, files, sourceKind, source };
|
|
317
|
+
return { name: library.name, version: library.library_version, kind: "library", needs: [], statement: null, library, files, sourceKind, source };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const isNeedBrought = (need) => need.kind !== "engine";
|
|
321
|
+
const named = (unit) => `${unit.name} ${unit.version}`;
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Works out what adding a piece does to a game, and writes nothing.
|
|
325
|
+
*
|
|
326
|
+
* piece is the unit being added. had is what the game has, by name ({ name: unit }). gameLibraries is what the
|
|
327
|
+
* game's own package.json brings ({ three: "0.170.0" }). find(name, needKind, ranges) looks a need up at its
|
|
328
|
+
* source and answers the newest unit every range accepts, or null.
|
|
329
|
+
*
|
|
330
|
+
* Answers { added: [units, each after what it needs, the piece itself last], keptNames: [names left as they
|
|
331
|
+
* are], engineNeeds: [{ name, version_range, needed_by_name }] }. Throws piece_already_added,
|
|
332
|
+
* piece_version_clash or piece_need_unmet.
|
|
333
|
+
*/
|
|
334
|
+
export async function planAdd({ piece, had = {}, gameLibraries = {}, find }) {
|
|
335
|
+
if (had[piece.name]) {
|
|
336
|
+
if (had[piece.name].version === piece.version) return { added: [], keptNames: [piece.name], engineNeeds: [] };
|
|
337
|
+
refuse("piece_already_added", { message: `The game already has ${named(had[piece.name])}, and this is ${piece.version}.`, field: "source", fix: `A piece moves to another version only on your word: zaisma pieces update ${piece.name}.` });
|
|
338
|
+
}
|
|
339
|
+
const clash = (need, neededBy, holderLine, waysOut) => refuse("piece_version_clash", { message: `${named(neededBy)} needs ${need.name} ${need.version_range}, and ${holderLine}.`, field: need.name, fix: `Nothing was changed. ${waysOut}` });
|
|
340
|
+
// Every range met for a name, over every pass: a pass that finds a version one of them refuses starts again with all of them known.
|
|
341
|
+
const knownRanges = new Map();
|
|
342
|
+
const found = new Map();
|
|
343
|
+
for (;;) {
|
|
344
|
+
const added = new Map();
|
|
345
|
+
const order = [];
|
|
346
|
+
const keptNames = new Set();
|
|
347
|
+
const engineNeeds = [];
|
|
348
|
+
let isStartingAgain = false;
|
|
349
|
+
const visit = async (unit) => {
|
|
350
|
+
for (const need of unit.needs) {
|
|
351
|
+
if (isStartingAgain) return;
|
|
352
|
+
if (!isNeedBrought(need)) {
|
|
353
|
+
engineNeeds.push({ name: need.name, version_range: need.version_range, needed_by_name: unit.name });
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
const ranges = knownRanges.get(need.name) ?? knownRanges.set(need.name, []).get(need.name);
|
|
357
|
+
const isRangeNew = !ranges.some((known) => known.need.version_range === need.version_range);
|
|
358
|
+
if (isRangeNew) ranges.push({ need, neededBy: unit });
|
|
359
|
+
if (need.name === piece.name) {
|
|
360
|
+
if (!satisfies(piece.version, need.version_range)) clash(need, unit, `this is ${named(piece)}`, `Add a version of ${piece.name} that ${unit.name} accepts, or a version of ${unit.name} that accepts ${named(piece)}.`);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const existing = had[need.name];
|
|
364
|
+
if (existing) {
|
|
365
|
+
const isLibraryNeed = need.kind === "library";
|
|
366
|
+
if ((existing.kind === "library") !== isLibraryNeed) refuse("piece_need_unmet", { message: `${named(unit)} needs ${need.name} as a ${need.kind}, and the game has ${named(existing)} as a ${existing.kind === "library" ? "library" : "piece"}.`, field: need.name, fix: `Nothing was changed. Tell ${unit.name}'s maker: a need's kind says whether it's a piece or a library.` });
|
|
367
|
+
if (!satisfies(existing.version, need.version_range)) clash(need, unit, `the game has ${named(existing)}`, `Two ways out: move the game's ${need.name} to a version both accept (zaisma pieces update ${need.name} --version "${need.version_range}"), or use a version of ${unit.name} that accepts ${named(existing)}.`);
|
|
368
|
+
keptNames.add(need.name);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (need.kind === "library" && gameLibraries[need.name] !== undefined) {
|
|
372
|
+
// The game brings this library itself (its package.json): it's used as it is, or it's a clash.
|
|
373
|
+
if (!satisfies(gameLibraries[need.name], need.version_range)) clash(need, unit, `the game's own package.json has ${need.name} ${gameLibraries[need.name]}`, `Two ways out: move ${need.name} in the game's package.json to a version within ${need.version_range}, or use a version of ${unit.name} that accepts ${need.name} ${gameLibraries[need.name]}.`);
|
|
374
|
+
keptNames.add(need.name);
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
const coming = added.get(need.name);
|
|
378
|
+
if (coming) {
|
|
379
|
+
if (satisfies(coming.version, need.version_range)) continue;
|
|
380
|
+
// Chosen before this range was known: start again, choosing with it.
|
|
381
|
+
isStartingAgain = true;
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const everyRange = ranges.map((known) => known.need.version_range);
|
|
385
|
+
const findKey = `${need.name}\n${everyRange.join("\n")}`;
|
|
386
|
+
if (!found.has(findKey)) found.set(findKey, await find(need.name, need.kind, everyRange));
|
|
387
|
+
const chosen = found.get(findKey);
|
|
388
|
+
if (!chosen) {
|
|
389
|
+
const other = ranges.find((known) => known.need.version_range !== need.version_range);
|
|
390
|
+
if (other) clash(need, unit, `${named(other.neededBy)} needs ${need.name} ${other.need.version_range}: no version of ${need.name} fits both`, `Use a version of ${unit.name} or of ${other.neededBy.name} whose needs overlap, or tell their makers.`);
|
|
391
|
+
refuse("piece_need_unmet", { message: `${named(unit)} needs ${need.name} ${need.version_range}, and none was found.`, field: need.name, fix: `Nothing was changed. Add ${need.name} first from where it's published (zaisma pieces add <its folder or .tgz>), then run this again.` });
|
|
392
|
+
}
|
|
393
|
+
if (chosen.kind === "template") refuse("piece_need_unmet", { message: `${named(unit)} needs ${need.name}, which is a template.`, field: need.name, fix: `Nothing was changed. A template is copied into a game once and is never needed by a piece: tell ${unit.name}'s maker.` });
|
|
394
|
+
if ((chosen.kind === "library") !== (need.kind === "library")) refuse("piece_need_unmet", { message: `${named(unit)} needs ${need.name} as a ${need.kind}, and what was found is a ${chosen.kind === "library" ? "library" : "piece"}.`, field: need.name, fix: `Nothing was changed. Tell ${unit.name}'s maker: a need's kind says whether it's a piece or a library.` });
|
|
395
|
+
added.set(need.name, chosen);
|
|
396
|
+
await visit(chosen);
|
|
397
|
+
if (isStartingAgain) return;
|
|
398
|
+
order.push(chosen);
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
await visit(piece);
|
|
402
|
+
if (!isStartingAgain) return { added: [...order, piece], keptNames: [...keptNames], engineNeeds };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** The pieces in a game that need one of its names, each with the range it accepts. A template is the game's own code once copied, so it holds nothing. */
|
|
407
|
+
export function needersOf(name, had) {
|
|
408
|
+
const needers = [];
|
|
409
|
+
for (const holder of Object.values(had)) {
|
|
410
|
+
if (holder.kind === "template" || holder.name === name) continue;
|
|
411
|
+
const need = holder.needs.find((entry) => entry.name === name && isNeedBrought(entry));
|
|
412
|
+
if (need) needers.push({ holder, need });
|
|
413
|
+
}
|
|
414
|
+
return needers;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Whether the pieces a game has would accept another version of one of them: throws piece_version_clash naming the first that wouldn't. */
|
|
418
|
+
export function checkUpdateFits({ name, nextVersion, had }) {
|
|
419
|
+
for (const { holder, need } of needersOf(name, had)) {
|
|
420
|
+
if (satisfies(nextVersion, need.version_range)) continue;
|
|
421
|
+
refuse("piece_version_clash", {
|
|
422
|
+
message: `${named(holder)} needs ${name} ${need.version_range}, and this would move ${name} to ${nextVersion}.`,
|
|
423
|
+
field: name,
|
|
424
|
+
fix: `Nothing was changed. Two ways out: update ${holder.name} first to a version that accepts ${name} ${nextVersion}, or pick a version of ${name} within ${need.version_range} (--version "${need.version_range}").`,
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ---- Reading a piece from where it is ----
|
|
430
|
+
|
|
431
|
+
const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
432
|
+
|
|
433
|
+
/** A text file's bytes with every line ending as "\n", so a checkout that turns them into "\r\n" (Git on Windows) isn't an edit. A file with a zero byte isn't text. */
|
|
434
|
+
const withPlainLineEndings = (bytes) => (bytes.includes(0) || !bytes.includes(13) ? bytes : Buffer.from(Buffer.from(bytes).toString("latin1").replace(/\r\n/g, "\n"), "latin1"));
|
|
435
|
+
|
|
436
|
+
/** One hash for a set of files: any file changed, added or removed changes it. files is { path: bytes }. */
|
|
437
|
+
export function filesHash(files) {
|
|
438
|
+
const lines = Object.keys(files).sort().map((path) => `${path}\0${sha256Hex(withPlainLineEndings(files[path]))}`);
|
|
439
|
+
return sha256Hex(lines.join("\n"));
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** The files of a .tar's bytes, by path. Only plain files (a link is left out); a path that would leave the folder is refused. */
|
|
443
|
+
export function readTar(bytes) {
|
|
444
|
+
const files = {};
|
|
445
|
+
const untrusted = (message) => refuse("bad_piece_source", { message, field: "source", fix: "Don't use this archive. A piece's files all sit inside its own folder." });
|
|
446
|
+
let headerStartBytes = 0;
|
|
447
|
+
let longName = null;
|
|
448
|
+
let fileCount = 0;
|
|
449
|
+
while (headerStartBytes + 512 <= bytes.length) {
|
|
450
|
+
const header = bytes.subarray(headerStartBytes, headerStartBytes + 512);
|
|
451
|
+
if (header.every((byte) => byte === 0)) break;
|
|
452
|
+
const text = (start, fieldSizeBytes) => {
|
|
453
|
+
const end = header.indexOf(0, start);
|
|
454
|
+
return Buffer.from(header.subarray(start, end === -1 || end > start + fieldSizeBytes ? start + fieldSizeBytes : end)).toString("utf8");
|
|
455
|
+
};
|
|
456
|
+
const sizeBytes = parseInt(text(124, 12).trim() || "0", 8);
|
|
457
|
+
if (!Number.isFinite(sizeBytes) || sizeBytes < 0 || headerStartBytes + 512 + sizeBytes > bytes.length) untrusted("The archive is cut short or damaged.");
|
|
458
|
+
const entryKind = String.fromCharCode(header[156] || 48);
|
|
459
|
+
const prefix = text(345, 155);
|
|
460
|
+
const name = longName ?? (prefix ? `${prefix}/${text(0, 100)}` : text(0, 100));
|
|
461
|
+
const body = bytes.subarray(headerStartBytes + 512, headerStartBytes + 512 + sizeBytes);
|
|
462
|
+
longName = null;
|
|
463
|
+
if (entryKind === "L") longName = Buffer.from(body).toString("utf8").replace(/\0+$/, "");
|
|
464
|
+
else if (entryKind === "x") {
|
|
465
|
+
// A pax header: lines of "<length> key=value\n"; path names the next entry when its name is too long for the header.
|
|
466
|
+
const path = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(Buffer.from(body).toString("utf8"));
|
|
467
|
+
if (path) longName = path[1];
|
|
468
|
+
} else if (entryKind === "0" || entryKind === "\0") {
|
|
469
|
+
// Only a path that would leave the archive's folder is refused here; a hidden file is npm's own business until a piece lists it.
|
|
470
|
+
if (name.startsWith("/") || /^[A-Za-z]:/.test(name) || name.includes("\\") || name.split("/").includes("..")) untrusted(`The archive holds a file outside itself: "${name}".`);
|
|
471
|
+
if (++fileCount > PIECE_LIMITS.maximumFileCount * 2) untrusted(`The archive holds more than ${PIECE_LIMITS.maximumFileCount * 2} files.`);
|
|
472
|
+
files[name] = Buffer.from(body);
|
|
473
|
+
}
|
|
474
|
+
headerStartBytes += 512 + Math.ceil(sizeBytes / 512) * 512;
|
|
475
|
+
}
|
|
476
|
+
return files;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** A read piece as a unit: its statement and the files it lists. allFiles is everything found beside its piece.json, by path. */
|
|
480
|
+
function pieceFrom(allFiles, sourceKind, source, whereFrom) {
|
|
481
|
+
const statementBytes = allFiles[STATEMENT_PATH];
|
|
482
|
+
if (!statementBytes) refuse("bad_piece_source", { message: `${whereFrom} has no ${STATEMENT_PATH}, so it isn't a piece.`, field: "source", fix: `Give a piece's folder, its .tgz, or its name on npm. A piece has a ${STATEMENT_PATH} at its top (docs/PIECES.md).` });
|
|
483
|
+
if (statementBytes.length > PIECE_LIMITS.maximumStatementSizeBytes) refuse("bad_piece_statement", { message: `${whereFrom}'s ${STATEMENT_PATH} is over ${PIECE_LIMITS.maximumStatementSizeBytes} bytes.`, field: null, fix: "A statement says what a piece is and needs; anything longer belongs in its README." });
|
|
484
|
+
const statementText = statementBytes.toString("utf8");
|
|
485
|
+
const statement = readStatement(statementText, `${whereFrom}'s ${STATEMENT_PATH}`);
|
|
486
|
+
const bad = (field, message, fix) => refuse("bad_piece_statement", { message: `${whereFrom}: ${message}`, field, fix });
|
|
487
|
+
const files = { [STATEMENT_PATH]: statementBytes };
|
|
488
|
+
for (const path of new Set([...statement.file_paths, ...statement.server_file_paths])) {
|
|
489
|
+
if (!allFiles[path]) bad(statement.file_paths.includes(path) ? "file_paths" : "server_file_paths", `its ${STATEMENT_PATH} lists ${path}, which isn't there.`, "List only files the piece holds.");
|
|
490
|
+
files[path] = allFiles[path];
|
|
491
|
+
}
|
|
492
|
+
if (files[STATEMENT_MODULE_PATH] && !isStatementModule(files[STATEMENT_MODULE_PATH], statementText)) bad(null, `its ${STATEMENT_MODULE_PATH} isn't its ${STATEMENT_PATH}, so its code would read another statement than the one it gives.`, `Its maker runs: zaisma pieces check <the piece's folder> --fix.`);
|
|
493
|
+
// A piece published on npm is found there by its package's name and version, so the two can't differ.
|
|
494
|
+
if (allFiles["package.json"]) {
|
|
495
|
+
let packageJson = null;
|
|
496
|
+
try {
|
|
497
|
+
packageJson = JSON.parse(allFiles["package.json"].toString("utf8"));
|
|
498
|
+
} catch {
|
|
499
|
+
// Falls through to the refusal.
|
|
500
|
+
}
|
|
501
|
+
if (packageJson?.name !== statement.name) bad("name", `its ${STATEMENT_PATH} says ${statement.name}, and its package.json says ${packageJson?.name}.`, "Give both the same name.");
|
|
502
|
+
if (packageJson?.version !== statement.piece_version) bad("piece_version", `its ${STATEMENT_PATH} says ${statement.piece_version}, and its package.json says ${packageJson?.version}.`, "Give both the same version.");
|
|
503
|
+
}
|
|
504
|
+
return unitOf({ statement, files, sourceKind, source });
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** The files asked for in a folder, by path; a missing one is left out, and a link is refused. */
|
|
508
|
+
async function readListedFiles(folder, paths) {
|
|
509
|
+
const files = {};
|
|
510
|
+
for (const path of paths) {
|
|
511
|
+
const full = join(folder, ...path.split("/"));
|
|
512
|
+
const found = await lstat(full).catch(() => null);
|
|
513
|
+
if (found?.isSymbolicLink()) refuse("bad_piece_source", { message: `${full} is a link to another file.`, field: "source", fix: "Put the file itself in the piece: a link could point anywhere on this computer." });
|
|
514
|
+
if (found?.isFile()) files[path] = await readFile(full);
|
|
515
|
+
}
|
|
516
|
+
return files;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async function readPieceFolder(folder) {
|
|
520
|
+
const statementBytes = (await readListedFiles(folder, [STATEMENT_PATH]))[STATEMENT_PATH];
|
|
521
|
+
if (!statementBytes) refuse("bad_piece_source", { message: `${folder} has no ${STATEMENT_PATH}, so it isn't a piece.`, field: "source", fix: `Give a piece's folder, its .tgz, or its name on npm. A piece has a ${STATEMENT_PATH} at its top (docs/PIECES.md).` });
|
|
522
|
+
const statement = readStatement(statementBytes.toString("utf8"), `${folder}'s ${STATEMENT_PATH}`);
|
|
523
|
+
const files = await readListedFiles(folder, [STATEMENT_PATH, "package.json", ...statement.file_paths, ...statement.server_file_paths]);
|
|
524
|
+
return pieceFrom(files, "folder", resolve(folder), folder);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** Every file in a .tgz, by path. npm packs a package's files under "package/". */
|
|
528
|
+
function readTarball(tarballBytes, whereFrom) {
|
|
529
|
+
if (tarballBytes.length > PIECE_LIMITS.maximumArchiveSizeBytes) refuse("bad_piece_source", { message: `${whereFrom} is over ${PIECE_LIMITS.maximumArchiveSizeBytes / 1_000_000} MB.`, field: "source", fix: "A piece that big isn't one this command adds." });
|
|
530
|
+
let tar;
|
|
531
|
+
try {
|
|
532
|
+
tar = gunzipSync(tarballBytes, { maxOutputLength: PIECE_LIMITS.maximumUnpackedSizeBytes });
|
|
533
|
+
} catch {
|
|
534
|
+
refuse("bad_piece_source", { message: `${whereFrom} isn't a .tgz archive, or unpacks to over ${PIECE_LIMITS.maximumUnpackedSizeBytes / 1_000_000} MB.`, field: "source", fix: "Give a piece's folder, the .tgz that npm pack makes of it, or its name on npm." });
|
|
535
|
+
}
|
|
536
|
+
const packed = readTar(tar);
|
|
537
|
+
const top = Object.keys(packed).every((path) => path.startsWith("package/")) ? "package/" : "";
|
|
538
|
+
return Object.fromEntries(Object.entries(packed).map(([path, bytes]) => [path.slice(top.length), bytes]));
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
async function fetchBytes(url, accept) {
|
|
542
|
+
let response;
|
|
543
|
+
try {
|
|
544
|
+
response = await fetch(url, { headers: accept ? { accept } : {}, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
|
545
|
+
} catch {
|
|
546
|
+
response = null;
|
|
547
|
+
}
|
|
548
|
+
if (response?.status === 404) return null;
|
|
549
|
+
if (!response?.ok) refuse("piece_source_unreachable", { message: `${url} couldn't be reached.`, field: "source", fix: "Check the connection and run it again; nothing was changed." });
|
|
550
|
+
return Buffer.from(await response.arrayBuffer());
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* npm, as one command run reads it: each name's versions are asked for once. versionsOf(name) answers
|
|
555
|
+
* { version: { tarballUrl, integrity } }, or null when npm has no such name; archiveOf(name, ranges) the files of
|
|
556
|
+
* the newest version every range accepts, or null.
|
|
557
|
+
*/
|
|
558
|
+
function npmReader() {
|
|
559
|
+
// The developer's own registry when npm is set to one, as the command's check for a newer version of itself reads it.
|
|
560
|
+
const registryUrl = (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
|
|
561
|
+
const asked = new Map();
|
|
562
|
+
const versionsOf = (name) => {
|
|
563
|
+
if (!asked.has(name)) {
|
|
564
|
+
asked.set(
|
|
565
|
+
name,
|
|
566
|
+
fetchBytes(`${registryUrl}/${name.replace("/", "%2F")}`, "application/vnd.npm.install-v1+json").then((bytes) => {
|
|
567
|
+
if (!bytes) return null;
|
|
568
|
+
const packument = JSON.parse(bytes.toString("utf8"));
|
|
569
|
+
return Object.fromEntries(Object.entries(packument.versions ?? {}).map(([version, entry]) => [version, { tarballUrl: entry.dist.tarball, integrity: entry.dist.integrity ?? null }]));
|
|
570
|
+
}),
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
return asked.get(name);
|
|
574
|
+
};
|
|
575
|
+
const archiveOf = async (name, ranges) => {
|
|
576
|
+
const versions = await versionsOf(name);
|
|
577
|
+
const version = versions && newestSatisfying(Object.keys(versions).filter(parseVersion), ranges);
|
|
578
|
+
if (!version) return null;
|
|
579
|
+
const tarballBytes = await fetchBytes(versions[version].tarballUrl);
|
|
580
|
+
if (!tarballBytes) return null;
|
|
581
|
+
const integrity = versions[version].integrity;
|
|
582
|
+
// npm's own hash of the archive: what was published is what's unpacked.
|
|
583
|
+
if (integrity?.startsWith("sha512-") && createHash("sha512").update(tarballBytes).digest("base64") !== integrity.slice(7)) {
|
|
584
|
+
refuse("bad_piece_source", { message: `${name} ${version}'s archive isn't the one npm lists: its hash differs.`, field: "source", fix: "Nothing was changed. Run it again; if it keeps happening, don't use this version." });
|
|
585
|
+
}
|
|
586
|
+
return { version, allFiles: readTarball(tarballBytes, `${name} ${version} on npm`), whereFrom: `${name} ${version} on npm` };
|
|
587
|
+
};
|
|
588
|
+
return { versionsOf, archiveOf };
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** The file of a package that a browser imports, by its package.json. */
|
|
592
|
+
function browserEntryOf(packageJson) {
|
|
593
|
+
const dotExport = packageJson.exports?.["."] ?? packageJson.exports;
|
|
594
|
+
const entry = [typeof dotExport === "string" ? dotExport : (dotExport?.import?.default ?? dotExport?.import ?? dotExport?.default), packageJson.module, packageJson.main].find((path) => typeof path === "string");
|
|
595
|
+
return entry?.replace(/^\.\//, "") ?? null;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** The files a module reaches by relative imports, from readFileAt(path) → bytes or null. Answers { path: bytes }. */
|
|
599
|
+
async function reachedFiles(entryPath, readFileAt) {
|
|
600
|
+
const files = {};
|
|
601
|
+
const waiting = [entryPath];
|
|
602
|
+
while (waiting.length) {
|
|
603
|
+
const path = waiting.pop();
|
|
604
|
+
if (files[path] || !isSafePath(path)) continue;
|
|
605
|
+
const bytes = await readFileAt(path);
|
|
606
|
+
if (!bytes) continue;
|
|
607
|
+
files[path] = bytes;
|
|
608
|
+
if (!/\.m?js$/.test(path)) continue;
|
|
609
|
+
for (const match of bytes.toString("utf8").matchAll(/(?:from|import)\s*\(?\s*["'](\.{1,2}\/[^"']+)["']/g)) {
|
|
610
|
+
const parts = [];
|
|
611
|
+
for (const part of [...path.split("/").slice(0, -1), ...match[1].split("/")]) part === ".." ? parts.pop() : part !== "." && parts.push(part);
|
|
612
|
+
waiting.push(parts.join("/"));
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return files;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* A library that isn't a piece (three.js), from its package's files: the file a browser imports and the files
|
|
620
|
+
* that one reaches, with its licence file. Answers a unit of kind "library".
|
|
621
|
+
*/
|
|
622
|
+
async function libraryFrom(readFileAt, name, sourceKind) {
|
|
623
|
+
const packageJson = await Promise.resolve(readFileAt("package.json")).then((bytes) => JSON.parse(bytes.toString("utf8"))).catch(() => ({}));
|
|
624
|
+
const entryPath = parseVersion(packageJson.version) ? browserEntryOf(packageJson) : null;
|
|
625
|
+
const files = entryPath ? await reachedFiles(entryPath, readFileAt) : {};
|
|
626
|
+
if (!entryPath || !files[entryPath]) refuse("piece_need_unmet", { message: `${name} ${packageJson.version} has no file a browser can import.`, field: name, fix: `Add ${name} to the game yourself, with a bundler or an import map, then run this again.` });
|
|
627
|
+
// A game holds no file without an extension, so a licence travels as LICENSE.txt.
|
|
628
|
+
for (const path of ["LICENSE", "LICENSE.md", "LICENSE.txt", "LICENCE", "license", "license.md", "license.txt"]) {
|
|
629
|
+
const bytes = await readFileAt(path);
|
|
630
|
+
if (bytes) files[path.includes(".") ? path : `${path}.txt`] = bytes;
|
|
631
|
+
}
|
|
632
|
+
const license = typeof packageJson.license === "string" && packageJson.license.length <= 100 ? packageJson.license : null;
|
|
633
|
+
const library = { name, library_version: packageJson.version, summary: String(packageJson.description ?? "").slice(0, PIECE_LIMITS.maximumSummaryCharacterCount), license, entry_path: entryPath, file_paths: Object.keys(files).sort() };
|
|
634
|
+
return unitOf({ library, files, sourceKind, source: `${name}@${packageJson.version}` });
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** A library already installed beside a piece's folder (a node_modules above it), when every range accepts its version. */
|
|
638
|
+
async function readInstalledLibrary(name, ranges, fromFolder) {
|
|
639
|
+
for (let folder = fromFolder; ; folder = dirname(folder)) {
|
|
640
|
+
const libraryFolder = join(folder, "node_modules", ...name.split("/"));
|
|
641
|
+
const packageJson = await readFile(join(libraryFolder, "package.json"), "utf8").then(JSON.parse).catch(() => null);
|
|
642
|
+
if (packageJson && ranges.every((rangeText) => satisfies(packageJson.version, rangeText))) return libraryFrom((path) => readFile(join(libraryFolder, ...path.split("/"))).catch(() => null), name, "folder");
|
|
643
|
+
if (dirname(folder) === folder) return null;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** What a source names: a folder, a .tgz file, or a name on npm with an optional range ("@studio/dash-move@^1.2"). Answers the piece as a unit. */
|
|
648
|
+
export async function readSource(source, { baseFolder = process.cwd(), npm = npmReader() } = {}) {
|
|
649
|
+
const path = isAbsolute(source) ? source : resolve(baseFolder, source);
|
|
650
|
+
const found = await stat(path).catch(() => null);
|
|
651
|
+
if (found?.isDirectory()) return readPieceFolder(path);
|
|
652
|
+
if (found?.isFile()) return pieceFrom(readTarball(await readFile(path), source), "tarball", path, source);
|
|
653
|
+
const match = /^((?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*)(?:@(.+))?$/.exec(source);
|
|
654
|
+
if (!match || source.startsWith(".") || source.includes("//") || source.includes("\\")) refuse("piece_not_found", { message: `There's no folder or file at ${source}, and it isn't a name on npm.`, field: "source", fix: "Give a piece's folder, its .tgz, or its name on npm, like @studio/dash-move." });
|
|
655
|
+
if (match[2] !== undefined && !parseRange(match[2])) refuse("bad_piece_source", { message: `"${match[2]}" isn't a version or a range.`, field: "source", fix: "Give a name alone for the newest, or with a range, like @studio/dash-move@^1.2." });
|
|
656
|
+
const archive = await npm.archiveOf(match[1], [match[2] ?? "*"]);
|
|
657
|
+
if (!archive) refuse("piece_not_found", { message: `npm has no ${match[1]}${match[2] ? ` at ${match[2]}` : ""}.`, field: "source", fix: "Check the name and the version. A piece that isn't on npm is added from its folder or its .tgz." });
|
|
658
|
+
return pieceFrom(archive.allFiles, "npm", `${match[1]}@${archive.version}`, archive.whereFrom);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Looks a piece's needs up where the piece itself came from: beside its folder, else on npm. */
|
|
662
|
+
function needFinder(piece, npm) {
|
|
663
|
+
return async (name, needKind, ranges) => {
|
|
664
|
+
const isFolder = piece.sourceKind === "folder";
|
|
665
|
+
if (needKind === "library") {
|
|
666
|
+
const installed = isFolder ? await readInstalledLibrary(name, ranges, dirname(piece.source)) : null;
|
|
667
|
+
if (installed) return installed;
|
|
668
|
+
const archive = await npm.archiveOf(name, ranges);
|
|
669
|
+
return archive ? libraryFrom(async (path) => archive.allFiles[path] ?? null, name, "npm") : null;
|
|
670
|
+
}
|
|
671
|
+
if (isFolder) {
|
|
672
|
+
// A piece's neighbours: its own folder's siblings, and theirs when it sits in a scope's folder.
|
|
673
|
+
for (const parent of new Set([dirname(piece.source), dirname(dirname(piece.source))])) {
|
|
674
|
+
for (const entry of await readdir(parent, { withFileTypes: true }).catch(() => [])) {
|
|
675
|
+
if (!entry.isDirectory() || entry.name === "node_modules") continue;
|
|
676
|
+
for (const folder of entry.name.startsWith("@") ? (await readdir(join(parent, entry.name), { withFileTypes: true }).catch(() => [])).filter((inner) => inner.isDirectory()).map((inner) => join(parent, entry.name, inner.name)) : [join(parent, entry.name)]) {
|
|
677
|
+
const beside = await readFile(join(folder, STATEMENT_PATH), "utf8").then(JSON.parse).catch(() => null);
|
|
678
|
+
if (beside?.name === name && ranges.every((rangeText) => satisfies(beside.piece_version, rangeText))) return readPieceFolder(folder);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
const archive = await npm.archiveOf(name, ranges);
|
|
684
|
+
return archive ? pieceFrom(archive.allFiles, "npm", `${name}@${archive.version}`, archive.whereFrom) : null;
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// ---- A game's pieces ----
|
|
689
|
+
|
|
690
|
+
const emptyRecord = () => ({ about: "This game's pieces, kept by `zaisma pieces`: don't edit it by hand. docs/PIECES.md says what a piece is.", record_version_number: RECORD_VERSION_NUMBER, pieces: [], libraries: [] });
|
|
691
|
+
const LIBRARY_FIELDS = ["name", "library_version", "summary", "license", "entry_path", "file_paths", "source_kind", "files_sha256"];
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* The game's record of its pieces; an empty one when it has none yet. Throws bad_pieces_record when it can't be
|
|
695
|
+
* read, and pieces_record_newer when a newer command wrote it.
|
|
696
|
+
*/
|
|
697
|
+
export async function readRecord(gameFolder) {
|
|
698
|
+
const text = await readFile(join(gameFolder, ...RECORD_PATH.split("/")), "utf8").catch(() => null);
|
|
699
|
+
if (text === null) return emptyRecord();
|
|
700
|
+
const bad = () => refuse("bad_pieces_record", { message: `${RECORD_PATH} can't be read.`, field: null, fix: `Bring ${RECORD_PATH} back from your version control: it's the game's record of its pieces, and only the command changes it.` });
|
|
701
|
+
let record;
|
|
702
|
+
try {
|
|
703
|
+
record = JSON.parse(text);
|
|
704
|
+
} catch {
|
|
705
|
+
bad();
|
|
706
|
+
}
|
|
707
|
+
if (!isPlainObject(record) || !Number.isInteger(record.record_version_number)) bad();
|
|
708
|
+
if (record.record_version_number > RECORD_VERSION_NUMBER) refuse("pieces_record_newer", { message: `${RECORD_PATH} is written in format ${record.record_version_number}, and this command reads up to ${RECORD_VERSION_NUMBER}.`, field: null, fix: `Run the newest command: ${NEWEST_COMMAND} pieces.` });
|
|
709
|
+
if (!Array.isArray(record.pieces) || !Array.isArray(record.libraries)) bad();
|
|
710
|
+
for (const entry of record.pieces) {
|
|
711
|
+
const isHashRight = isPlainObject(entry) && (entry.files_sha256 === null ? entry.statement?.kind === "template" : /^[0-9a-f]{64}$/.test(entry.files_sha256));
|
|
712
|
+
if (!isHashRight || !SOURCE_KINDS.includes(entry.source_kind)) bad();
|
|
713
|
+
try {
|
|
714
|
+
readStatement(JSON.stringify(entry.statement), RECORD_PATH);
|
|
715
|
+
} catch (error) {
|
|
716
|
+
if (error instanceof PiecesError && error.error.code === "piece_statement_newer") throw error;
|
|
717
|
+
bad();
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
for (const entry of record.libraries) {
|
|
721
|
+
const isRight = isPlainObject(entry) && LIBRARY_FIELDS.every((field) => field in entry) && typeof entry.name === "string" && NAME_PATTERN.test(entry.name) && parseVersion(entry.library_version) && isSafePath(entry.entry_path) && Array.isArray(entry.file_paths) && entry.file_paths.every(isSafePath) && SOURCE_KINDS.includes(entry.source_kind) && /^[0-9a-f]{64}$/.test(entry.files_sha256);
|
|
722
|
+
if (!isRight) bad();
|
|
723
|
+
}
|
|
724
|
+
const names = [...record.pieces.map((entry) => entry.statement.name), ...record.libraries.map((entry) => entry.name)];
|
|
725
|
+
if (new Set(names).size !== names.length) bad();
|
|
726
|
+
return record;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** What a game has, by name, as units without their files; each unit's recorded is its entry in the record. */
|
|
730
|
+
function hadOf(record) {
|
|
731
|
+
const had = {};
|
|
732
|
+
for (const entry of record.pieces) had[entry.statement.name] = { ...unitOf({ statement: entry.statement, sourceKind: entry.source_kind }), recorded: entry };
|
|
733
|
+
for (const entry of record.libraries) had[entry.name] = { ...unitOf({ library: entry, sourceKind: entry.source_kind }), recorded: entry };
|
|
734
|
+
return had;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Where a unit's files sit in a game: [{ path (in the game's folder), filePath (in the piece), hashKey }]. A
|
|
739
|
+
* template's go in the game's own folder; anything else's in pieces/<name>/, its game server's in zaisma-server/pieces/<name>/.
|
|
740
|
+
*/
|
|
741
|
+
export function placesOf(unit) {
|
|
742
|
+
if (unit.kind === "library") return unit.library.file_paths.map((filePath) => ({ path: `${PIECES_FOLDER}/${unit.name}/${filePath}`, filePath, hashKey: filePath }));
|
|
743
|
+
if (unit.kind === "template") return unit.statement.file_paths.map((filePath) => ({ path: filePath, filePath, hashKey: filePath }));
|
|
744
|
+
return [
|
|
745
|
+
{ path: `${PIECES_FOLDER}/${unit.name}/${STATEMENT_PATH}`, filePath: STATEMENT_PATH, hashKey: STATEMENT_PATH },
|
|
746
|
+
...unit.statement.file_paths.map((filePath) => ({ path: `${PIECES_FOLDER}/${unit.name}/${filePath}`, filePath, hashKey: filePath })),
|
|
747
|
+
...unit.statement.server_file_paths.map((filePath) => ({ path: `${SERVER_PIECES_FOLDER}/${unit.name}/${filePath}`, filePath, hashKey: `server:${filePath}` })),
|
|
748
|
+
];
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/** The folders that hold only one unit's files in a game: replaced whole when it moves to another version, removed with it. */
|
|
752
|
+
const foldersOf = (unit) => (unit.kind === "template" ? [] : [`${PIECES_FOLDER}/${unit.name}`, ...(unit.kind !== "library" && unit.statement.server_file_paths.length ? [`${SERVER_PIECES_FOLDER}/${unit.name}`] : [])]);
|
|
753
|
+
|
|
754
|
+
/** The hash of a unit's files as it was read from its source. */
|
|
755
|
+
const sourceHash = (unit) => filesHash(Object.fromEntries(placesOf(unit).map((place) => [place.hashKey, unit.files[place.filePath]])));
|
|
756
|
+
|
|
757
|
+
/** Whether a unit's files in the game are still the ones that were added. A template's are the game's own, so never. */
|
|
758
|
+
async function isEdited(gameFolder, unit) {
|
|
759
|
+
if (unit.recorded.files_sha256 === null) return false;
|
|
760
|
+
const files = {};
|
|
761
|
+
for (const place of placesOf(unit)) {
|
|
762
|
+
const bytes = await readFile(join(gameFolder, ...place.path.split("/"))).catch(() => null);
|
|
763
|
+
if (bytes) files[place.hashKey] = bytes;
|
|
764
|
+
}
|
|
765
|
+
return filesHash(files) !== unit.recorded.files_sha256;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
async function writeUnit(gameFolder, unit) {
|
|
769
|
+
for (const folder of [`${PIECES_FOLDER}/${unit.name}`, `${SERVER_PIECES_FOLDER}/${unit.name}`]) if (unit.kind !== "template") await rm(join(gameFolder, ...folder.split("/")), { recursive: true, force: true });
|
|
770
|
+
for (const place of placesOf(unit)) {
|
|
771
|
+
const target = join(gameFolder, ...place.path.split("/"));
|
|
772
|
+
await mkdir(dirname(target), { recursive: true });
|
|
773
|
+
await writeFile(target, unit.files[place.filePath]);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** A unit read from its source, as the record keeps it. */
|
|
778
|
+
function recordedOf(unit) {
|
|
779
|
+
// A template is copied once and then the game's own: its files are never checked again.
|
|
780
|
+
if (unit.kind !== "library") return { statement: unit.statement, source_kind: unit.sourceKind, files_sha256: unit.kind === "template" ? null : sourceHash(unit) };
|
|
781
|
+
return { ...unit.library, source_kind: unit.sourceKind, files_sha256: sourceHash(unit) };
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function putInRecord(record, unit) {
|
|
785
|
+
const list = unit.kind === "library" ? record.libraries : record.pieces;
|
|
786
|
+
const nameOf = (entry) => (unit.kind === "library" ? entry.name : entry.statement.name);
|
|
787
|
+
const kept = list.filter((entry) => nameOf(entry) !== unit.name);
|
|
788
|
+
list.splice(0, list.length, ...[...kept, recordedOf(unit)].sort((first, second) => (nameOf(first) < nameOf(second) ? -1 : 1)));
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function takeFromRecord(record, name) {
|
|
792
|
+
record.pieces = record.pieces.filter((entry) => entry.statement.name !== name);
|
|
793
|
+
record.libraries = record.libraries.filter((entry) => entry.name !== name);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
async function writeRecord(gameFolder, record) {
|
|
797
|
+
const target = join(gameFolder, ...RECORD_PATH.split("/"));
|
|
798
|
+
await mkdir(dirname(target), { recursive: true });
|
|
799
|
+
await writeFile(target, JSON.stringify(record, null, 2) + "\n");
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** The libraries a game brings itself: what's installed in its node_modules, else the lowest version its package.json asks for. */
|
|
803
|
+
async function gameLibrariesOf(gameFolder, names) {
|
|
804
|
+
const libraries = {};
|
|
805
|
+
const packageJson = await readFile(join(gameFolder, "package.json"), "utf8").then(JSON.parse).catch(() => null);
|
|
806
|
+
if (!packageJson) return libraries;
|
|
807
|
+
for (const name of names) {
|
|
808
|
+
const asked = packageJson.dependencies?.[name] ?? packageJson.devDependencies?.[name];
|
|
809
|
+
if (asked === undefined) continue;
|
|
810
|
+
const installed = await readFile(join(gameFolder, "node_modules", ...name.split("/"), "package.json"), "utf8").then(JSON.parse).catch(() => null);
|
|
811
|
+
const lowest = /\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?/.exec(String(asked))?.[0];
|
|
812
|
+
if (installed?.version ?? lowest) libraries[name] = installed?.version ?? lowest;
|
|
813
|
+
}
|
|
814
|
+
return libraries;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/** A game's own libraries, looked up as needs for them come up. */
|
|
818
|
+
function gameLibrariesReader(gameFolder) {
|
|
819
|
+
const gameLibraries = {};
|
|
820
|
+
const lookedUp = new Set();
|
|
821
|
+
const note = async (unit) => {
|
|
822
|
+
const names = unit.needs.filter((need) => need.kind === "library" && !lookedUp.has(need.name)).map((need) => need.name);
|
|
823
|
+
names.forEach((name) => lookedUp.add(name));
|
|
824
|
+
Object.assign(gameLibraries, await gameLibrariesOf(gameFolder, names));
|
|
825
|
+
};
|
|
826
|
+
return { gameLibraries, note };
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** What a game's page needs to import its pieces without a bundler: the import map entries for libraries brought into pieces/. */
|
|
830
|
+
export function importMapOf(record) {
|
|
831
|
+
return { imports: Object.fromEntries(record.libraries.map((entry) => [entry.name, `./${PIECES_FOLDER}/${entry.name}/${entry.entry_path}`])) };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** The standards a game's pieces are built on. */
|
|
835
|
+
const standardsOf = (record) => [...new Set(record.pieces.map((entry) => entry.statement.standard))].sort();
|
|
836
|
+
|
|
837
|
+
/** One piece as the command answers it: its statement, and where a game imports it from. */
|
|
838
|
+
function shownPiece(entry, isPieceEdited) {
|
|
839
|
+
const { statement } = entry;
|
|
840
|
+
const isTemplate = statement.kind === "template";
|
|
841
|
+
return {
|
|
842
|
+
name: statement.name,
|
|
843
|
+
piece_version: statement.piece_version,
|
|
844
|
+
kind: statement.kind,
|
|
845
|
+
standard: statement.standard,
|
|
846
|
+
summary: statement.summary,
|
|
847
|
+
license: statement.license,
|
|
848
|
+
source_kind: entry.source_kind,
|
|
849
|
+
import_path: isTemplate || statement.entry_path === null ? null : `./${PIECES_FOLDER}/${statement.name}/${statement.entry_path}`,
|
|
850
|
+
server_import_path: isTemplate || statement.server_entry_path === null ? null : `./${PIECES_FOLDER}/${statement.name}/${statement.server_entry_path}`,
|
|
851
|
+
needs: statement.needs,
|
|
852
|
+
settings: statement.settings,
|
|
853
|
+
hooks: statement.hooks,
|
|
854
|
+
is_edited: isPieceEdited,
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/** One library as the command answers it. */
|
|
859
|
+
function shownLibrary(entry, isLibraryEdited) {
|
|
860
|
+
return { name: entry.name, library_version: entry.library_version, summary: entry.summary, license: entry.license, source_kind: entry.source_kind, import_path: `./${PIECES_FOLDER}/${entry.name}/${entry.entry_path}`, is_edited: isLibraryEdited };
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
const shownUnits = (units) => ({
|
|
864
|
+
pieces: units.filter((unit) => unit.kind !== "library").map((unit) => shownPiece(recordedOf(unit), false)),
|
|
865
|
+
libraries: units.filter((unit) => unit.kind === "library").map((unit) => shownLibrary(recordedOf(unit), false)),
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
/** zaisma pieces: what the game has. */
|
|
869
|
+
export async function listPieces(gameFolder) {
|
|
870
|
+
const record = await readRecord(gameFolder);
|
|
871
|
+
const had = hadOf(record);
|
|
872
|
+
const pieces = [];
|
|
873
|
+
for (const entry of record.pieces) pieces.push(shownPiece(entry, await isEdited(gameFolder, had[entry.statement.name])));
|
|
874
|
+
const libraries = [];
|
|
875
|
+
for (const entry of record.libraries) libraries.push(shownLibrary(entry, await isEdited(gameFolder, had[entry.name])));
|
|
876
|
+
return { pieces, libraries, standards: standardsOf(record), import_map: importMapOf(record) };
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/** Writes a plan's units into the game and its record, after checking a template writes over nothing. */
|
|
880
|
+
async function carryOut(gameFolder, record, added, isDryRun) {
|
|
881
|
+
for (const unit of added.filter((entry) => entry.kind === "template")) {
|
|
882
|
+
for (const place of placesOf(unit)) {
|
|
883
|
+
if (await lstat(join(gameFolder, ...place.path.split("/"))).catch(() => null)) refuse("template_file_exists", { message: `${unit.name} would write ${place.path}, which the game already has.`, field: place.path, fix: "Nothing was changed. A template starts a game: add it to an empty folder, or move that file away first." });
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
const standardsBefore = standardsOf(record);
|
|
887
|
+
for (const unit of added) {
|
|
888
|
+
if (!isDryRun) await writeUnit(gameFolder, unit);
|
|
889
|
+
putInRecord(record, unit);
|
|
890
|
+
}
|
|
891
|
+
if (!isDryRun && added.length) await writeRecord(gameFolder, record);
|
|
892
|
+
return standardsOf(record).filter((standard) => !standardsBefore.includes(standard));
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* zaisma pieces add: adds a piece and what it needs, or changes nothing. With isDryRun it answers what adding
|
|
897
|
+
* would do and writes nothing.
|
|
898
|
+
*/
|
|
899
|
+
export async function addPiece(gameFolder, source, { isDryRun = false } = {}) {
|
|
900
|
+
const npm = npmReader();
|
|
901
|
+
const piece = await readSource(source, { npm });
|
|
902
|
+
const record = await readRecord(gameFolder);
|
|
903
|
+
const find = needFinder(piece, npm);
|
|
904
|
+
const libraries = gameLibrariesReader(gameFolder);
|
|
905
|
+
await libraries.note(piece);
|
|
906
|
+
const plan = await planAdd({
|
|
907
|
+
piece,
|
|
908
|
+
had: hadOf(record),
|
|
909
|
+
gameLibraries: libraries.gameLibraries,
|
|
910
|
+
find: async (name, needKind, ranges) => {
|
|
911
|
+
const found = await find(name, needKind, ranges);
|
|
912
|
+
if (found) await libraries.note(found);
|
|
913
|
+
return found;
|
|
914
|
+
},
|
|
915
|
+
});
|
|
916
|
+
const newStandards = await carryOut(gameFolder, record, plan.added, isDryRun);
|
|
917
|
+
const shown = shownUnits(plan.added);
|
|
918
|
+
return { is_dry_run: isDryRun, added_pieces: shown.pieces, added_libraries: shown.libraries, kept_names: plan.keptNames, engine_needs: plan.engineNeeds, standards: standardsOf(record), new_standards: newStandards, import_map: importMapOf(record) };
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
const noSuchPiece = (name) => refuse("piece_not_added", { message: `The game has no piece or library ${name} in its ${PIECES_FOLDER} folder.`, field: "name", fix: `zaisma pieces lists what it has; zaisma pieces add ${name} adds it. A library in the game's own package.json is the game's to move.` });
|
|
922
|
+
const refuseEdited = (name, command) => refuse("piece_edited", { message: `${name}'s files in the game aren't the ones that were added: someone changed them.`, field: "name", fix: `Nothing was changed. A piece is changed through its settings and hooks, never its files; if a change is missing, tell its maker. To lose the edits anyway: zaisma pieces ${command} ${name} --discard-edits.` });
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* zaisma pieces update: moves one piece (or one library brought for pieces) to another version, on the
|
|
926
|
+
* developer's word, when everything else in the game accepts it. Nothing else moves; what the new version needs
|
|
927
|
+
* and the game lacks is brought.
|
|
928
|
+
*/
|
|
929
|
+
export async function updatePiece(gameFolder, name, { versionRange = "*", source = null, isDiscardingEdits = false, isDryRun = false } = {}) {
|
|
930
|
+
const record = await readRecord(gameFolder);
|
|
931
|
+
const had = hadOf(record);
|
|
932
|
+
const current = had[name];
|
|
933
|
+
if (!current) noSuchPiece(name);
|
|
934
|
+
if (current.kind === "template") refuse("piece_not_updatable", { message: `${name} is a template: it was copied once and is the game's own now.`, field: "name", fix: "Nothing to update. Take what you want from a newer template by hand." });
|
|
935
|
+
if (!parseRange(versionRange)) refuse("bad_piece_source", { message: `"${versionRange}" isn't a version or a range.`, field: "version", fix: 'Give a version or a range, like "^1.2" or "1.4.0".' });
|
|
936
|
+
const npm = npmReader();
|
|
937
|
+
let next;
|
|
938
|
+
if (source !== null && current.kind === "library") refuse("bad_piece_source", { message: `${name} is a library, which comes from npm.`, field: "from", fix: "Leave --from out, and give --version for the version you want." });
|
|
939
|
+
if (source !== null) next = await readSource(source, { npm });
|
|
940
|
+
else if (current.kind === "library") {
|
|
941
|
+
const archive = await npm.archiveOf(name, [versionRange]);
|
|
942
|
+
next = archive ? await libraryFrom(async (path) => archive.allFiles[path] ?? null, name, "npm") : null;
|
|
943
|
+
} else if (current.sourceKind === "npm") next = await readSource(`${name}@${versionRange}`, { npm });
|
|
944
|
+
else refuse("piece_source_needed", { message: `${name} was added from a ${current.sourceKind}, so there's nowhere to look for another version.`, field: "from", fix: `Say where the new version is: zaisma pieces update ${name} --from <folder or .tgz>.` });
|
|
945
|
+
if (!next) refuse("piece_not_found", { message: `npm has no ${name} at ${versionRange}.`, field: "version", fix: "Check the version." });
|
|
946
|
+
if (next.name !== name) refuse("bad_piece_source", { message: `That's ${next.name}, not ${name}.`, field: "from", fix: `Give a source of ${name}.` });
|
|
947
|
+
if (!satisfies(next.version, versionRange)) refuse("piece_not_found", { message: `That source holds ${named(next)}, outside ${versionRange}.`, field: "version", fix: "Give a source of the version you want, or leave --version out." });
|
|
948
|
+
const answer = (updated, added, plan, newStandards) => {
|
|
949
|
+
const shown = shownUnits(added);
|
|
950
|
+
const isLibrary = current.kind === "library";
|
|
951
|
+
return {
|
|
952
|
+
is_dry_run: isDryRun,
|
|
953
|
+
name,
|
|
954
|
+
updated_piece: updated && !isLibrary ? shownPiece(recordedOf(updated), false) : null,
|
|
955
|
+
updated_library: updated && isLibrary ? shownLibrary(recordedOf(updated), false) : null,
|
|
956
|
+
earlier_piece_version: isLibrary ? null : current.version,
|
|
957
|
+
earlier_library_version: isLibrary ? current.version : null,
|
|
958
|
+
added_pieces: shown.pieces,
|
|
959
|
+
added_libraries: shown.libraries,
|
|
960
|
+
kept_names: plan?.keptNames ?? [],
|
|
961
|
+
engine_needs: plan?.engineNeeds ?? [],
|
|
962
|
+
standards: standardsOf(record),
|
|
963
|
+
new_standards: newStandards,
|
|
964
|
+
import_map: importMapOf(record),
|
|
965
|
+
};
|
|
966
|
+
};
|
|
967
|
+
if (next.version === current.version) return answer(null, [], null, []);
|
|
968
|
+
if ((await isEdited(gameFolder, current)) && !isDiscardingEdits) refuseEdited(name, "update");
|
|
969
|
+
checkUpdateFits({ name, nextVersion: next.version, had });
|
|
970
|
+
// The new version's own needs are met the same way adding meets them.
|
|
971
|
+
const others = Object.fromEntries(Object.entries(had).filter(([hadName]) => hadName !== name));
|
|
972
|
+
const libraries = gameLibrariesReader(gameFolder);
|
|
973
|
+
await libraries.note(next);
|
|
974
|
+
const find = needFinder(next, npm);
|
|
975
|
+
const plan = await planAdd({
|
|
976
|
+
piece: next,
|
|
977
|
+
had: others,
|
|
978
|
+
gameLibraries: libraries.gameLibraries,
|
|
979
|
+
find: async (needName, needKind, ranges) => {
|
|
980
|
+
const found = await find(needName, needKind, ranges);
|
|
981
|
+
if (found) await libraries.note(found);
|
|
982
|
+
return found;
|
|
983
|
+
},
|
|
984
|
+
});
|
|
985
|
+
const newStandards = await carryOut(gameFolder, record, plan.added, isDryRun);
|
|
986
|
+
return answer(next, plan.added.filter((unit) => unit.name !== name), plan, newStandards);
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* zaisma pieces remove: takes one piece (or library) out of the game, unless another of its pieces needs it.
|
|
991
|
+
* Nothing else is removed; what it needed and nothing needs now is named, for the developer to decide.
|
|
992
|
+
*/
|
|
993
|
+
export async function removePiece(gameFolder, name, { isDiscardingEdits = false, isDryRun = false } = {}) {
|
|
994
|
+
const record = await readRecord(gameFolder);
|
|
995
|
+
const had = hadOf(record);
|
|
996
|
+
const current = had[name];
|
|
997
|
+
if (!current) noSuchPiece(name);
|
|
998
|
+
if (current.kind === "template") refuse("piece_not_removable", { message: `${name} is a template: its files are the game's own now.`, field: "name", fix: "Delete the files you don't want yourself; the pieces it brought are removed one by one." });
|
|
999
|
+
const needers = needersOf(name, had);
|
|
1000
|
+
if (needers.length) refuse("piece_still_needed", { message: `${needers.map(({ holder, need }) => `${named(holder)} needs ${name} ${need.version_range}`).join(", and ")}.`, field: "name", fix: `Nothing was changed. Remove ${needers.map(({ holder }) => holder.name).join(" and ")} first, or keep ${name}.` });
|
|
1001
|
+
if ((await isEdited(gameFolder, current)) && !isDiscardingEdits) refuseEdited(name, "remove");
|
|
1002
|
+
const others = Object.fromEntries(Object.entries(had).filter(([hadName]) => hadName !== name));
|
|
1003
|
+
const noLongerNeededNames = current.needs.filter((need) => isNeedBrought(need) && others[need.name] && !needersOf(need.name, others).length).map((need) => need.name);
|
|
1004
|
+
takeFromRecord(record, name);
|
|
1005
|
+
if (!isDryRun) {
|
|
1006
|
+
for (const folder of foldersOf(current)) await rm(join(gameFolder, ...folder.split("/")), { recursive: true, force: true });
|
|
1007
|
+
// A scope's folder that held only this piece goes with it.
|
|
1008
|
+
if (name.startsWith("@")) for (const base of [PIECES_FOLDER, SERVER_PIECES_FOLDER]) {
|
|
1009
|
+
const scopeFolder = join(gameFolder, ...base.split("/"), name.split("/")[0]);
|
|
1010
|
+
const left = await readdir(scopeFolder).catch(() => null);
|
|
1011
|
+
if (left && !left.length) await rm(scopeFolder, { recursive: true, force: true });
|
|
1012
|
+
}
|
|
1013
|
+
await writeRecord(gameFolder, record);
|
|
1014
|
+
}
|
|
1015
|
+
return { is_dry_run: isDryRun, removed_name: name, removed_folders: foldersOf(current), no_longer_needed_names: noLongerNeededNames, import_map: importMapOf(record) };
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* zaisma pieces newer: which of a game's pieces have a newer version on npm, and the newest the rest of the
|
|
1020
|
+
* game accepts. It changes nothing: a version moves only with pieces update.
|
|
1021
|
+
*/
|
|
1022
|
+
export async function newerPieces(gameFolder) {
|
|
1023
|
+
const record = await readRecord(gameFolder);
|
|
1024
|
+
const had = hadOf(record);
|
|
1025
|
+
const npm = npmReader();
|
|
1026
|
+
const newer = { newer_pieces: [], newer_libraries: [], unchecked_names: [] };
|
|
1027
|
+
for (const unit of Object.values(had)) {
|
|
1028
|
+
if (unit.kind === "template") continue;
|
|
1029
|
+
const versions = unit.sourceKind === "npm" ? await npm.versionsOf(unit.name) : null;
|
|
1030
|
+
if (!versions) {
|
|
1031
|
+
newer.unchecked_names.push(unit.name);
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
const isNewer = (version) => parseVersion(version) && compareVersions(version, unit.version) > 0;
|
|
1035
|
+
const newest = newestSatisfying(Object.keys(versions).filter(isNewer), "*");
|
|
1036
|
+
if (!newest) continue;
|
|
1037
|
+
const needers = needersOf(unit.name, had);
|
|
1038
|
+
const newestAccepted = newestSatisfying(Object.keys(versions).filter(isNewer), ["*", ...needers.map(({ need }) => need.version_range)]);
|
|
1039
|
+
const heldBackByNames = needers.filter(({ need }) => !satisfies(newest, need.version_range)).map(({ holder }) => holder.name);
|
|
1040
|
+
if (unit.kind === "library") newer.newer_libraries.push({ name: unit.name, library_version: unit.version, newest_library_version: newest, newest_accepted_library_version: newestAccepted, held_back_by_names: heldBackByNames });
|
|
1041
|
+
else newer.newer_pieces.push({ name: unit.name, piece_version: unit.version, newest_piece_version: newest, newest_accepted_piece_version: newestAccepted, held_back_by_names: heldBackByNames });
|
|
1042
|
+
}
|
|
1043
|
+
return newer;
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// ---- A maker's check of a piece, before publishing it ----
|
|
1047
|
+
|
|
1048
|
+
/** Every problem the check finds. refused: adding the piece would fail or break it in a game. note: worth fixing, and it still adds. */
|
|
1049
|
+
export const PIECE_CHECK_CODES = {
|
|
1050
|
+
bad_piece_statement: { problemKind: "refused", meaning: "The piece.json isn't one: the message names the field." },
|
|
1051
|
+
piece_statement_newer: { problemKind: "refused", meaning: "The piece.json is written for a newer command than this one." },
|
|
1052
|
+
missing_file: { problemKind: "refused", meaning: "The piece.json lists a file that isn't there, or the file is a link." },
|
|
1053
|
+
stale_statement_module: { problemKind: "refused", meaning: "piece.json.js isn't piece.json as a module any more; --fix writes it again." },
|
|
1054
|
+
package_disagrees: { problemKind: "refused", meaning: "The package.json beside it has another name or version, or leaves a listed file out of what npm packs." },
|
|
1055
|
+
unlisted_import: { problemKind: "refused", meaning: "A file imports a file of the piece's own that the piece.json doesn't list, so a game wouldn't get it." },
|
|
1056
|
+
undeclared_need: { problemKind: "refused", meaning: "A file imports another piece or a library that isn't in needs." },
|
|
1057
|
+
file_not_uploadable: { problemKind: "note", meaning: "A file is of a type Zaisma's upload doesn't take, so a game whose folder is uploaded as it is can't hold the piece." },
|
|
1058
|
+
no_reference: { problemKind: "note", meaning: "The file a game imports has no .d.ts beside it: it's what an AI reads to use the piece without opening its code." },
|
|
1059
|
+
no_readme: { problemKind: "note", meaning: "There's no README.md among the piece's files." },
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
/** The modules a JavaScript file imports, by what's between the quotes; null when it can't be parsed. */
|
|
1063
|
+
function importedModules(text) {
|
|
1064
|
+
let tree;
|
|
1065
|
+
try {
|
|
1066
|
+
tree = parseJavaScript(text, { ecmaVersion: "latest", sourceType: "module" });
|
|
1067
|
+
} catch {
|
|
1068
|
+
return null;
|
|
1069
|
+
}
|
|
1070
|
+
const modules = [];
|
|
1071
|
+
const visit = (node) => {
|
|
1072
|
+
if (!node || typeof node.type !== "string") return;
|
|
1073
|
+
if ((node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.source) modules.push(node.source.value);
|
|
1074
|
+
if (node.type === "ImportExpression" && node.source.type === "Literal" && typeof node.source.value === "string") modules.push(node.source.value);
|
|
1075
|
+
for (const key of Object.keys(node)) {
|
|
1076
|
+
const child = node[key];
|
|
1077
|
+
if (Array.isArray(child)) child.forEach(visit);
|
|
1078
|
+
else if (child && typeof child === "object") visit(child);
|
|
1079
|
+
}
|
|
1080
|
+
};
|
|
1081
|
+
visit(tree);
|
|
1082
|
+
return modules;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* zaisma pieces check: what a maker runs on a piece's folder before publishing it. Answers { name,
|
|
1087
|
+
* piece_version, is_ready, problems }, each problem { code, problem_kind, message, path, fix }; is_ready is
|
|
1088
|
+
* false with any "refused" problem. With isFixing it first writes piece.json.js again from piece.json, when the
|
|
1089
|
+
* piece has one.
|
|
1090
|
+
*/
|
|
1091
|
+
export async function checkPiece(pieceFolder, { isFixing = false } = {}) {
|
|
1092
|
+
const problems = [];
|
|
1093
|
+
const add = (code, message, path, fix) => problems.push({ code, problem_kind: PIECE_CHECK_CODES[code].problemKind, message, path, fix });
|
|
1094
|
+
const done = (statement) => ({ name: statement?.name ?? null, piece_version: statement?.piece_version ?? null, is_ready: !problems.some((problem) => problem.problem_kind === "refused"), problems });
|
|
1095
|
+
const statementBytes = await readFile(join(pieceFolder, STATEMENT_PATH)).catch(() => null);
|
|
1096
|
+
if (!statementBytes) refuse("bad_piece_source", { message: `${pieceFolder} has no ${STATEMENT_PATH}, so it isn't a piece.`, field: "folder", fix: `Give a piece's folder: one with a ${STATEMENT_PATH} at its top (docs/PIECES.md).` });
|
|
1097
|
+
const statementText = statementBytes.toString("utf8");
|
|
1098
|
+
let statement;
|
|
1099
|
+
try {
|
|
1100
|
+
statement = readStatement(statementText);
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
if (!(error instanceof PiecesError)) throw error;
|
|
1103
|
+
add(error.error.code, error.error.message, STATEMENT_PATH, error.error.fix);
|
|
1104
|
+
return done(null);
|
|
1105
|
+
}
|
|
1106
|
+
const listedPaths = [...new Set([...statement.file_paths, ...statement.server_file_paths])];
|
|
1107
|
+
const isModuleListed = listedPaths.includes(STATEMENT_MODULE_PATH);
|
|
1108
|
+
if (isFixing && isModuleListed) await writeFile(join(pieceFolder, STATEMENT_MODULE_PATH), statementModuleText(statementText));
|
|
1109
|
+
const files = {};
|
|
1110
|
+
for (const path of listedPaths) {
|
|
1111
|
+
const found = await lstat(join(pieceFolder, ...path.split("/"))).catch(() => null);
|
|
1112
|
+
if (!found?.isFile()) add("missing_file", `${STATEMENT_PATH} lists ${path}, which ${found?.isSymbolicLink() ? "is a link to another file" : "isn't there"}.`, path, found?.isSymbolicLink() ? "Put the file itself in the piece." : "Add the file, or take it out of the list.");
|
|
1113
|
+
else files[path] = await readFile(join(pieceFolder, ...path.split("/")));
|
|
1114
|
+
}
|
|
1115
|
+
if (files[STATEMENT_MODULE_PATH] && !isStatementModule(files[STATEMENT_MODULE_PATH], statementText)) add("stale_statement_module", `${STATEMENT_MODULE_PATH} isn't ${STATEMENT_PATH} as a module any more, so the piece's code would read another statement than the one it gives.`, STATEMENT_MODULE_PATH, "Run this check again with --fix: it writes the file from piece.json.");
|
|
1116
|
+
const packageJson = await readFile(join(pieceFolder, "package.json"), "utf8").then(JSON.parse).catch(() => null);
|
|
1117
|
+
if (packageJson) {
|
|
1118
|
+
if (packageJson.name !== statement.name || packageJson.version !== statement.piece_version) add("package_disagrees", `${STATEMENT_PATH} says ${statement.name} ${statement.piece_version}, and package.json says ${packageJson.name} ${packageJson.version}.`, "package.json", "Give both the same name and version: a piece is found on npm by its package's.");
|
|
1119
|
+
if (Array.isArray(packageJson.files)) {
|
|
1120
|
+
// Plain names only: a pattern in "files" is npm's to read.
|
|
1121
|
+
const isPacked = (path) => packageJson.files.some((packed) => /[*?!{[]/.test(packed) || path === packed.replace(/^\.\//, "").replace(/\/$/, "") || path.startsWith(`${packed.replace(/^\.\//, "").replace(/\/$/, "")}/`));
|
|
1122
|
+
for (const path of [STATEMENT_PATH, ...listedPaths]) if (!isPacked(path)) add("package_disagrees", `package.json's files leaves out ${path}, so npm wouldn't publish it.`, "package.json", `Add "${path}" to package.json's files.`);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
// What each file imports: its own files must be listed, and anything outside the piece must be one of its needs.
|
|
1126
|
+
const needKinds = Object.fromEntries(statement.needs.map((need) => [need.name, need.kind]));
|
|
1127
|
+
const isTemplate = statement.kind === "template";
|
|
1128
|
+
for (const [path, bytes] of Object.entries(files)) {
|
|
1129
|
+
if (!/\.m?js$/.test(path)) continue;
|
|
1130
|
+
const modules = importedModules(bytes.toString("utf8"));
|
|
1131
|
+
for (const module of modules ?? []) {
|
|
1132
|
+
const sides = [statement.file_paths.includes(path) ? statement.file_paths : null, statement.server_file_paths.includes(path) ? statement.server_file_paths : null].filter(Boolean);
|
|
1133
|
+
if (module.startsWith(".")) {
|
|
1134
|
+
// As the file sits in a game: pieces/<name>/<path> with its neighbours beside it, or the game's own folder for a template.
|
|
1135
|
+
const parts = isTemplate ? [] : [PIECES_FOLDER, ...statement.name.split("/")];
|
|
1136
|
+
for (const part of [...path.split("/").slice(0, -1), ...module.split("/")]) part === ".." ? parts.pop() : part !== "." && parts.push(part);
|
|
1137
|
+
const target = parts.join("/");
|
|
1138
|
+
const ownFolder = `${PIECES_FOLDER}/${statement.name}/`;
|
|
1139
|
+
if (!isTemplate && target.startsWith(ownFolder)) {
|
|
1140
|
+
const inside = target.slice(ownFolder.length);
|
|
1141
|
+
if (inside !== STATEMENT_PATH) for (const side of sides) if (!side.includes(inside)) add("unlisted_import", `${path} imports ${module}, and ${inside} isn't in ${side === statement.file_paths ? "file_paths" : "server_file_paths"}.`, path, `List ${inside} there, so a game gets it.`);
|
|
1142
|
+
} else if (target.startsWith(`${PIECES_FOLDER}/`)) {
|
|
1143
|
+
const neighbour = /^((?:@[^/]+\/)?[^/]+)\//.exec(target.slice(PIECES_FOLDER.length + 1))?.[1];
|
|
1144
|
+
if (!neighbour || needKinds[neighbour] !== "piece") add("undeclared_need", `${path} imports ${module}, and ${neighbour ?? "that"} isn't a piece in its needs.`, path, `Add { "name": "${neighbour ?? "<its name>"}", "version_range": "…", "kind": "piece" } to needs: what a piece needs is always stated.`);
|
|
1145
|
+
} else if (isTemplate) {
|
|
1146
|
+
if (!statement.file_paths.includes(target)) add("unlisted_import", `${path} imports ${module}, and ${target} isn't in file_paths.`, path, `List ${target} there, so a game gets it.`);
|
|
1147
|
+
} else add("undeclared_need", `${path} imports ${module}, which leaves the ${PIECES_FOLDER} folder.`, path, `Import only the piece's own files and its needs, each from where a game has it: ${PIECES_FOLDER}/<name>/.`);
|
|
1148
|
+
} else if (!module.startsWith("node:") && !/^[a-z]+:/.test(module)) {
|
|
1149
|
+
const library = /^((?:@[^/]+\/)?[^/]+)/.exec(module)?.[1];
|
|
1150
|
+
if (needKinds[library] !== "library") add("undeclared_need", `${path} imports ${module}, and ${library} isn't a library in its needs.`, path, `Add { "name": "${library}", "version_range": "…", "kind": "library" } to needs: what a piece needs is always stated.`);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
for (const path of listedPaths) {
|
|
1155
|
+
if (path.endsWith(".d.ts") || GAME_FILE_EXTENSIONS.includes(extensionOf(path))) continue;
|
|
1156
|
+
add("file_not_uploadable", `${path} is of a type Zaisma's upload doesn't take.`, path, "A game whose folder is uploaded as it is can't hold this file. Rename it (a licence travels as LICENSE.txt), or leave it out if the game never reads it.");
|
|
1157
|
+
}
|
|
1158
|
+
const entryPath = statement.entry_path;
|
|
1159
|
+
if (!isTemplate && entryPath && /\.m?js$/.test(entryPath) && !statement.file_paths.includes(entryPath.replace(/\.m?js$/, ".d.ts"))) add("no_reference", `${entryPath} has no ${entryPath.replace(/\.m?js$/, ".d.ts")} among the piece's files.`, entryPath, "Write one with every call, setting, hook and error explained and an example: it's what an AI reads instead of the code.");
|
|
1160
|
+
if (!statement.file_paths.includes("README.md")) add("no_readme", "There's no README.md in file_paths.", null, "Add one that shows the piece in use.");
|
|
1161
|
+
return done(statement);
|
|
1162
|
+
}
|