temporal-fmt 0.9.71 → 0.9.80
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 +13 -49
- package/dist/{chunk-MXXTJ5CW.js → chunk-5KP5H7X2.js} +3 -3
- package/dist/{chunk-ZT3UXRAA.js → chunk-DMJWJTFY.js} +3 -8
- package/dist/chunk-DMJWJTFY.js.map +1 -0
- package/dist/{chunk-CQJYB7E7.js → chunk-HGRT37LT.js} +4 -10
- package/dist/chunk-HGRT37LT.js.map +1 -0
- package/dist/{chunk-3FMUGYE2.js → chunk-KV6GMX4D.js} +4 -159
- package/dist/chunk-KV6GMX4D.js.map +1 -0
- package/dist/chunk-UGYSEYUQ.js +168 -0
- package/dist/chunk-UGYSEYUQ.js.map +1 -0
- package/dist/{chunk-3SC5AVSY.js → chunk-WEVNKOQA.js} +2 -2
- package/dist/chunk-WP7TBCTT.js +241 -0
- package/dist/chunk-WP7TBCTT.js.map +1 -0
- package/dist/{chunk-BQET6RUR.js → chunk-Z245NHDT.js} +2 -19
- package/dist/{chunk-BQET6RUR.js.map → chunk-Z245NHDT.js.map} +1 -1
- package/dist/format.cjs +0 -17
- package/dist/format.cjs.map +1 -1
- package/dist/format.js +3 -3
- package/dist/index.cjs +3832 -4705
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -103
- package/dist/index.d.ts +20 -103
- package/dist/index.js +2406 -846
- package/dist/index.js.map +1 -1
- package/dist/interval.cjs +106 -4773
- package/dist/interval.cjs.map +1 -1
- package/dist/interval.js +5 -10
- package/dist/parse.cjs +0 -13
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.js +3 -3
- package/dist/recurrence.js +2 -1
- package/dist/relativeTime.cjs.map +1 -1
- package/dist/relativeTime.js +2 -2
- package/dist/tokens.d.cts +0 -4
- package/dist/tokens.d.ts +0 -4
- package/package.json +5 -21
- package/MODS.md +0 -148
- package/dist/chunk-3FMUGYE2.js.map +0 -1
- package/dist/chunk-CQJYB7E7.js.map +0 -1
- package/dist/chunk-ZT3UXRAA.js.map +0 -1
- package/dist/chunk-ZTIF4ZHX.js +0 -3041
- package/dist/chunk-ZTIF4ZHX.js.map +0 -1
- package/dist/modApi.d.cts +0 -147
- package/dist/modApi.d.ts +0 -147
- package/dist/runtime.d.cts +0 -206
- package/dist/runtime.d.ts +0 -206
- package/scripts/cli.mjs +0 -324
- package/scripts/loadMods.d.mts +0 -37
- package/scripts/loadMods.mjs +0 -801
- package/scripts/managePermissions.mjs +0 -126
- package/scripts/modConfig.mjs +0 -96
- package/scripts/modSandbox.d.mts +0 -13
- package/scripts/modSandbox.mjs +0 -855
- package/scripts/modWire.mjs +0 -241
- package/scripts/modWorker.mjs +0 -574
- package/scripts/semverRange.mjs +0 -157
- package/scripts/versions.json +0 -42
- /package/dist/{chunk-MXXTJ5CW.js.map → chunk-5KP5H7X2.js.map} +0 -0
- /package/dist/{chunk-3SC5AVSY.js.map → chunk-WEVNKOQA.js.map} +0 -0
package/scripts/loadMods.mjs
DELETED
|
@@ -1,801 +0,0 @@
|
|
|
1
|
-
// Loads community mods from a folder — drop a .mjs file in mods/, it
|
|
2
|
-
// gets picked up on startup and registered against the library through
|
|
3
|
-
// ModContext (see src/modApi.ts). Modeled on the Minecraft-style "mods
|
|
4
|
-
// folder" convention: no manifest step, no publishing to a registry,
|
|
5
|
-
// just a file on disk that the host looks for and runs.
|
|
6
|
-
//
|
|
7
|
-
// This lives in scripts/, not src/, on purpose. readdir/dynamic-import
|
|
8
|
-
// are Node-only, and src/ is what gets published and bundled for
|
|
9
|
-
// non-Node consumers too (tsup builds esm+cjs, ships a .d.ts) — pulling
|
|
10
|
-
// fs/path into that surface would mean anyone importing plain format()
|
|
11
|
-
// drags in Node-only code they never asked for. The CLI is already
|
|
12
|
-
// Node-only, so this is the right layer for it.
|
|
13
|
-
//
|
|
14
|
-
// Two on-disk shapes are accepted:
|
|
15
|
-
//
|
|
16
|
-
// 1. A loose .mjs file — the original, still-simplest case. TypeScript
|
|
17
|
-
// mods have to be compiled and renamed first — the loader can't run
|
|
18
|
-
// a TS transpile step itself without pulling in a compiler as a
|
|
19
|
-
// dependency, which the rest of this package deliberately avoids
|
|
20
|
-
// (see README -> Providing Temporal for the same reasoning applied
|
|
21
|
-
// to the polyfill). A .ts file sitting in mods/ fails loudly with a
|
|
22
|
-
// message telling the author to build it, rather than getting
|
|
23
|
-
// silently skipped — silent skip is how someone loses an afternoon
|
|
24
|
-
// wondering why their mod never ran.
|
|
25
|
-
//
|
|
26
|
-
// 2. A .tfmod archive — a gzipped tar (same format as .tgz, renamed
|
|
27
|
-
// for identity) containing mod.json (metadata: name/version/main/
|
|
28
|
-
// requires/priority/permissions) plus main.mjs and, optionally, a
|
|
29
|
-
// data/ directory of files main.mjs can read at register() time.
|
|
30
|
-
// This exists for mods that need more than one file, so the loader
|
|
31
|
-
// can learn a mod's name/requires without executing any of its
|
|
32
|
-
// code — mod.json is read directly from the archive, no import()
|
|
33
|
-
// happens until dependency order is already decided — and because
|
|
34
|
-
// it's the only shape that can request capabilities (a loose .mjs
|
|
35
|
-
// file has no manifest to declare permissions in, so it runs with
|
|
36
|
-
// none; see MODS.md).
|
|
37
|
-
//
|
|
38
|
-
// Loading is two passes either way. Pass one collects every mod's
|
|
39
|
-
// name/requires/priority without calling register() yet (via mod.json
|
|
40
|
-
// for .tfmod, via a sandboxed subprocess import for .mjs — see
|
|
41
|
-
// scripts/modSandbox.mjs) — order can't be decided until every mod's
|
|
42
|
-
// declared dependencies are known. Pass two resolves a load order from
|
|
43
|
-
// those dependencies (priority as a tiebreak, then filename as the
|
|
44
|
-
// final tiebreak) and runs each mod's register() — in its own sandboxed
|
|
45
|
-
// subprocess with only the capabilities the user granted, its
|
|
46
|
-
// registrations replayed here against the real registry, tracking which
|
|
47
|
-
// mod touched which registration key so conflicts can be reported
|
|
48
|
-
// afterward.
|
|
49
|
-
//
|
|
50
|
-
// register() never runs in this process anymore. A mod that only
|
|
51
|
-
// registers data (a locale, a holiday set) runs in a short-lived
|
|
52
|
-
// subprocess that exits once its registrations have been handed back; a
|
|
53
|
-
// mod that installs a runtime override (overrideFormat/overrideParse/
|
|
54
|
-
// any ctx.override*) keeps its subprocess alive as the target of a
|
|
55
|
-
// synchronous pipe bridge, because that closure has to answer every
|
|
56
|
-
// later format()/parse() call and it can't leave the sandbox.
|
|
57
|
-
|
|
58
|
-
import { readdir, mkdtemp, rm, readFile, stat, mkdir, realpath } from 'node:fs/promises';
|
|
59
|
-
import { join, extname, resolve, basename, relative, isAbsolute } from 'node:path';
|
|
60
|
-
import { tmpdir } from 'node:os';
|
|
61
|
-
import { execFile } from 'node:child_process';
|
|
62
|
-
import { promisify } from 'node:util';
|
|
63
|
-
import { buildTrackedModContext, OverrideConflictError } from '../dist/index.js';
|
|
64
|
-
import { checkVersionRange } from './semverRange.mjs';
|
|
65
|
-
import { isValidConfigSchema, resolveConfig } from './modConfig.mjs';
|
|
66
|
-
import { createRequire } from 'node:module';
|
|
67
|
-
import {
|
|
68
|
-
GRANTABLE_PERMISSIONS,
|
|
69
|
-
createSandboxContext,
|
|
70
|
-
describeMjsMods,
|
|
71
|
-
resolvePermissions,
|
|
72
|
-
runModInSandbox,
|
|
73
|
-
makeOverrideBridgeImpl,
|
|
74
|
-
runtimeTimeoutMs,
|
|
75
|
-
memoryCeilingMb,
|
|
76
|
-
} from './modSandbox.mjs';
|
|
77
|
-
import { fromWire, rehydrateFormatterOptions, rehydrateCustomToken, isExperimentalPermissionModel, CURRENT_API_LEVEL } from './modWire.mjs';
|
|
78
|
-
|
|
79
|
-
const execFileAsync = promisify(execFile);
|
|
80
|
-
|
|
81
|
-
// Read once at module load, not per-mod — the host version can't
|
|
82
|
-
// change mid-process. createRequire is the simplest way to read JSON
|
|
83
|
-
// from an ESM file without an import-assertion syntax that varies
|
|
84
|
-
// across the Node versions this loader needs to run on.
|
|
85
|
-
const HOST_VERSION = createRequire(import.meta.url)('../package.json').version;
|
|
86
|
-
|
|
87
|
-
// Same order of magnitude as MAX_CUSTOM_VOCABS in src/localeRegistry.ts —
|
|
88
|
-
// a mods folder with thousands of entries is either a mistake (pointed
|
|
89
|
-
// at the wrong directory) or someone testing the loader's limits, not a
|
|
90
|
-
// real use case.
|
|
91
|
-
const MAX_MOD_FILES = 500;
|
|
92
|
-
|
|
93
|
-
// Extraction shells out to the system `tar` rather than adding a tar/
|
|
94
|
-
// gzip-parsing dependency — this package stays dependency-free by
|
|
95
|
-
// design (see README -> Providing Temporal for the same call made about
|
|
96
|
-
// the Temporal polyfill), and `tar` is effectively universal on systems
|
|
97
|
-
// that would run a Node CLI. If it's missing, the .tfmod fails with a
|
|
98
|
-
// clear reason instead of a cryptic ENOENT from execFile.
|
|
99
|
-
async function extractTfmod(archivePath, destDir) {
|
|
100
|
-
await execFileAsync('tar', ['-xzf', archivePath, '-C', destDir]);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// Validates the shape the loader actually reads off mod.json — a subset
|
|
104
|
-
// of Mod's fields (no `register`, since mod.json is data, not code) plus
|
|
105
|
-
// `main`, the entry-point filename inside the archive, plus fields only
|
|
106
|
-
// .tfmod mods get to declare (loose .mjs mods have no manifest to put
|
|
107
|
-
// them in): `temporalFmtVersion`, a semver range or exact version this
|
|
108
|
-
// mod was built against; `minApiLevel`, the lowest mod-API level this
|
|
109
|
-
// mod needs (see CURRENT_API_LEVEL in modWire.mjs — a separate axis from
|
|
110
|
-
// temporalFmtVersion, since a mod author knows which ctx functions they
|
|
111
|
-
// used far more reliably than which package version introduced them);
|
|
112
|
-
// `config`, a schema for user-editable settings (see modConfig.mjs); and
|
|
113
|
-
// `permissions`, the capabilities the mod wants, each marked required or
|
|
114
|
-
// optional. All are optional — a mod that doesn't need any just omits
|
|
115
|
-
// them.
|
|
116
|
-
function isValidManifest(value) {
|
|
117
|
-
if (typeof value !== 'object' || value === null) return false;
|
|
118
|
-
const v = value;
|
|
119
|
-
if (typeof v.name !== 'string' || v.name.length === 0) return false;
|
|
120
|
-
if (typeof v.main !== 'string' || v.main.length === 0) return false;
|
|
121
|
-
if (v.version !== undefined && typeof v.version !== 'string') return false;
|
|
122
|
-
if (v.requires !== undefined && !(Array.isArray(v.requires) && v.requires.every((r) => typeof r === 'string'))) return false;
|
|
123
|
-
if (v.priority !== undefined && typeof v.priority !== 'number') return false;
|
|
124
|
-
if (v.temporalFmtVersion !== undefined && typeof v.temporalFmtVersion !== 'string') return false;
|
|
125
|
-
if (v.minApiLevel !== undefined && !(Number.isInteger(v.minApiLevel) && v.minApiLevel >= 1)) return false;
|
|
126
|
-
if (v.config !== undefined && !isValidConfigSchema(v.config)) return false;
|
|
127
|
-
if (v.permissions !== undefined && !(Array.isArray(v.permissions) && v.permissions.every(isValidPermissionEntry))) return false;
|
|
128
|
-
return true;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Two shapes say the same thing: "fs:read" (a bare capability — the
|
|
132
|
-
// pre-required/optional format, still accepted so nothing that used to
|
|
133
|
-
// hard-fail on denial silently downgrades) or { "capability": "fs:read",
|
|
134
|
-
// "required": true }. A missing "required" means required: a mod that
|
|
135
|
-
// doesn't say is asking, not wishing.
|
|
136
|
-
function isValidPermissionEntry(p) {
|
|
137
|
-
if (typeof p === 'string') return true;
|
|
138
|
-
return (
|
|
139
|
-
typeof p === 'object' && p !== null &&
|
|
140
|
-
typeof p.capability === 'string' &&
|
|
141
|
-
(p.required === undefined || typeof p.required === 'boolean')
|
|
142
|
-
);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function normalizePermissions(permissions) {
|
|
146
|
-
return permissions.map((p) =>
|
|
147
|
-
typeof p === 'string' ? { capability: p, required: true } : { capability: p.capability, required: p.required ?? true }
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// Containment check for paths that come out of a .tfmod manifest. The
|
|
152
|
-
// manifest's "main" (and the mod name, for config lookups) is
|
|
153
|
-
// attacker-controlled archive data — the loader's documented contract is
|
|
154
|
-
// that a .tfmod is self-contained: code comes from inside the extraction
|
|
155
|
-
// dir, config comes from inside the config dir. Without this check a
|
|
156
|
-
// manifest could declare "main": "../../../some/file/outside.mjs" and
|
|
157
|
-
// have the loader import() a file that isn't part of the archive the
|
|
158
|
-
// user installed (breaking the "archive contents == executed code"
|
|
159
|
-
// review assumption), or a mod name like "../../secrets" that reads a
|
|
160
|
-
// config JSON from outside the config tree. Absolute paths, traversal
|
|
161
|
-
// segments, and symlinks that resolve outside the sandbox are all
|
|
162
|
-
// rejected before stat/import/read ever happens.
|
|
163
|
-
function isContainedInside(baseDir, targetPath) {
|
|
164
|
-
// resolve() collapses `..` segments textually and, when the target is
|
|
165
|
-
// absolute, discards the base entirely — either way the result is a
|
|
166
|
-
// canonical absolute path to compare against the base with
|
|
167
|
-
// path.relative: anything outside base prefixes with `..` (or lands on
|
|
168
|
-
// a different absolute root), which is exactly what we reject.
|
|
169
|
-
const base = resolve(baseDir);
|
|
170
|
-
const target = resolve(baseDir, targetPath);
|
|
171
|
-
const rel = relative(base, target);
|
|
172
|
-
return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// Validates the two manifest-controlled strings that reach the
|
|
176
|
-
// filesystem: mod.json's "main" (imported as code) and the mod name
|
|
177
|
-
// (used to find config/<name>.json). Returns a failure reason string on
|
|
178
|
-
// a bad value, undefined on a good one.
|
|
179
|
-
function manifestPathFailure(kind, value) {
|
|
180
|
-
if (isAbsolute(value)) {
|
|
181
|
-
return `mod.json "${kind}" must be a relative path inside the archive, got an absolute path "${value}"`;
|
|
182
|
-
}
|
|
183
|
-
if (value.split(/[\\/]/).includes('..')) {
|
|
184
|
-
return `mod.json "${kind}" must not contain ".." path segments (got "${value}") — a .tfmod mod runs only files from inside its own archive`;
|
|
185
|
-
}
|
|
186
|
-
return undefined;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// Extracts every .tfmod into its own subdirectory of `scratchDir` and
|
|
190
|
-
// reads mod.json out of each — no main.mjs gets imported here. That's
|
|
191
|
-
// the whole point of the manifest: the loader can find out a mod's
|
|
192
|
-
// name/requires/permissions (needed for pass-two ordering and the
|
|
193
|
-
// permission prompts) without running any of the mod's own code first.
|
|
194
|
-
async function readTfmodManifests(absDir, tfmodFiles, scratchDir) {
|
|
195
|
-
const entries = [];
|
|
196
|
-
const failed = [];
|
|
197
|
-
for (const file of tfmodFiles) {
|
|
198
|
-
const archivePath = join(absDir, file);
|
|
199
|
-
const extractDir = join(scratchDir, basename(file, '.tfmod'));
|
|
200
|
-
try {
|
|
201
|
-
// fs.mkdir with recursive:true instead of spawning the `mkdir`
|
|
202
|
-
// binary — `mkdir -p` doesn't exist as an executable on Windows
|
|
203
|
-
// (cmd.exe's mkdir is a shell builtin, not something spawn() can
|
|
204
|
-
// find on PATH), so this failed every .tfmod extraction there with
|
|
205
|
-
// ENOENT even though it worked fine on POSIX. fs.promises.mkdir is
|
|
206
|
-
// the actual cross-platform primitive for this, no subprocess or
|
|
207
|
-
// shell needed.
|
|
208
|
-
await mkdir(extractDir, { recursive: true });
|
|
209
|
-
await extractTfmod(archivePath, extractDir);
|
|
210
|
-
} catch (err) {
|
|
211
|
-
failed.push({ file, reason: `couldn't extract archive: ${err.message}` });
|
|
212
|
-
continue;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
let manifest;
|
|
216
|
-
try {
|
|
217
|
-
const raw = await readFile(join(extractDir, 'mod.json'), 'utf8');
|
|
218
|
-
manifest = JSON.parse(raw);
|
|
219
|
-
} catch (err) {
|
|
220
|
-
failed.push({ file, reason: `couldn't read mod.json from archive: ${err.message}` });
|
|
221
|
-
continue;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
if (!isValidManifest(manifest)) {
|
|
225
|
-
failed.push({
|
|
226
|
-
file,
|
|
227
|
-
reason:
|
|
228
|
-
'mod.json must have a "name" string and a "main" string, and — if present — "version" as a string, "requires" as a string array, "priority" as a number, "temporalFmtVersion" as a string, "minApiLevel" as a positive integer, "config" as a valid settings schema, and "permissions" as an array of capabilities or { capability, required } entries',
|
|
229
|
-
});
|
|
230
|
-
continue;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
const permissions = normalizePermissions(manifest.permissions ?? []);
|
|
234
|
-
|
|
235
|
-
// The permission list is closed on purpose. Anything a mod declares
|
|
236
|
-
// that no flag can back would be a permission the loader claims to
|
|
237
|
-
// enforce but can't, so this fails the mod with the full set of what
|
|
238
|
-
// exists and why the common absences (network, environment) don't.
|
|
239
|
-
const unknown = permissions.filter((p) => !GRANTABLE_PERMISSIONS.includes(p.capability)).map((p) => p.capability);
|
|
240
|
-
if (unknown.length > 0) {
|
|
241
|
-
failed.push({
|
|
242
|
-
file,
|
|
243
|
-
reason:
|
|
244
|
-
`mod.json "permissions" includes ${unknown.map((p) => `"${p}"`).join(', ')} — supported capabilities are ` +
|
|
245
|
-
`${GRANTABLE_PERMISSIONS.join(', ')}. Network access isn't offered because Node's permission model can't restrict it ` +
|
|
246
|
-
`on any supported version, and environment variables can't be granted, only scrubbed (they are).`,
|
|
247
|
-
});
|
|
248
|
-
continue;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// Checked here, before dependency ordering or register() ever run,
|
|
252
|
-
// so a version mismatch fails this one mod cleanly instead of
|
|
253
|
-
// surfacing later as a confusing runtime error from code that
|
|
254
|
-
// assumed an API this host version doesn't have.
|
|
255
|
-
if (manifest.temporalFmtVersion !== undefined) {
|
|
256
|
-
const versionCheck = checkVersionRange(HOST_VERSION, manifest.temporalFmtVersion);
|
|
257
|
-
if (!versionCheck.ok) {
|
|
258
|
-
failed.push({ file, reason: `"${manifest.name}" ${versionCheck.reason}` });
|
|
259
|
-
continue;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// Same reasoning, different axis: minApiLevel is what a mod author
|
|
264
|
-
// actually knows (the ctx functions they used), not the package
|
|
265
|
-
// version those functions shipped in. A mod that needs Level 3 and
|
|
266
|
-
// gets loaded on a Level 2 host would otherwise run right up until
|
|
267
|
-
// it calls ctx.registerFormatToken/ctx.log and hits a raw "is not a
|
|
268
|
-
// function" — this turns that into a clean failure before any mod
|
|
269
|
-
// code executes, naming the level gap directly. A mod declaring a
|
|
270
|
-
// level the host EXCEEDS is fine and says nothing; the level system
|
|
271
|
-
// is additive by design (see API_DOCS/), so a Level 1 mod runs
|
|
272
|
-
// unmodified on however far past Level 1 the host has gone.
|
|
273
|
-
if (manifest.minApiLevel !== undefined && manifest.minApiLevel > CURRENT_API_LEVEL) {
|
|
274
|
-
failed.push({
|
|
275
|
-
file,
|
|
276
|
-
reason: `"${manifest.name}" needs mod API level ${manifest.minApiLevel}, this host provides level ${CURRENT_API_LEVEL} — update temporal-fmt, or use a version of this mod built against an older API level.`,
|
|
277
|
-
});
|
|
278
|
-
continue;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
// "main" is archive-controlled data — reject absolute paths and
|
|
282
|
-
// traversal segments before join/stat/import can escape the
|
|
283
|
-
// extraction dir (see manifestPathFailure). This is a security
|
|
284
|
-
// boundary, not a nicety: the loader promises that a .tfmod only
|
|
285
|
-
// executes code from inside its own archive.
|
|
286
|
-
const mainFailure = manifestPathFailure('main', manifest.main);
|
|
287
|
-
if (mainFailure) {
|
|
288
|
-
failed.push({ file, reason: mainFailure });
|
|
289
|
-
continue;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const mainPath = join(extractDir, manifest.main);
|
|
293
|
-
try {
|
|
294
|
-
await stat(mainPath);
|
|
295
|
-
} catch {
|
|
296
|
-
failed.push({ file, reason: `mod.json names "main": "${manifest.main}", but that file isn't in the archive` });
|
|
297
|
-
continue;
|
|
298
|
-
}
|
|
299
|
-
// stat() follows symlinks — a tar member could be a symlink pointing
|
|
300
|
-
// outside the extraction dir. Re-check containment on the resolved
|
|
301
|
-
// real path so import() can't follow a link out of the sandbox even
|
|
302
|
-
// though the textual path looked clean.
|
|
303
|
-
const realMain = await realpath(mainPath).catch(() => mainPath);
|
|
304
|
-
const realExtractDir = await realpath(extractDir).catch(() => extractDir);
|
|
305
|
-
if (!isContainedInside(realExtractDir, realMain)) {
|
|
306
|
-
failed.push({
|
|
307
|
-
file,
|
|
308
|
-
reason: `mod.json "main" ("${manifest.main}") resolves outside the mod's extraction directory — a .tfmod mod runs only files from inside its own archive`,
|
|
309
|
-
});
|
|
310
|
-
continue;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
entries.push({
|
|
314
|
-
file,
|
|
315
|
-
kind: 'tfmod',
|
|
316
|
-
mod: { name: manifest.name, version: manifest.version, requires: manifest.requires, priority: manifest.priority },
|
|
317
|
-
// realMain/realExtractDir, not the raw paths: spawnWorker() grants
|
|
318
|
-
// --allow-fs-read on the realpath'd extraction dir (see realRoot()
|
|
319
|
-
// in modSandbox.mjs), because the OS temp dir is itself a symlink
|
|
320
|
-
// on macOS (/tmp -> /private/tmp, /var -> /private/var) and on some
|
|
321
|
-
// Windows setups. If the worker then imports the raw, non-realpath
|
|
322
|
-
// path, Node's permission model sees a path outside what was
|
|
323
|
-
// granted and refuses it — the grant and the access have to agree
|
|
324
|
-
// on which side of the symlink they're both talking about.
|
|
325
|
-
importPath: realMain,
|
|
326
|
-
extractDir: realExtractDir,
|
|
327
|
-
configSchema: manifest.config,
|
|
328
|
-
permissions,
|
|
329
|
-
});
|
|
330
|
-
}
|
|
331
|
-
return { entries, failed };
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
// Kahn's algorithm for the dependency order, with a `ready` queue kept
|
|
335
|
-
// sorted by (priority ascending, original file order) so ties resolve
|
|
336
|
-
// the same way every run.
|
|
337
|
-
function resolveLoadOrder(entries) {
|
|
338
|
-
const byName = new Map(entries.map((e) => [e.mod.name, e]));
|
|
339
|
-
const originalIndex = new Map(entries.map((e, i) => [e.mod.name, i]));
|
|
340
|
-
const failed = [];
|
|
341
|
-
const indegree = new Map(entries.map((e) => [e.mod.name, 0]));
|
|
342
|
-
const dependents = new Map(entries.map((e) => [e.mod.name, []]));
|
|
343
|
-
const missingDep = new Set();
|
|
344
|
-
|
|
345
|
-
for (const e of entries) {
|
|
346
|
-
for (const dep of e.mod.requires ?? []) {
|
|
347
|
-
if (!byName.has(dep)) {
|
|
348
|
-
failed.push({ file: e.file, reason: `requires "${dep}", which isn't present in mods/` });
|
|
349
|
-
missingDep.add(e.mod.name);
|
|
350
|
-
continue;
|
|
351
|
-
}
|
|
352
|
-
indegree.set(e.mod.name, indegree.get(e.mod.name) + 1);
|
|
353
|
-
dependents.get(dep).push(e.mod.name);
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
// A mod with a missing dependency is already excluded from the run.
|
|
358
|
-
// Dropping it from the graph means it can't gate mods that don't
|
|
359
|
-
// depend on it, and it won't get reported a second time by the cycle
|
|
360
|
-
// check below.
|
|
361
|
-
const remaining = entries.filter((e) => !missingDep.has(e.mod.name));
|
|
362
|
-
|
|
363
|
-
const sortKey = (e) => [e.mod.priority ?? 0, originalIndex.get(e.mod.name)];
|
|
364
|
-
const readyBefore = (a, b) => {
|
|
365
|
-
const [ap, ai] = sortKey(a);
|
|
366
|
-
const [bp, bi] = sortKey(b);
|
|
367
|
-
return ap !== bp ? ap - bp : ai - bi;
|
|
368
|
-
};
|
|
369
|
-
|
|
370
|
-
const ready = remaining.filter((e) => indegree.get(e.mod.name) === 0).sort(readyBefore);
|
|
371
|
-
const order = [];
|
|
372
|
-
|
|
373
|
-
while (ready.length > 0) {
|
|
374
|
-
const next = ready.shift();
|
|
375
|
-
order.push(next);
|
|
376
|
-
for (const depName of dependents.get(next.mod.name)) {
|
|
377
|
-
indegree.set(depName, indegree.get(depName) - 1);
|
|
378
|
-
if (indegree.get(depName) === 0) {
|
|
379
|
-
const depEntry = byName.get(depName);
|
|
380
|
-
const insertAt = ready.findIndex((e) => readyBefore(depEntry, e) < 0);
|
|
381
|
-
if (insertAt === -1) ready.push(depEntry);
|
|
382
|
-
else ready.splice(insertAt, 1, depEntry);
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
if (order.length < remaining.length) {
|
|
388
|
-
// Whatever's left has indegree > 0 with nothing left to unlock it —
|
|
389
|
-
// a cycle. Report each stuck mod with who it's still waiting on, so
|
|
390
|
-
// the author doesn't have to reconstruct the cycle by hand.
|
|
391
|
-
const orderedNames = new Set(order.map((e) => e.mod.name));
|
|
392
|
-
for (const e of remaining) {
|
|
393
|
-
if (orderedNames.has(e.mod.name)) continue;
|
|
394
|
-
const waitingOn = (e.mod.requires ?? []).filter((dep) => !orderedNames.has(dep) && byName.has(dep));
|
|
395
|
-
failed.push({ file: e.file, reason: `circular dependency — still waiting on: ${waitingOn.join(', ')}` });
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
return { order, failed };
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
// User config files live next to mods/, not inside it — config is the
|
|
403
|
-
// host machine's data (which mods/*.tfmod are just installed software),
|
|
404
|
-
// and keeping it out of mods/ means re-downloading or updating a
|
|
405
|
-
// .tfmod never touches a user's settings. Default sibling location:
|
|
406
|
-
// dir's parent + "config", so the common "./mods" + "./config" pairing
|
|
407
|
-
// needs no extra argument, but any dir can still pass its own.
|
|
408
|
-
async function readUserConfig(configDir, modName) {
|
|
409
|
-
// modName is archive-controlled (mod.json's "name") — it becomes part
|
|
410
|
-
// of a filesystem path here, so traversal/absolute forms are rejected
|
|
411
|
-
// before the read. The mod could read any file itself once its code
|
|
412
|
-
// runs, but config loading happens BEFORE register() (and for mods that
|
|
413
|
-
// fail validation entirely), so this path stays locked down on
|
|
414
|
-
// principle: the loader shouldn't hand archive data a read of files
|
|
415
|
-
// outside the config tree it owns.
|
|
416
|
-
const configFailure = manifestPathFailure('name', modName);
|
|
417
|
-
if (configFailure) {
|
|
418
|
-
return { value: undefined, path: join(configDir, `${modName}.json`), existed: false, error: configFailure };
|
|
419
|
-
}
|
|
420
|
-
const configPath = join(configDir, `${modName}.json`);
|
|
421
|
-
try {
|
|
422
|
-
const raw = await readFile(configPath, 'utf8');
|
|
423
|
-
return { value: JSON.parse(raw), path: configPath, existed: true };
|
|
424
|
-
} catch (err) {
|
|
425
|
-
if (err.code === 'ENOENT') return { value: undefined, path: configPath, existed: false };
|
|
426
|
-
// Malformed JSON or a permissions error is worth surfacing as a
|
|
427
|
-
// failure for this mod rather than silently falling back to
|
|
428
|
-
// defaults — a config file that exists but can't be read is very
|
|
429
|
-
// likely a mistake the user wants to know about.
|
|
430
|
-
return { value: undefined, path: configPath, existed: true, error: err.message };
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// A loose .mjs mod hitting a denied capability gets this appended to
|
|
435
|
-
// its failure line. The permission model's own error ("Access to this
|
|
436
|
-
// API has been restricted") doesn't say why nothing was granted or how
|
|
437
|
-
// to change it, and a mod that can't run is exactly the moment to.
|
|
438
|
-
function zeroPermissionHint(reason) {
|
|
439
|
-
if (!/Access to this API has been restricted/.test(reason)) return reason;
|
|
440
|
-
return (
|
|
441
|
-
`${reason} — this mod has no granted capabilities (a loose .mjs mod can't request any). ` +
|
|
442
|
-
`Package it as a .tfmod with a "permissions" field to ask for what it needs.`
|
|
443
|
-
);
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
export async function loadMods(dir = './mods', configDir = join(resolve(dir), '..', 'config')) {
|
|
447
|
-
const report = { loaded: [], downgraded: [], failed: [], conflicts: [] };
|
|
448
|
-
// realpath, not just resolve: resolve() only makes the path absolute,
|
|
449
|
-
// it doesn't follow symlinks, and the OS temp dir is a symlink on
|
|
450
|
-
// macOS (/var -> /private/var) and some Windows setups. Every mod path
|
|
451
|
-
// handed to the sandboxed worker is built by joining onto absDir, and
|
|
452
|
-
// spawnWorker() separately realpath's its --allow-fs-read roots (see
|
|
453
|
-
// realRoot() in modSandbox.mjs) — if absDir stayed on the symlinked
|
|
454
|
-
// side, the grant (realpath'd) and the actual import (not) would refer
|
|
455
|
-
// to the same file by two different paths and the permission model
|
|
456
|
-
// would refuse an import that should have been allowed.
|
|
457
|
-
const absDir = await realpath(resolve(dir)).catch(() => resolve(dir));
|
|
458
|
-
const absConfigDir = resolve(configDir);
|
|
459
|
-
// Permission answers live next to mods/, like config/ does: it's the
|
|
460
|
-
// host project's data about what it has agreed to, not part of the
|
|
461
|
-
// mods themselves, and keeping it beside the folder means it's the
|
|
462
|
-
// same "delete this to start over" story as the config dir.
|
|
463
|
-
const permissionsPath = join(resolve(dir), '..', '.temporal-fmt-permissions.json');
|
|
464
|
-
const sandboxCtx = await createSandboxContext();
|
|
465
|
-
|
|
466
|
-
let dirEntries;
|
|
467
|
-
try {
|
|
468
|
-
dirEntries = await readdir(absDir);
|
|
469
|
-
} catch (err) {
|
|
470
|
-
// No mods/ folder is the common case, not an error — most installs
|
|
471
|
-
// won't have one. Anything else (permissions, a file where a
|
|
472
|
-
// directory should be) is worth surfacing.
|
|
473
|
-
if (err.code === 'ENOENT') return report;
|
|
474
|
-
report.failed.push({ file: absDir, reason: `couldn't read mods directory: ${err.message}` });
|
|
475
|
-
return report;
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
if (dirEntries.length > MAX_MOD_FILES) {
|
|
479
|
-
report.failed.push({
|
|
480
|
-
file: absDir,
|
|
481
|
-
reason: `mods directory has ${dirEntries.length} entries, more than the ${MAX_MOD_FILES}-file limit — check this is the right folder`,
|
|
482
|
-
});
|
|
483
|
-
return report;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
for (const file of dirEntries.filter((f) => extname(f) === '.ts')) {
|
|
487
|
-
report.failed.push({
|
|
488
|
-
file,
|
|
489
|
-
reason: 'mods must be .mjs, not .ts — compile it first (tsc file.ts --module esnext --target esnext) and rename the output to .mjs',
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
const mjsFiles = dirEntries.filter((f) => extname(f) === '.mjs').sort();
|
|
494
|
-
const tfmodFiles = dirEntries.filter((f) => extname(f) === '.tfmod').sort();
|
|
495
|
-
|
|
496
|
-
// .tfmod archives get extracted to a scratch dir under the OS temp
|
|
497
|
-
// directory, cleaned up once this call is done regardless of outcome
|
|
498
|
-
// — extraction is a side effect of loading, not something that should
|
|
499
|
-
// accumulate on disk across runs.
|
|
500
|
-
let scratchDir = null;
|
|
501
|
-
let mjsEntries = [];
|
|
502
|
-
let tfmodEntries = [];
|
|
503
|
-
try {
|
|
504
|
-
// Pass one for .mjs: each file is imported inside its own
|
|
505
|
-
// zero-permission subprocess, which reports the default export's
|
|
506
|
-
// name/requires/priority back and exits. Nothing about a mod's
|
|
507
|
-
// top-level code has ever been safe to assume, and now none of it
|
|
508
|
-
// runs in this process even for discovery.
|
|
509
|
-
const mjsResult = await describeMjsMods(absDir, mjsFiles, sandboxCtx);
|
|
510
|
-
mjsEntries = mjsResult.entries;
|
|
511
|
-
report.failed.push(...mjsResult.failed);
|
|
512
|
-
|
|
513
|
-
if (tfmodFiles.length > 0) {
|
|
514
|
-
scratchDir = await mkdtemp(join(tmpdir(), 'temporal-fmt-tfmod-'));
|
|
515
|
-
const tfmodResult = await readTfmodManifests(absDir, tfmodFiles, scratchDir);
|
|
516
|
-
tfmodEntries = tfmodResult.entries;
|
|
517
|
-
report.failed.push(...tfmodResult.failed);
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
const entries = [...mjsEntries, ...tfmodEntries];
|
|
521
|
-
|
|
522
|
-
// Duplicate mod names would make the dependency graph ambiguous — a
|
|
523
|
-
// `requires: ['x']` is meaningless if two files both call themselves
|
|
524
|
-
// "x". Catch this before graph resolution rather than let whichever
|
|
525
|
-
// one a Map happened to see last quietly win. Duplicates across the
|
|
526
|
-
// two formats (an .mjs and a .tfmod both named "x") collide the same
|
|
527
|
-
// way as two of the same format would.
|
|
528
|
-
const seenNames = new Map();
|
|
529
|
-
const uniqueEntries = [];
|
|
530
|
-
for (const e of entries) {
|
|
531
|
-
const prior = seenNames.get(e.mod.name);
|
|
532
|
-
if (prior) {
|
|
533
|
-
report.failed.push({ file: e.file, reason: `mod name "${e.mod.name}" is already used by ${prior} — mod names must be unique across mods/` });
|
|
534
|
-
continue;
|
|
535
|
-
}
|
|
536
|
-
seenNames.set(e.mod.name, e.file);
|
|
537
|
-
uniqueEntries.push(e);
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
const { order, failed: orderFailures } = resolveLoadOrder(uniqueEntries);
|
|
541
|
-
report.failed.push(...orderFailures);
|
|
542
|
-
|
|
543
|
-
const registeredBy = new Map(); // "kind:key" -> [{ file, name }]
|
|
544
|
-
// Registrations so far this pass, in load order — each subprocess
|
|
545
|
-
// replays them locally so a mod that reads earlier state (a grammar
|
|
546
|
-
// built on another mod's vocab, say) sees what it would have
|
|
547
|
-
// in-process.
|
|
548
|
-
let priorRegistrations = [];
|
|
549
|
-
|
|
550
|
-
for (const entry of order) {
|
|
551
|
-
const { file, kind, mod, importPath, configSchema, permissions } = entry;
|
|
552
|
-
|
|
553
|
-
// Config only applies to .tfmod mods with a declared schema — a
|
|
554
|
-
// loose .mjs mod has no manifest to put a schema in, so it always
|
|
555
|
-
// gets {}, same as a .tfmod mod that didn't declare one. Every
|
|
556
|
-
// mod's register() can rely on a second argument existing;
|
|
557
|
-
// whether it has any keys depends on whether the mod asked for
|
|
558
|
-
// any.
|
|
559
|
-
let resolvedConfig = {};
|
|
560
|
-
if (configSchema) {
|
|
561
|
-
const userConfig = await readUserConfig(absConfigDir, mod.name);
|
|
562
|
-
if (userConfig.error) {
|
|
563
|
-
report.failed.push({ file, reason: `couldn't read config/${mod.name}.json: ${userConfig.error}` });
|
|
564
|
-
continue;
|
|
565
|
-
}
|
|
566
|
-
const { config, errors } = resolveConfig(configSchema, userConfig.value);
|
|
567
|
-
resolvedConfig = config;
|
|
568
|
-
// Bad individual keys don't fail the whole mod — they fall back
|
|
569
|
-
// to that key's default (see resolveConfig) and get reported
|
|
570
|
-
// here so the user can fix their config file, same spirit as a
|
|
571
|
-
// conflict report: surfaced, not silently swallowed, but not a
|
|
572
|
-
// hard stop either.
|
|
573
|
-
for (const errorMsg of errors) {
|
|
574
|
-
report.failed.push({ file: userConfig.path, reason: `${mod.name}: ${errorMsg} (using default)` });
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
// The permission gate, before any mod code runs: each requested
|
|
579
|
-
// capability is either already answered for this exact
|
|
580
|
-
// name@version (cache), asked of the user now (default no on
|
|
581
|
-
// empty input, or when there's no terminal to ask), or denied.
|
|
582
|
-
// Loose .mjs mods never get here with requests — they have no
|
|
583
|
-
// manifest — and run with nothing granted.
|
|
584
|
-
let grantedPermissions = new Set();
|
|
585
|
-
let denials = [];
|
|
586
|
-
if (permissions.length > 0) {
|
|
587
|
-
const resolved = await resolvePermissions({
|
|
588
|
-
modName: mod.name,
|
|
589
|
-
version: mod.version,
|
|
590
|
-
requested: permissions.map((p) => p.capability),
|
|
591
|
-
cachePath: permissionsPath,
|
|
592
|
-
});
|
|
593
|
-
grantedPermissions = resolved.granted;
|
|
594
|
-
denials = resolved.denials;
|
|
595
|
-
|
|
596
|
-
// A denied required capability is a hard no: the mod said it can't
|
|
597
|
-
// do its job without this, so running it with the capability
|
|
598
|
-
// missing would just move the failure somewhere more confusing.
|
|
599
|
-
// Fail it here, same as an unhandled crash, before any of its
|
|
600
|
-
// code gets a process.
|
|
601
|
-
const requiredDenied = permissions.filter((p) => p.required && !grantedPermissions.has(p.capability));
|
|
602
|
-
if (requiredDenied.length > 0) {
|
|
603
|
-
const caps = requiredDenied.map((p) => p.capability).join(', ');
|
|
604
|
-
const autoDenied = requiredDenied.some((p) =>
|
|
605
|
-
denials.find((d) => d.permission === p.capability)?.reason.startsWith('no terminal')
|
|
606
|
-
);
|
|
607
|
-
const grantCommand = requiredDenied.length === 1
|
|
608
|
-
? `node scripts/managePermissions.mjs grant ${mod.name}${mod.version ? `@${mod.version}` : ''} ${caps}`
|
|
609
|
-
: 'node scripts/managePermissions.mjs grant <mod> <capability> (one per denied capability)';
|
|
610
|
-
report.failed.push({
|
|
611
|
-
file,
|
|
612
|
-
reason:
|
|
613
|
-
`denied required permission: ${caps} — "${mod.name}" won't load without it` +
|
|
614
|
-
(autoDenied ? ' (denied automatically: no terminal to ask)' : '') +
|
|
615
|
-
`. Grant it with "${grantCommand}", or delete .temporal-fmt-permissions.json to re-ask everything.`,
|
|
616
|
-
});
|
|
617
|
-
continue;
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
// Anything denied at this point is optional — the mod runs with
|
|
622
|
-
// what it got, and the report says downgraded rather than loaded so
|
|
623
|
-
// "it ran with less than it asked for" is scannable at a glance.
|
|
624
|
-
const downgraded = permissions.some((p) => !p.required && !grantedPermissions.has(p.capability));
|
|
625
|
-
|
|
626
|
-
const sandboxRun = await runModInSandbox({
|
|
627
|
-
kind,
|
|
628
|
-
modPath: importPath,
|
|
629
|
-
modName: mod.name,
|
|
630
|
-
modReadRoot: kind === 'tfmod' ? entry.extractDir : absDir,
|
|
631
|
-
grantedPermissions,
|
|
632
|
-
config: resolvedConfig,
|
|
633
|
-
priorRegistrations,
|
|
634
|
-
sandboxCtx,
|
|
635
|
-
});
|
|
636
|
-
|
|
637
|
-
if (!sandboxRun.ok) {
|
|
638
|
-
const reason = kind === 'mjs' ? zeroPermissionHint(sandboxRun.reason) : sandboxRun.reason;
|
|
639
|
-
report.failed.push({ file, reason });
|
|
640
|
-
continue;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
// Host-side replay: the subprocess recorded what register()
|
|
644
|
-
// called, and this is where it actually takes effect — through
|
|
645
|
-
// the same tracked context an in-process mod would have used, so
|
|
646
|
-
// conflict detection, override exclusivity, and the report all
|
|
647
|
-
// behave exactly as they did before sandboxing.
|
|
648
|
-
const touched = [];
|
|
649
|
-
const diagnostics = [];
|
|
650
|
-
const trackedCtx = buildTrackedModContext(mod.name, (regKey) => touched.push(regKey), (event) => diagnostics.push(event));
|
|
651
|
-
try {
|
|
652
|
-
for (const record of sandboxRun.registrations) {
|
|
653
|
-
if (record.fn === 'createFormatter') {
|
|
654
|
-
trackedCtx.createFormatter(rehydrateFormatterOptions(record.args[0]));
|
|
655
|
-
} else if (record.fn === 'registerFormatToken') {
|
|
656
|
-
trackedCtx.registerFormatToken(rehydrateCustomToken(record.args[0]));
|
|
657
|
-
} else {
|
|
658
|
-
trackedCtx[record.fn](...record.args.map((a) => fromWire(a, sandboxCtx.hostTemporal)));
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
// log()/reportIssue() calls don't touch the registry, so they
|
|
662
|
-
// don't need fromWire's Temporal-instance rehydration the way
|
|
663
|
-
// registration args do — meta/detail already crossed as plain
|
|
664
|
-
// JSON-able data (see modWorker.mjs's toWire call for each).
|
|
665
|
-
// Replaying through trackedCtx (rather than just copying
|
|
666
|
-
// sandboxRun.diagnostics straight into the report) reuses its
|
|
667
|
-
// base fallback printing, same as an in-process mod's log()
|
|
668
|
-
// call would get, so sandboxed and in-process mods behave the
|
|
669
|
-
// same way here too.
|
|
670
|
-
for (const event of sandboxRun.diagnostics ?? []) {
|
|
671
|
-
if (event.source === 'log') {
|
|
672
|
-
trackedCtx.log(event.level, event.message, event.meta);
|
|
673
|
-
} else {
|
|
674
|
-
trackedCtx.reportIssue({ message: event.message, severity: event.level === 'error' ? 'error' : 'warning', detail: event.detail });
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
for (const fnName of sandboxRun.overrides) {
|
|
678
|
-
const method = `override${fnName[0].toUpperCase()}${fnName.slice(1)}`;
|
|
679
|
-
trackedCtx[method](makeOverrideBridgeImpl(sandboxRun.bridge, fnName, mod.name, sandboxCtx));
|
|
680
|
-
}
|
|
681
|
-
} catch (err) {
|
|
682
|
-
if (err instanceof OverrideConflictError) {
|
|
683
|
-
report.failed.push({ file, reason: err.message });
|
|
684
|
-
} else {
|
|
685
|
-
report.failed.push({ file, reason: `replaying "${mod.name}"'s registrations failed: ${err.message}` });
|
|
686
|
-
}
|
|
687
|
-
continue;
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
for (const { kind: regKind, key } of touched) {
|
|
691
|
-
const mapKey = `${regKind}:${key}`;
|
|
692
|
-
if (!registeredBy.has(mapKey)) registeredBy.set(mapKey, []);
|
|
693
|
-
registeredBy.get(mapKey).push({ file, name: mod.name });
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
priorRegistrations = [...priorRegistrations, ...sandboxRun.registrations];
|
|
697
|
-
|
|
698
|
-
(downgraded ? report.downgraded : report.loaded).push({
|
|
699
|
-
file,
|
|
700
|
-
name: mod.name,
|
|
701
|
-
version: mod.version,
|
|
702
|
-
kind,
|
|
703
|
-
diagnostics,
|
|
704
|
-
sandbox: {
|
|
705
|
-
permissionsRequested: permissions,
|
|
706
|
-
granted: [...grantedPermissions],
|
|
707
|
-
denials,
|
|
708
|
-
overrides: sandboxRun.overrides,
|
|
709
|
-
timeoutMs: sandboxRun.overrides.length > 0 ? runtimeTimeoutMs() : undefined,
|
|
710
|
-
memoryCeilingMb: sandboxRun.overrides.length > 0 ? memoryCeilingMb() : undefined,
|
|
711
|
-
},
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
for (const [mapKey, registrants] of registeredBy) {
|
|
716
|
-
if (registrants.length < 2) continue;
|
|
717
|
-
const [regKind, key] = mapKey.split(':');
|
|
718
|
-
report.conflicts.push({
|
|
719
|
-
kind: regKind,
|
|
720
|
-
key,
|
|
721
|
-
mods: registrants.map((r) => r.name),
|
|
722
|
-
winner: registrants[registrants.length - 1].name,
|
|
723
|
-
});
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
return report;
|
|
727
|
-
} finally {
|
|
728
|
-
if (scratchDir) {
|
|
729
|
-
await rm(scratchDir, { recursive: true, force: true }).catch(() => {});
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
export function formatModLoadReport(report) {
|
|
735
|
-
const lines = [];
|
|
736
|
-
const anyMods = (report.loaded.length > 0 || report.downgraded?.length > 0 || report.failed.length > 0);
|
|
737
|
-
if (anyMods && isExperimentalPermissionModel()) {
|
|
738
|
-
lines.push(' (sandboxing is experimental on this Node version — Node\'s permission model stabilized in 22.13)');
|
|
739
|
-
}
|
|
740
|
-
for (const m of report.loaded) {
|
|
741
|
-
lines.push(` loaded ${m.name}${m.version ? `@${m.version}` : ''} (${m.file})${sandboxSuffix(m)}`);
|
|
742
|
-
for (const line of diagnosticLines(m.diagnostics)) lines.push(line);
|
|
743
|
-
}
|
|
744
|
-
for (const m of report.downgraded ?? []) {
|
|
745
|
-
lines.push(` downgraded ${m.name}${m.version ? `@${m.version}` : ''} (${m.file})${sandboxSuffix(m)}`);
|
|
746
|
-
for (const line of diagnosticLines(m.diagnostics)) lines.push(line);
|
|
747
|
-
}
|
|
748
|
-
for (const f of report.failed) {
|
|
749
|
-
lines.push(` failed ${f.file}: ${f.reason}`);
|
|
750
|
-
}
|
|
751
|
-
for (const c of report.conflicts ?? []) {
|
|
752
|
-
lines.push(` conflict on ${c.kind} "${c.key}": ${c.mods.join(', ')} — "${c.winner}" wins (loaded last)`);
|
|
753
|
-
}
|
|
754
|
-
return lines.join('\n');
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
// One indented line per ctx.log()/ctx.reportIssue() call a mod made
|
|
758
|
-
// during register(), directly under its loaded/downgraded line — this
|
|
759
|
-
// is the whole point of both functions: visible in the report a person
|
|
760
|
-
// actually reads, not lost in a subprocess's discarded stdout/stderr
|
|
761
|
-
// (see modWorker.mjs's top comment on why a mod's own console.log can't
|
|
762
|
-
// reach the terminal at all under the sandbox).
|
|
763
|
-
function diagnosticLines(diagnostics) {
|
|
764
|
-
return (diagnostics ?? []).map((d) => {
|
|
765
|
-
const extra = d.source === 'log' && d.meta !== undefined ? ` ${JSON.stringify(d.meta)}`
|
|
766
|
-
: d.source === 'reportIssue' && d.detail !== undefined ? ` ${JSON.stringify(d.detail)}`
|
|
767
|
-
: '';
|
|
768
|
-
return ` [${d.level}] ${d.message}${extra}`;
|
|
769
|
-
});
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
function sandboxSuffix(m) {
|
|
773
|
-
if (!m.sandbox) return '';
|
|
774
|
-
const { permissionsRequested, granted, denials, overrides, timeoutMs, memoryCeilingMb: ceilingMb } = m.sandbox;
|
|
775
|
-
|
|
776
|
-
let permissionPart;
|
|
777
|
-
if (permissionsRequested.length === 0) {
|
|
778
|
-
permissionPart = m.kind === 'mjs'
|
|
779
|
-
? 'sandboxed: no permissions — a loose .mjs mod can\'t request any, package as .tfmod to ask for capabilities'
|
|
780
|
-
: 'sandboxed: no permissions requested';
|
|
781
|
-
} else {
|
|
782
|
-
const bits = permissionsRequested.map((p) =>
|
|
783
|
-
granted.includes(p.capability)
|
|
784
|
-
? `${p.capability} granted`
|
|
785
|
-
: `${p.capability} denied (optional)`
|
|
786
|
-
);
|
|
787
|
-
permissionPart = `sandboxed: ${bits.join(', ')}`;
|
|
788
|
-
const unprompted = denials.filter((d) => d.reason.startsWith('no terminal'));
|
|
789
|
-
if (unprompted.length > 0) {
|
|
790
|
-
permissionPart += ` (${unprompted.length} denied with no terminal to ask — re-run interactively or answer once in ${'.temporal-fmt-permissions.json'})`;
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
const parts = [permissionPart];
|
|
795
|
-
if (overrides.length > 0) {
|
|
796
|
-
const timeoutLabel = timeoutMs < 1000 ? `${timeoutMs}ms` : `${Math.round(timeoutMs / 1000)}s`;
|
|
797
|
-
const watched = `${timeoutLabel} timeout, ${ceilingMb}MB memory ceiling`;
|
|
798
|
-
parts.push(`${overrides.join(', ')} override${overrides.length > 1 ? 's' : ''} via subprocess, ${watched}`);
|
|
799
|
-
}
|
|
800
|
-
return ` [${parts.join('] [')}]`;
|
|
801
|
-
}
|