@triflare/fx 2.2.0-alpha.2 → 2.2.0-alpha.4

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.
@@ -0,0 +1,636 @@
1
+ /**
2
+ * Run runner.
3
+ *
4
+ * `fx run` reuses the headless PenguinMod VM from the testing subsystem, but
5
+ * its job is to execute project code rather than to assert on it. The run file
6
+ * is merged into an in-memory build so the compiler checks the entry point and
7
+ * every block it calls; the VM then starts `main` and steps until the scripts
8
+ * it started have finished.
9
+ */
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { build } from "../build.js";
13
+ import { loadProject } from "../vm.js";
14
+ import { loadConfigFrom, DEFAULT_RUN } from "../config.js";
15
+ import { discoverSources } from "../project.js";
16
+ import { DEFAULT_TEST_PATTERN } from "../test/discover.js";
17
+ import { discoverRuns } from "./discover.js";
18
+ import { loadProjectCatalog } from "../project-catalog.js";
19
+ import { productVersion } from "../brand.js";
20
+ import { installExternalIOGuard } from "../test/runner.js";
21
+ import { parseRuns } from "./parse.js";
22
+
23
+ /** Exit codes promised by `fx run`. */
24
+ export const RUN_EXIT = {
25
+ OK: 0,
26
+ FAILED: 1,
27
+ ERROR: 2,
28
+ INTERRUPTED: 3,
29
+ USAGE: 4,
30
+ };
31
+
32
+ /** A configuration, parsing or execution problem with the run itself. */
33
+ export class RunError extends Error {
34
+ constructor(message, options = {}) {
35
+ super(message, options.cause ? { cause: options.cause } : undefined);
36
+ this.name = "RunError";
37
+ this.exitCode = options.exitCode ?? RUN_EXIT.ERROR;
38
+ this.hint = options.hint;
39
+ this.file = options.file ?? null;
40
+ this.line = options.line ?? null;
41
+ this.column = options.column ?? null;
42
+ }
43
+ }
44
+
45
+ class RunTimeoutError extends Error {
46
+ constructor(timeout) {
47
+ super(`Run timed out after ${timeout}ms`);
48
+ this.name = "TimeoutError";
49
+ }
50
+ }
51
+
52
+ const sleepBuffer = new Int32Array(new SharedArrayBuffer(4));
53
+
54
+ /**
55
+ * Read one line from standard input synchronously, for `run.prompt`.
56
+ *
57
+ * A deadline makes a pending read cancellable. Node's default stdin handle is
58
+ * blocking, so switch it to non-blocking first; otherwise `readSync` would
59
+ * wait forever and the run timeout could never be observed.
60
+ */
61
+ export function readStdinLine({ deadline = null, timeout = null } = {}) {
62
+ const handle = process.stdin?._handle;
63
+ const restoreBlocking =
64
+ typeof handle?.setBlocking === "function"
65
+ ? () => handle.setBlocking(true)
66
+ : () => {};
67
+ if (typeof handle?.setBlocking === "function") handle.setBlocking(false);
68
+
69
+ const buffer = Buffer.alloc(1);
70
+ const bytes = [];
71
+ const timedOut = () => {
72
+ if (deadline != null && performance.now() >= deadline)
73
+ throw new RunTimeoutError(
74
+ timeout ?? Math.max(1, deadline - performance.now()),
75
+ );
76
+ };
77
+ try {
78
+ for (;;) {
79
+ timedOut();
80
+ let read;
81
+ try {
82
+ read = fs.readSync(0, buffer, 0, 1, null);
83
+ } catch (error) {
84
+ if (error.code === "EAGAIN") {
85
+ const remaining =
86
+ deadline == null ? 10 : Math.max(1, deadline - performance.now());
87
+ Atomics.wait(sleepBuffer, 0, 0, Math.min(10, remaining));
88
+ continue;
89
+ }
90
+ if (error.code === "EOF" || error.code === "EBADF") break;
91
+ throw error;
92
+ }
93
+ if (read === 0) break;
94
+ if (buffer[0] === 0x0a) break;
95
+ if (buffer[0] !== 0x0d) bytes.push(buffer[0]);
96
+ }
97
+ return Buffer.from(bytes).toString("utf8");
98
+ } finally {
99
+ restoreBlocking();
100
+ }
101
+ }
102
+
103
+ function defaultPrompt(message, options) {
104
+ if (message) process.stderr.write(`${message} `);
105
+ return readStdinLine(options);
106
+ }
107
+
108
+ /** Scratch-style truthiness for a compiled boolean input. */
109
+ function truthy(value) {
110
+ if (typeof value === "boolean") return value;
111
+ if (typeof value === "number") return value !== 0;
112
+ const text = String(value ?? "").trim();
113
+ return text !== "" && text !== "0" && !/^false$/i.test(text);
114
+ }
115
+
116
+ /**
117
+ * Tell the VM's IR compiler about the run opcodes. Without this, the compiler
118
+ * rejects extension-shaped opcodes even though their primitives are installed.
119
+ */
120
+ function registerRunBlockInfo(runtime) {
121
+ if (!Array.isArray(runtime._blockInfo)) return;
122
+ const args = (names) =>
123
+ Object.fromEntries(names.map((name) => [name, { compilerInfo: {} }]));
124
+ runtime._blockInfo.unshift({
125
+ id: "fxRun",
126
+ name: "Run",
127
+ blocks: [
128
+ {
129
+ info: {
130
+ opcode: "print",
131
+ blockType: "command",
132
+ arguments: args(["TEXT"]),
133
+ },
134
+ },
135
+ {
136
+ info: {
137
+ opcode: "warn",
138
+ blockType: "command",
139
+ arguments: args(["TEXT"]),
140
+ },
141
+ },
142
+ {
143
+ info: {
144
+ opcode: "error",
145
+ blockType: "command",
146
+ arguments: args(["TEXT"]),
147
+ },
148
+ },
149
+ {
150
+ info: {
151
+ opcode: "assert",
152
+ blockType: "command",
153
+ arguments: args(["CONDITION", "MESSAGE"]),
154
+ },
155
+ },
156
+ {
157
+ info: {
158
+ opcode: "prompt",
159
+ blockType: "reporter",
160
+ arguments: args(["TEXT"]),
161
+ },
162
+ },
163
+ ],
164
+ });
165
+ }
166
+
167
+ /** Deterministic pseudo-random source for a run. */
168
+ function mulberry32(seed) {
169
+ let state = seed | 0;
170
+ return () => {
171
+ state = (state + 0x6d2b79f5) | 0;
172
+ let t = Math.imul(state ^ (state >>> 15), 1 | state);
173
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
174
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
175
+ };
176
+ }
177
+
178
+ /** Input block id for the shapes a compiled and a loaded project use. */
179
+ function inputBlockId(input) {
180
+ if (Array.isArray(input)) return input[1] ?? null;
181
+ if (input && typeof input === "object")
182
+ return input.block ?? input.shadow ?? null;
183
+ return null;
184
+ }
185
+
186
+ /** Find the compiled `main` procedure on the stage, if it exists. */
187
+ function findMainProcedure(target) {
188
+ const blocks = target?.blocks?._blocks ?? {};
189
+ for (const block of Object.values(blocks)) {
190
+ if (
191
+ block.opcode !== "procedures_definition" &&
192
+ block.opcode !== "procedures_definition_return"
193
+ )
194
+ continue;
195
+ const protoId = inputBlockId(block.inputs?.custom_block);
196
+ const proto = typeof protoId === "string" ? blocks[protoId] : null;
197
+ const mutation = proto?.mutation;
198
+ if (String(mutation?.proccode ?? "") !== "main") continue;
199
+ return {
200
+ proccode: "main",
201
+ argumentids: "[]",
202
+ returns:
203
+ block.opcode === "procedures_definition_return" ||
204
+ mutation.returns === "true" ||
205
+ mutation.returns === true,
206
+ };
207
+ }
208
+ return null;
209
+ }
210
+
211
+ /** Add a synthetic top-level `procedures_call` that starts the entry point. */
212
+ function injectEntryCall(target, procedure, stamp) {
213
+ const callId = `${stamp}_main`;
214
+ target.blocks._blocks[callId] = {
215
+ id: callId,
216
+ opcode: "procedures_call",
217
+ next: null,
218
+ parent: null,
219
+ inputs: {},
220
+ fields: {},
221
+ shadow: false,
222
+ topLevel: true,
223
+ x: 0,
224
+ y: 0,
225
+ mutation: {
226
+ tagName: "mutation",
227
+ children: [],
228
+ proccode: procedure.proccode,
229
+ argumentids: procedure.argumentids,
230
+ warp: "false",
231
+ ...(procedure.returns ? { returns: "true" } : {}),
232
+ },
233
+ };
234
+ return callId;
235
+ }
236
+
237
+ /** Resolve files for a run, filtering them through the configured glob. */
238
+ function resolveRunFiles({ root, files, cwd, pattern }) {
239
+ if (files?.length)
240
+ return files.map((file) => {
241
+ const absolute = path.resolve(cwd, file);
242
+ return {
243
+ file: absolute,
244
+ relative: path.relative(root, absolute).split(path.sep).join("/"),
245
+ };
246
+ });
247
+ return discoverRuns({ dir: root, pattern });
248
+ }
249
+
250
+ /** Build the project plus the run entry files in memory. */
251
+ function buildRunProject({ root, loaded, runFiles, catalog, extensionUrls }) {
252
+ const runPaths = new Set(runFiles.map((entry) => entry.file));
253
+ const projectSources = discoverSources(root, {
254
+ testPattern: loaded.fx?.tests
255
+ ? loaded.fx.tests.pattern
256
+ : DEFAULT_TEST_PATTERN,
257
+ runPattern: loaded.fx?.run?.pattern,
258
+ })
259
+ .filter((file) => !runPaths.has(file))
260
+ .map((file) => ({ file, source: fs.readFileSync(file, "utf8") }));
261
+
262
+ const entries = runFiles.map((entry) => ({
263
+ file: entry.file,
264
+ source: fs.readFileSync(entry.file, "utf8"),
265
+ }));
266
+
267
+ return build({
268
+ sources: [...projectSources, ...entries],
269
+ dir: root,
270
+ projectConfig: loaded.project,
271
+ fxConfig: loaded.fx,
272
+ catalog,
273
+ extensionUrls,
274
+ runMode: true,
275
+ useConfigFile: false,
276
+ });
277
+ }
278
+
279
+ /**
280
+ * Execute a run file's `main` function in a fresh headless VM.
281
+ *
282
+ * @param {object} options
283
+ * @returns {Promise<object>}
284
+ */
285
+ async function runInVm({
286
+ root,
287
+ runFiles,
288
+ built,
289
+ config,
290
+ seed,
291
+ onPrint = () => {},
292
+ onOutput = () => {},
293
+ prompt = defaultPrompt,
294
+ }) {
295
+ const started = performance.now();
296
+ const deadline = started + config.timeout;
297
+ const startDate = new Date();
298
+ const ask = (message) =>
299
+ prompt === defaultPrompt
300
+ ? defaultPrompt(message, { deadline, timeout: config.timeout })
301
+ : prompt(message);
302
+ let vm;
303
+ try {
304
+ vm = await loadProject(built.sb3, {
305
+ allowProjectExtensions: config.allowProjectExtensions,
306
+ });
307
+ } catch (error) {
308
+ throw new RunError(
309
+ `could not load the project: ${error?.message ?? String(error)}`,
310
+ { cause: error },
311
+ );
312
+ }
313
+
314
+ const runtime = vm.runtime;
315
+ runtime.currentStepTime = 1000 / config.ticksPerSecond;
316
+ runtime.updateCurrentMSecs = () => {};
317
+
318
+ const prints = [];
319
+ const errors = [];
320
+ const warnings = [];
321
+ const prompts = [];
322
+ const originalError = console.error;
323
+ const originalWarn = console.warn;
324
+ const originalRandom = Math.random;
325
+ const compileErrorEvent =
326
+ runtime.constructor?.COMPILE_ERROR ?? "COMPILE_ERROR";
327
+ const onCompileError = (_target, error) =>
328
+ errors.push(error?.message ?? String(error));
329
+ runtime.on?.(compileErrorEvent, onCompileError);
330
+
331
+ console.error = (...args) => errors.push(args.map(String).join(" "));
332
+ console.warn = (...args) => warnings.push(args.map(String).join(" "));
333
+ Math.random = mulberry32(seed);
334
+ let explicitFailure = null;
335
+ const emit = (type, text) => onOutput({ type, text });
336
+
337
+ // The compiler only emits `fxRun_*` opcodes for the run build. Implement
338
+ // them directly on the runtime so running needs no extension file, catalog,
339
+ // or project trust decision.
340
+ Object.assign(runtime._primitives, {
341
+ fxRun_print(args) {
342
+ const line = String(args?.TEXT ?? "");
343
+ prints.push(line);
344
+ onPrint(line);
345
+ emit("print", line);
346
+ },
347
+ fxRun_warn(args) {
348
+ const line = String(args?.TEXT ?? "");
349
+ warnings.push(line);
350
+ emit("warn", line);
351
+ },
352
+ fxRun_error(args) {
353
+ const line = String(args?.TEXT ?? "");
354
+ errors.push(line);
355
+ explicitFailure ??= { name: "RunError", message: line };
356
+ emit("error", line);
357
+ },
358
+ fxRun_assert(args) {
359
+ if (truthy(args?.CONDITION)) return;
360
+ const line =
361
+ String(args?.MESSAGE ?? "").trim() || "assertion failed during fx run";
362
+ errors.push(line);
363
+ explicitFailure ??= { name: "AssertionError", message: line };
364
+ emit("error", line);
365
+ },
366
+ fxRun_prompt(args) {
367
+ const message = String(args?.TEXT ?? "");
368
+ emit("prompt", message);
369
+ const answer = String(ask(message) ?? "");
370
+ prompts.push({ message, answer });
371
+ return answer;
372
+ },
373
+ });
374
+ registerRunBlockInfo(runtime);
375
+
376
+ const stage = runtime.getTargetForStage?.();
377
+ const procedure = findMainProcedure(stage);
378
+ let callId = null;
379
+ let ticks = 0;
380
+ let failure = null;
381
+ let failureExit = RUN_EXIT.FAILED;
382
+
383
+ try {
384
+ if (!procedure)
385
+ throw new RunError(
386
+ "The project does not expose the run entry point `main`",
387
+ { exitCode: RUN_EXIT.ERROR },
388
+ );
389
+ if (typeof runtime._pushThread !== "function")
390
+ throw new RunError(
391
+ "This PenguinMod VM build cannot run project blocks by name",
392
+ { exitCode: RUN_EXIT.ERROR },
393
+ );
394
+
395
+ const stamp = `fxrun_${Date.now().toString(36)}`;
396
+ callId = injectEntryCall(stage, procedure, stamp);
397
+ const thread = runtime._pushThread(callId, stage);
398
+ if (!thread)
399
+ throw new RunError("Could not start the run entry point in the VM");
400
+
401
+ // Keep stepping until every script started by `main` has finished. A
402
+ // broadcast or a cloned script may outlive the entry-point thread itself.
403
+ while (runtime.threads.length > 0) {
404
+ if (performance.now() > deadline)
405
+ throw new RunTimeoutError(config.timeout);
406
+ try {
407
+ runtime.currentMSecs += 1000 / config.ticksPerSecond;
408
+ runtime._step();
409
+ } catch (error) {
410
+ errors.push(error?.message ?? String(error));
411
+ if (config.failOnRuntimeError) throw error;
412
+ }
413
+ ticks += 1;
414
+ if (explicitFailure) break;
415
+ }
416
+
417
+ if (explicitFailure) {
418
+ failure = explicitFailure;
419
+ failureExit = RUN_EXIT.FAILED;
420
+ } else if (config.failOnRuntimeError && errors.length > 0)
421
+ throw new Error(`runtime error: ${errors[0]}`);
422
+ } catch (error) {
423
+ failure = {
424
+ name: error?.name ?? "Error",
425
+ message: error?.message ?? String(error),
426
+ };
427
+ failureExit = error?.exitCode ?? RUN_EXIT.FAILED;
428
+ } finally {
429
+ runtime.off?.(compileErrorEvent, onCompileError);
430
+ console.error = originalError;
431
+ console.warn = originalWarn;
432
+ Math.random = originalRandom;
433
+ if (callId && stage?.blocks?._blocks) delete stage.blocks._blocks[callId];
434
+ try {
435
+ vm.stopAll();
436
+ } catch {
437
+ // A VM that failed to load has nothing to stop.
438
+ }
439
+ }
440
+
441
+ return {
442
+ dir: root,
443
+ version: productVersion(),
444
+ startTime: startDate.toISOString(),
445
+ durationMs: Math.round(performance.now() - started),
446
+ seed,
447
+ ticks,
448
+ files: runFiles.map((entry) => ({
449
+ file: entry.relative,
450
+ entry: "main",
451
+ status: failure ? "failed" : "passed",
452
+ error: failure,
453
+ })),
454
+ prints,
455
+ errors,
456
+ warnings,
457
+ prompts,
458
+ error: failure,
459
+ ok: !failure,
460
+ exitCode: failure ? failureExit : RUN_EXIT.OK,
461
+ };
462
+ }
463
+
464
+ let runQueue = Promise.resolve();
465
+
466
+ /**
467
+ * Run a project's entry point headlessly.
468
+ *
469
+ * @param {object} [options]
470
+ * @param {string} [options.dir] project directory
471
+ * @param {string[]} [options.files] explicit run files, relative to `cwd`
472
+ * @param {string} [options.cwd] base for explicit files
473
+ * @param {object} [options.loaded] preloaded project config
474
+ * @param {Record<string, object>} [options.catalog]
475
+ * @param {Record<string, string>} [options.extensionUrls]
476
+ * @param {number} [options.seed]
477
+ * @param {number} [options.timeout]
478
+ * @param {number} [options.ticksPerSecond]
479
+ * @param {boolean} [options.failOnRuntimeError]
480
+ * @param {boolean} [options.allowProjectExtensions] trust this project's extensions
481
+ * @param {boolean} [options.allowExternalIO] allow network access during the run
482
+ * @param {(line: string) => void} [options.onPrint]
483
+ * @param {(output: {type: "print"|"warn"|"error"|"prompt", text: string}) => void} [options.onOutput]
484
+ * @param {(message: string) => string} [options.prompt] read a line for `run.prompt`
485
+ * @returns {Promise<object>}
486
+ */
487
+ export function runRuns(options = {}) {
488
+ // Runs swap process-wide state (stdin, console, Math.random and the
489
+ // external-I/O guard), so overlapping API calls must not interleave.
490
+ const result = runQueue.then(() => runRunsNow(options));
491
+ runQueue = result.catch(() => {});
492
+ return result;
493
+ }
494
+
495
+ async function runRunsNow({
496
+ dir = process.cwd(),
497
+ files,
498
+ cwd = process.cwd(),
499
+ loaded: provided,
500
+ catalog,
501
+ extensionUrls,
502
+ seed,
503
+ timeout,
504
+ ticksPerSecond,
505
+ failOnRuntimeError,
506
+ allowProjectExtensions = false,
507
+ allowExternalIO = false,
508
+ onPrint = () => {},
509
+ onOutput = () => {},
510
+ prompt = defaultPrompt,
511
+ } = {}) {
512
+ const root = path.resolve(dir);
513
+ const loaded = provided ?? loadConfigFrom(root);
514
+ const configDir = loaded.path ? path.dirname(loaded.path) : root;
515
+ const settings = loaded.fx?.run;
516
+
517
+ if (!settings)
518
+ throw new RunError("Running is disabled in this project.", {
519
+ exitCode: RUN_EXIT.ERROR,
520
+ hint: 'run "fx feature run enable" to turn running on',
521
+ });
522
+
523
+ const config = {
524
+ ...DEFAULT_RUN,
525
+ ...settings,
526
+ seed: seed ?? settings.seed ?? DEFAULT_RUN.seed,
527
+ timeout: timeout ?? settings.timeout ?? DEFAULT_RUN.timeout,
528
+ ticksPerSecond:
529
+ ticksPerSecond ?? settings.ticksPerSecond ?? DEFAULT_RUN.ticksPerSecond,
530
+ failOnRuntimeError:
531
+ failOnRuntimeError ??
532
+ settings.failOnRuntimeError ??
533
+ DEFAULT_RUN.failOnRuntimeError,
534
+ allowProjectExtensions: Boolean(allowProjectExtensions),
535
+ allowExternalIO: Boolean(allowExternalIO),
536
+ };
537
+
538
+ const discovered = resolveRunFiles({
539
+ root,
540
+ files,
541
+ cwd,
542
+ pattern: settings.pattern,
543
+ });
544
+ if (discovered.length === 0)
545
+ throw new RunError(
546
+ `No run files matched ${JSON.stringify(settings.pattern)} under ${root}`,
547
+ { exitCode: RUN_EXIT.ERROR },
548
+ );
549
+
550
+ let parsedRuns;
551
+ try {
552
+ parsedRuns = parseRuns(
553
+ discovered.map((entry) => ({
554
+ file: entry.relative,
555
+ source: fs.readFileSync(entry.file, "utf8"),
556
+ })),
557
+ );
558
+ } catch (error) {
559
+ throw new RunError(error.message, {
560
+ cause: error,
561
+ file: error.file ?? null,
562
+ line: error.line ?? null,
563
+ column: error.column ?? null,
564
+ });
565
+ }
566
+ const runFiles = parsedRuns.map((parsed, index) => ({
567
+ ...parsed,
568
+ absolute: discovered[index].file,
569
+ relative: discovered[index].relative,
570
+ }));
571
+
572
+ let extensions = { catalog, extensionUrls, warnings: [] };
573
+ if (!catalog) extensions = await loadProjectCatalog({ configDir, loaded });
574
+
575
+ // A project extension is arbitrary JavaScript that runs with Node process
576
+ // access in the VM. Deny it without an explicit opt-in, just like `fx test`.
577
+ // Run blocks need no extension, so nothing is exempt from this check.
578
+ if (!config.allowProjectExtensions) {
579
+ const blocked = Object.keys(extensions.extensionUrls ?? {});
580
+ if (blocked.length > 0)
581
+ throw new RunError(
582
+ `Project extensions are blocked during fx run: ${blocked
583
+ .sort()
584
+ .map((id) => JSON.stringify(id))
585
+ .join(", ")}. ` +
586
+ 'Pass "--allow-project-extensions" to trust and load this project\'s extensions for this run.',
587
+ { exitCode: RUN_EXIT.ERROR },
588
+ );
589
+ }
590
+
591
+ let built;
592
+ try {
593
+ built = buildRunProject({
594
+ root,
595
+ loaded,
596
+ runFiles: runFiles.map((entry) => ({
597
+ file: entry.absolute,
598
+ relative: entry.relative,
599
+ })),
600
+ catalog: extensions.catalog,
601
+ extensionUrls: extensions.extensionUrls,
602
+ });
603
+ } catch (error) {
604
+ throw new RunError(error.message, {
605
+ cause: error,
606
+ file: error.file ?? null,
607
+ line: error.line ?? null,
608
+ column: error.column ?? null,
609
+ });
610
+ }
611
+
612
+ const restoreExternalIO = config.allowExternalIO
613
+ ? () => {}
614
+ : installExternalIOGuard(Object.values(extensions.extensionUrls ?? {}), {
615
+ label: "fx run",
616
+ });
617
+ try {
618
+ const result = await runInVm({
619
+ root,
620
+ runFiles: runFiles.map((entry) => ({
621
+ file: entry.absolute,
622
+ relative: entry.relative,
623
+ })),
624
+ built,
625
+ config,
626
+ seed: config.seed,
627
+ onPrint,
628
+ onOutput,
629
+ prompt,
630
+ });
631
+ result.warnings.unshift(...extensions.warnings);
632
+ return result;
633
+ } finally {
634
+ restoreExternalIO();
635
+ }
636
+ }