lich-cli 0.0.0-stage → 0.1.1

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,1345 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // The Worker. It runs inside each Side_Process, loads one package, runs the calls the parent
4
+ // sends and answers with Tagged_Values. It is CommonJS so the package loads with a plain
5
+ // `require`, the way most apps load it, and so the Network_Guard from --require is already in place (network blocked by a guard).
6
+ const fs = require("node:fs");
7
+ const nodeModule = require("node:module");
8
+ const nodePath = require("node:path");
9
+ const nodeUrl = require("node:url");
10
+ const nodeUtil = require("node:util");
11
+ const guard = require("./guard.cjs");
12
+ // ---------------------------------------------------------------------------------------------
13
+ // Taken before the package loads, so a package that changes these globals cannot change how the
14
+ // Worker reads its values or reports its environment.
15
+ const isProxy = nodeUtil.types.isProxy;
16
+ const isMap = nodeUtil.types.isMap;
17
+ const isSet = nodeUtil.types.isSet;
18
+ const bufferPrototype = Buffer.prototype;
19
+ const evalErrorPrototype = EvalError.prototype;
20
+ function builtin(proto, key) {
21
+ const fn = Object.getOwnPropertyDescriptor(proto, key)?.value;
22
+ if (typeof fn !== "function")
23
+ throw new Error(`the built-in ${key} is missing`);
24
+ return fn;
25
+ }
26
+ const mapForEach = builtin(Map.prototype, "forEach");
27
+ const mapClear = builtin(Map.prototype, "clear");
28
+ const mapSet = builtin(Map.prototype, "set");
29
+ const setForEach = builtin(Set.prototype, "forEach");
30
+ const setClear = builtin(Set.prototype, "clear");
31
+ const setAdd = builtin(Set.prototype, "add");
32
+ const promiseThen = builtin(Promise.prototype, "then");
33
+ const now = performance.now.bind(performance);
34
+ // A package that fakes the timers must not stop the Worker's own waits.
35
+ const setTimer = setTimeout;
36
+ const clearTimer = clearTimeout;
37
+ const setTurn = setImmediate;
38
+ const { locale, timeZone } = new Intl.DateTimeFormat().resolvedOptions();
39
+ const liveEnv = { node: process.versions.node, locale, timeZone };
40
+ // `Symbol.match` and the like, keyed by the name a soul writes for them, such as "Symbol.match".
41
+ // The description of a well-known symbol is that same name, so this also reads entry keys.
42
+ const wellKnownSymbols = new Map(Reflect.ownKeys(Symbol).flatMap((key) => {
43
+ const value = Object.getOwnPropertyDescriptor(Symbol, key)?.value;
44
+ return typeof key === "string" && typeof value === "symbol" ? [[`Symbol.${key}`, value]] : [];
45
+ }));
46
+ // The codes Node gives when a package has no CommonJS entry that `require` can load.
47
+ const ESM_ONLY_CODES = new Set([
48
+ "ERR_REQUIRE_ESM",
49
+ "ERR_REQUIRE_ASYNC_MODULE",
50
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
51
+ ]);
52
+ // The conditions an app's `import` of the package matches in Node.
53
+ const IMPORT_CONDITIONS = new Set(["node", "import", "default"]);
54
+ // What `encode` writes for a Proxy. Its members are never read, because every read would run a trap.
55
+ const proxyMarker = () => ({ t: "unsupported", v: "Proxy" });
56
+ // A Callback_Id that callbackIdFor gives to a function the package made. It holds a NUL, so no
57
+ // recorded Callback_Id can be the same, and `numberFreshCallbacks` replaces it after each encode.
58
+ const FRESH_CALLBACK = "\u0000fresh";
59
+ // ---------------------------------------------------------------------------------------------
60
+ // State of this Side_Process
61
+ let core;
62
+ let session;
63
+ let loadStarted = false;
64
+ let dying = false;
65
+ // Each kept live object by Instance_Id, and the first Instance_Id of each kept object for encode.
66
+ const instances = new Map();
67
+ const liveIds = new WeakMap();
68
+ // Each Callback_Stand_In mapped to its recorded Callback_Id, for encode.
69
+ const standInIds = new WeakMap();
70
+ // One Callback_Stand_In per Callback_Id for the life of the process, so a function the app passed
71
+ // twice keeps one identity, as it had in the app.
72
+ const callbackStandIns = new Map();
73
+ // Started: the number of Soul_Calls this process has started, the `at` of a settlement now.
74
+ let started = 0;
75
+ // The Call_Position of the call running now, and of the last one started, for an invocation's `during`.
76
+ let running;
77
+ let lastStarted;
78
+ // A State_Rebuild runs from the first `rebuild` message until `resume`. A `run` before or a
79
+ // `resume` ends the chance of one, since a rebuild only fits a fresh process.
80
+ let rebuilding = false;
81
+ let rebuildClosed = false;
82
+ // Live invocations per Callback_Id in the replay, and per Rebuild_Call position in a State_Rebuild.
83
+ const invocationCounts = new Map();
84
+ const rebuildCounts = new Map();
85
+ // Logged invocations since the last reply.
86
+ let invocations = [];
87
+ // ---------------------------------------------------------------------------------------------
88
+ // Small readers. None of them runs package code: a Proxy is checked first, and only own data
89
+ // properties are read.
90
+ class BrokenMessage extends Error {
91
+ name = "BrokenMessage";
92
+ }
93
+ function isObjectLike(value) {
94
+ return (typeof value === "object" && value !== null) || typeof value === "function";
95
+ }
96
+ function isRecord(value) {
97
+ return typeof value === "object" && value !== null && !Array.isArray(value);
98
+ }
99
+ // A module namespace throws for a binding that is not initialised yet, so the read is guarded.
100
+ function ownDescriptor(holder, key) {
101
+ try {
102
+ return Object.getOwnPropertyDescriptor(holder, key);
103
+ }
104
+ catch {
105
+ return undefined;
106
+ }
107
+ }
108
+ function ownData(holder, key) {
109
+ const desc = ownDescriptor(holder, key);
110
+ return desc !== undefined && "value" in desc ? desc.value : undefined;
111
+ }
112
+ function oneLine(text) {
113
+ return text.replace(/[\r\n]+/g, " ").trim();
114
+ }
115
+ function firstLine(text) {
116
+ return (text.split(/\r?\n/, 1)[0] ?? "").trim();
117
+ }
118
+ // For an error message in a reply or on stderr. A thrown value need not be an Error.
119
+ function describe(value) {
120
+ if (isObjectLike(value)) {
121
+ if (isProxy(value))
122
+ return "a Proxy was thrown";
123
+ const message = ownData(value, "message");
124
+ if (typeof message === "string")
125
+ return firstLine(message);
126
+ return "a value that is not an Error was thrown";
127
+ }
128
+ return firstLine(String(value));
129
+ }
130
+ function inheritsFrom(value, target) {
131
+ for (let p = Object.getPrototypeOf(value); p !== null; p = Object.getPrototypeOf(p)) {
132
+ if (p === target)
133
+ return true;
134
+ // The next read would run the Proxy's getPrototypeOf trap.
135
+ if (isProxy(p))
136
+ return false;
137
+ }
138
+ return false;
139
+ }
140
+ // ---------------------------------------------------------------------------------------------
141
+ // Exits. The reason goes to stderr first, because the parent names its last line in `worker-failed`.
142
+ function die(code, reason) {
143
+ if (dying)
144
+ return;
145
+ dying = true;
146
+ process.stderr.write(`${oneLine(reason)}\n`, () => process.exit(code));
147
+ }
148
+ process.on("uncaughtException", (error) => {
149
+ die(70, `uncaught exception from the package: ${describe(error)}`);
150
+ });
151
+ process.on("unhandledRejection", (reason) => {
152
+ die(70, `unhandled rejection from the package: ${describe(reason)}`);
153
+ });
154
+ let channelWrite;
155
+ // `process.send` only checks `process.connected` and then calls `process._send`, which writes
156
+ // through Node's own closure over the pipe. So the Worker keeps `_send` and removes both, since
157
+ // either one alone is enough to forge a reply. The raw pipe handle under a symbol goes too.
158
+ //
159
+ // Node drops every incoming message while `process.channel` is falsy, and its disconnect path
160
+ // asserts it is set. So the Control object, whose `fd`, `ref` and `unref` would give the package a
161
+ // way in, is swapped for an inert stand-in that holds only the empty pending-message list Node reads.
162
+ function closeChannelToPackage() {
163
+ const write = Reflect.get(process, "_send");
164
+ const control = process.channel;
165
+ if (typeof write !== "function" || typeof process.send !== "function" || !isObjectLike(control)) {
166
+ throw new Error("the Worker has no IPC channel");
167
+ }
168
+ const pendingKey = Object.getOwnPropertySymbols(control).find((key) => key.description === "kPendingMessages");
169
+ const handleKey = Object.getOwnPropertySymbols(process).find((key) => key.description === "kChannelHandle");
170
+ if (pendingKey === undefined)
171
+ throw new Error("this Node version keeps the IPC channel in a form the Worker does not know");
172
+ channelWrite = write.bind(process);
173
+ const standIn = Object.freeze(Object.assign(Object.create(null), { [pendingKey]: Object.freeze([]) }));
174
+ Reflect.deleteProperty(process, "send");
175
+ Reflect.deleteProperty(process, "_send");
176
+ Reflect.deleteProperty(process, "_channel");
177
+ if (handleKey !== undefined)
178
+ Reflect.deleteProperty(process, handleKey);
179
+ // Writable, because Node sets it to null when the channel closes.
180
+ Object.defineProperty(process, "channel", { value: standIn, writable: true, enumerable: true, configurable: true });
181
+ }
182
+ // The Reply_Token of this Side_Process. Set once in `start`, before any package code loads, and
183
+ // held only here, so the package cannot read it.
184
+ let replyToken;
185
+ function send(message) {
186
+ return new Promise((resolve, reject) => {
187
+ const write = channelWrite;
188
+ // The same check `process.send` makes before it writes.
189
+ if (write === undefined || replyToken === undefined || !process.connected) {
190
+ reject(new Error("the Worker's IPC channel is closed"));
191
+ return;
192
+ }
193
+ // The callback fires once the message is written, so a `running` message is out before a
194
+ // call that blocks the event loop starts.
195
+ write({ ...message, t: replyToken }, undefined, { swallowErrors: false }, (error) => {
196
+ if (error === null)
197
+ resolve();
198
+ else
199
+ reject(error);
200
+ });
201
+ });
202
+ }
203
+ // ---------------------------------------------------------------------------------------------
204
+ // Parent messages
205
+ function readMessage(raw) {
206
+ if (!isRecord(raw) || typeof raw.op !== "string")
207
+ throw new BrokenMessage("the message has no op");
208
+ switch (raw.op) {
209
+ case "load": {
210
+ if (loadStarted)
211
+ throw new BrokenMessage("a second load message");
212
+ const { packageName, soul, perCallMs } = raw;
213
+ if (typeof packageName !== "string" || packageName === "")
214
+ throw new BrokenMessage("load has no packageName");
215
+ if (!isRecord(soul) || !Array.isArray(soul.calls) || !isRecord(soul.valueTable)) {
216
+ throw new BrokenMessage("load has no soul with calls and a valueTable");
217
+ }
218
+ if (typeof perCallMs !== "number" || !Number.isSafeInteger(perCallMs) || perCallMs < 1) {
219
+ throw new BrokenMessage("load has no perCallMs of 1 or more");
220
+ }
221
+ return raw;
222
+ }
223
+ case "run":
224
+ case "rebuild": {
225
+ const op = raw.op;
226
+ if (session === undefined)
227
+ throw new BrokenMessage(`${op} before the package loaded`);
228
+ if (op === "run" && rebuilding)
229
+ throw new BrokenMessage("run during a State_Rebuild, before resume");
230
+ if (op === "rebuild" && rebuildClosed)
231
+ throw new BrokenMessage("rebuild after a run or a resume");
232
+ const count = session.soul.calls.length;
233
+ const { positions, single } = raw;
234
+ if (typeof single !== "boolean")
235
+ throw new BrokenMessage(`${op} has no single flag`);
236
+ const valid = Array.isArray(positions) &&
237
+ positions.every((p) => typeof p === "number" && Number.isSafeInteger(p) && p >= 0 && p < count);
238
+ if (!valid)
239
+ throw new BrokenMessage(`${op} has a position that is not a Call_Position of the soul`);
240
+ if (single && positions.length !== 1)
241
+ throw new BrokenMessage(`${op} with single set holds more than one position`);
242
+ return raw;
243
+ }
244
+ case "resume": {
245
+ if (session === undefined)
246
+ throw new BrokenMessage("resume before the package loaded");
247
+ const { next, callbackCounts } = raw;
248
+ const count = session.soul.calls.length;
249
+ if (typeof next !== "number" || !Number.isSafeInteger(next) || next < 0 || next > count) {
250
+ throw new BrokenMessage("resume has no next of 0 to the call count");
251
+ }
252
+ const counts = isRecord(callbackCounts) ? Object.values(callbackCounts) : undefined;
253
+ if (counts === undefined || !counts.every((n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0)) {
254
+ throw new BrokenMessage("resume has no callbackCounts of whole numbers");
255
+ }
256
+ return raw;
257
+ }
258
+ case "finish":
259
+ if (session === undefined)
260
+ throw new BrokenMessage("finish before the package loaded");
261
+ return { op: "finish" };
262
+ default:
263
+ throw new BrokenMessage(`unknown op ${JSON.stringify(raw.op)}`);
264
+ }
265
+ }
266
+ async function handle(raw) {
267
+ const message = readMessage(raw);
268
+ switch (message.op) {
269
+ case "load":
270
+ await load(message);
271
+ return;
272
+ case "run":
273
+ case "rebuild":
274
+ await run(message);
275
+ return;
276
+ case "resume":
277
+ resume(message);
278
+ return;
279
+ case "finish":
280
+ await finish();
281
+ return;
282
+ }
283
+ }
284
+ // ---------------------------------------------------------------------------------------------
285
+ // Loading the package
286
+ // The RegExps the package built, kept in first-seen order. `newRegExps` hands out the ones not
287
+ // yet sent. The cap stops a package that builds a new RegExp on every call.
288
+ const MAX_REGEXPS = 1000;
289
+ const seenRegExps = new Map();
290
+ let sentRegExps = 0;
291
+ let collecting = false;
292
+ function noteRegExp(args) {
293
+ if (seenRegExps.size >= MAX_REGEXPS)
294
+ return;
295
+ try {
296
+ // Built by the original constructor, so a RegExp or a pattern string reads the same way.
297
+ const made = new OriginalRegExp(args[0], args[1]);
298
+ const key = `${made.flags}/${made.source}`;
299
+ if (!seenRegExps.has(key))
300
+ seenRegExps.set(key, { source: made.source, flags: made.flags });
301
+ }
302
+ catch {
303
+ // The call itself throws the same error, which the package sees.
304
+ }
305
+ }
306
+ const OriginalRegExp = RegExp;
307
+ function installRegExpCollector() {
308
+ Object.defineProperty(globalThis, "RegExp", {
309
+ value: new Proxy(OriginalRegExp, {
310
+ construct(target, args, newTarget) {
311
+ noteRegExp(args);
312
+ return Reflect.construct(target, args, newTarget);
313
+ },
314
+ apply(target, thisArg, args) {
315
+ noteRegExp(args);
316
+ return Reflect.apply(target, thisArg, args);
317
+ },
318
+ }),
319
+ writable: true,
320
+ configurable: true,
321
+ enumerable: false,
322
+ });
323
+ collecting = true;
324
+ }
325
+ function newRegExps() {
326
+ if (!collecting)
327
+ return {};
328
+ const fresh = [...seenRegExps.values()].slice(sentRegExps);
329
+ sentRegExps = seenRegExps.size;
330
+ return { regexps: fresh };
331
+ }
332
+ async function load(message) {
333
+ loadStarted = true;
334
+ if (message.collectRegExps === true)
335
+ installRegExpCollector();
336
+ let moduleValue;
337
+ try {
338
+ moduleValue = await loadPackage(message.packageName);
339
+ }
340
+ catch (error) {
341
+ await send({ op: "load-failed", error: describe(error) });
342
+ return;
343
+ }
344
+ const { callbacks, callbacksDuring } = recordedCallbacks(message.soul);
345
+ session = { soul: message.soul, moduleValue, perCallMs: message.perCallMs, callbacks, callbacksDuring };
346
+ await send({ op: "ready", env: liveEnv });
347
+ }
348
+ function recordedCallbacks(soul) {
349
+ const callbacks = new Map();
350
+ const callbacksDuring = new Map();
351
+ const add = (map, key, call) => {
352
+ const list = map.get(key);
353
+ if (list === undefined)
354
+ map.set(key, [call]);
355
+ else
356
+ list.push(call);
357
+ };
358
+ for (const call of soul.calls) {
359
+ if (call.kind !== "callback" || call.callbackId === undefined)
360
+ continue;
361
+ add(callbacks, call.callbackId, call);
362
+ if (call.duringCall === undefined)
363
+ continue;
364
+ let byId = callbacksDuring.get(call.duringCall);
365
+ if (byId === undefined) {
366
+ byId = new Map();
367
+ callbacksDuring.set(call.duringCall, byId);
368
+ }
369
+ add(byId, call.callbackId, call);
370
+ }
371
+ return { callbacks, callbacksDuring };
372
+ }
373
+ async function loadPackage(name) {
374
+ // The cwd is the side's folder, so the lookup starts in its node_modules, as an app's would.
375
+ // The file need not exist: createRequire only takes its folder.
376
+ const load = nodeModule.createRequire(nodePath.join(process.cwd(), "index.cjs"));
377
+ try {
378
+ return load(name);
379
+ }
380
+ catch (error) {
381
+ const code = isObjectLike(error) && !isProxy(error) ? ownData(error, "code") : undefined;
382
+ if (!ESM_ONLY_CODES.has(code))
383
+ throw error;
384
+ }
385
+ const file = importEntry(load, name);
386
+ return (await import(nodeUrl.pathToFileURL(file).href));
387
+ }
388
+ function isFile(file) {
389
+ try {
390
+ return fs.statSync(file).isFile();
391
+ }
392
+ catch {
393
+ // Missing, or outside the read list, which the permission model reports as an error too.
394
+ return false;
395
+ }
396
+ }
397
+ function packageFolder(load, name) {
398
+ for (const dir of load.resolve.paths(name) ?? []) {
399
+ const folder = nodePath.join(dir, name);
400
+ if (isFile(nodePath.join(folder, "package.json")))
401
+ return folder;
402
+ }
403
+ throw new Error(`Cannot find the package ${name}`);
404
+ }
405
+ // The first target that the import conditions reach, in the key order of the exports map.
406
+ function conditionTarget(target) {
407
+ if (typeof target === "string")
408
+ return target;
409
+ if (Array.isArray(target)) {
410
+ for (const item of target) {
411
+ const found = conditionTarget(item);
412
+ if (found !== undefined)
413
+ return found;
414
+ }
415
+ return undefined;
416
+ }
417
+ if (isRecord(target)) {
418
+ for (const [key, value] of Object.entries(target)) {
419
+ if (!IMPORT_CONDITIONS.has(key))
420
+ continue;
421
+ const found = conditionTarget(value);
422
+ if (found !== undefined)
423
+ return found;
424
+ }
425
+ }
426
+ return undefined;
427
+ }
428
+ function rootExport(exportsField) {
429
+ if (isRecord(exportsField) && Object.keys(exportsField).some((key) => key.startsWith("."))) {
430
+ return Object.hasOwn(exportsField, ".") ? conditionTarget(exportsField["."]) : undefined;
431
+ }
432
+ return conditionTarget(exportsField);
433
+ }
434
+ // Resolves the root export the way Node's `import` would, for a package that `require` cannot load.
435
+ function importEntry(load, name) {
436
+ const folder = packageFolder(load, name);
437
+ // Node's own loader accepts a package.json that starts with a byte order mark, so this does too.
438
+ const text = fs.readFileSync(nodePath.join(folder, "package.json"), "utf8").replace(/^\uFEFF/, "");
439
+ const manifest = JSON.parse(text);
440
+ const fields = isRecord(manifest) ? manifest : {};
441
+ if (fields.exports !== undefined && fields.exports !== null) {
442
+ const target = rootExport(fields.exports);
443
+ if (target === undefined)
444
+ throw new Error(`The package ${name} has no root export for import`);
445
+ return nodePath.resolve(folder, target);
446
+ }
447
+ const main = [fields.module, fields.main].find((field) => typeof field === "string" && field !== "");
448
+ const base = nodePath.resolve(folder, main ?? "index.js");
449
+ // `main` may leave out the extension or name a folder, as the CommonJS lookup allows.
450
+ const candidates = [base, `${base}.js`, `${base}.mjs`, nodePath.join(base, "index.js"), nodePath.join(base, "index.mjs")];
451
+ return candidates.find(isFile) ?? base;
452
+ }
453
+ // A tableRef stands for its Value_Table entry. The step count stops a table that leads back to itself.
454
+ function follow(node) {
455
+ const table = session?.soul.valueTable ?? {};
456
+ let out = node;
457
+ for (let steps = 0; out.t === "tableRef"; steps++) {
458
+ if (steps > Object.keys(table).length || !Object.hasOwn(table, out.key))
459
+ return undefined;
460
+ const next = table[out.key];
461
+ if (next === undefined)
462
+ return undefined;
463
+ out = next;
464
+ }
465
+ return out;
466
+ }
467
+ function instanceIdOf(node) {
468
+ return "instanceId" in node && typeof node.instanceId === "string" ? node.instanceId : undefined;
469
+ }
470
+ // The property key of an entry in a live value. A unique symbol is made fresh in each process, so
471
+ // it cannot be named and its entry is skipped.
472
+ function entryKey(keyNode) {
473
+ const key = follow(keyNode);
474
+ if (key?.t === "string")
475
+ return key.v;
476
+ if (key?.t === "symbol" && key.description !== undefined) {
477
+ if (key.kind === "registered")
478
+ return Symbol.for(key.description);
479
+ if (key.kind === "well-known")
480
+ return wellKnownSymbols.get(key.description);
481
+ }
482
+ return undefined;
483
+ }
484
+ const liveKeys = (entries) => entries.map((entry) => entryKey(entry.key));
485
+ // `decode` defines the entries in order and adds no symbol key of its own, so the k-th symbol
486
+ // entry is the k-th own symbol of the decoded object. That also finds a unique symbol.
487
+ const decodedKeys = (entries, holder) => {
488
+ const symbols = Object.getOwnPropertySymbols(holder);
489
+ let next = 0;
490
+ return entries.map((entry) => {
491
+ const key = follow(entry.key);
492
+ if (key?.t === "string")
493
+ return key.v;
494
+ if (key?.t === "symbol")
495
+ return symbols[next++];
496
+ return undefined;
497
+ });
498
+ };
499
+ function propertyChild(holder, key, node, out) {
500
+ const desc = ownDescriptor(holder, key);
501
+ if (desc === undefined || !("value" in desc))
502
+ return;
503
+ out.push({
504
+ node,
505
+ value: desc.value,
506
+ place: (value) => {
507
+ Object.defineProperty(holder, key, { value });
508
+ },
509
+ });
510
+ }
511
+ function entryChildren(entries, holder, keysFor, out) {
512
+ if (entries === undefined)
513
+ return;
514
+ const keys = keysFor(entries, holder);
515
+ entries.forEach((entry, i) => {
516
+ const key = keys[i];
517
+ if (entry.value !== undefined && key !== undefined)
518
+ propertyChild(holder, key, entry.value, out);
519
+ });
520
+ }
521
+ // The parts of `holder` that sit where the node's child Tagged_Values sit. A promise or an
522
+ // iterator has no parts yet: its contents are walked when it settles or yields.
523
+ function childrenOf(node, holder, keysFor) {
524
+ const children = [];
525
+ switch (node.t) {
526
+ case "array":
527
+ if (!Array.isArray(holder))
528
+ break;
529
+ node.v.forEach((item, i) => {
530
+ if (!("hole" in item))
531
+ propertyChild(holder, String(i), item, children);
532
+ });
533
+ entryChildren(node.props, holder, keysFor, children);
534
+ break;
535
+ case "object":
536
+ entryChildren(node.v, holder, keysFor, children);
537
+ break;
538
+ case "class":
539
+ entryChildren(node.own, holder, keysFor, children);
540
+ break;
541
+ case "error": {
542
+ if (node.code !== undefined)
543
+ propertyChild(holder, "code", node.code, children);
544
+ if (node.cause !== undefined)
545
+ propertyChild(holder, "cause", node.cause, children);
546
+ const list = ownData(holder, "errors");
547
+ if (node.errors !== undefined && Array.isArray(list) && !isProxy(list)) {
548
+ node.errors.forEach((item, i) => propertyChild(list, String(i), item, children));
549
+ }
550
+ entryChildren(node.own, holder, keysFor, children);
551
+ break;
552
+ }
553
+ case "map": {
554
+ if (!isMap(holder))
555
+ break;
556
+ const pairs = [];
557
+ Reflect.apply(mapForEach, holder, [(value, key) => { pairs.push([key, value]); }]);
558
+ let changed = false;
559
+ node.v.forEach(([keyNode, valueNode], i) => {
560
+ const pair = pairs[i];
561
+ if (pair === undefined)
562
+ return;
563
+ children.push({ node: keyNode, value: pair[0], place: (value) => { pair[0] = value; changed = true; } }, { node: valueNode, value: pair[1], place: (value) => { pair[1] = value; changed = true; } });
564
+ });
565
+ const finish = () => {
566
+ if (!changed)
567
+ return;
568
+ Reflect.apply(mapClear, holder, []);
569
+ for (const [key, value] of pairs)
570
+ Reflect.apply(mapSet, holder, [key, value]);
571
+ };
572
+ return { children, finish };
573
+ }
574
+ case "set": {
575
+ if (!isSet(holder))
576
+ break;
577
+ const items = [];
578
+ Reflect.apply(setForEach, holder, [(item) => { items.push(item); }]);
579
+ let changed = false;
580
+ node.v.forEach((itemNode, i) => {
581
+ if (i >= items.length)
582
+ return;
583
+ children.push({ node: itemNode, value: items[i], place: (value) => { items[i] = value; changed = true; } });
584
+ });
585
+ const finish = () => {
586
+ if (!changed)
587
+ return;
588
+ Reflect.apply(setClear, holder, []);
589
+ for (const item of items)
590
+ Reflect.apply(setAdd, holder, [item]);
591
+ };
592
+ return { children, finish };
593
+ }
594
+ default:
595
+ break;
596
+ }
597
+ return { children };
598
+ }
599
+ // The live value that stands in place of a decoded part, or undefined to keep the decoded part.
600
+ // A kept object wins over a Callback_Stand_In, because a function the package made and the app
601
+ // passed back must reach the package as that same function.
602
+ function liveFor(node) {
603
+ const id = instanceIdOf(node);
604
+ if (id !== undefined && instances.has(id))
605
+ return { value: instances.get(id) };
606
+ if (node.t === "function")
607
+ return { value: standInFor(node) };
608
+ return undefined;
609
+ }
610
+ // Puts each kept live object in place of the decoded part that carries its Instance_Id. Keyed by
611
+ // the decoded object, so every place that shares it through a `ref` gets the same substitute.
612
+ function substitute(tagged, decoded) {
613
+ let out = decoded;
614
+ const substitutes = new Map();
615
+ const walked = new Set();
616
+ const stack = [{ node: tagged, value: decoded, place: (value) => { out = value; } }];
617
+ for (let task = stack.pop(); task !== undefined; task = stack.pop()) {
618
+ if (typeof task === "function") {
619
+ task();
620
+ continue;
621
+ }
622
+ const { value, place } = task;
623
+ const node = follow(task.node);
624
+ if (node === undefined || !isObjectLike(value))
625
+ continue;
626
+ if (substitutes.has(value)) {
627
+ place(substitutes.get(value));
628
+ continue;
629
+ }
630
+ const live = liveFor(node);
631
+ if (live !== undefined) {
632
+ substitutes.set(value, live.value);
633
+ place(live.value);
634
+ continue;
635
+ }
636
+ if (walked.has(value))
637
+ continue;
638
+ walked.add(value);
639
+ const { children, finish } = childrenOf(node, value, decodedKeys);
640
+ if (finish !== undefined)
641
+ stack.push(finish);
642
+ // Pushed in reverse so they pop in document order, which places a shared part before its refs.
643
+ for (const child of children.toReversed())
644
+ stack.push(child);
645
+ }
646
+ return out;
647
+ }
648
+ // Keeps each live object found where the recorded value carries an Instance_Id. An Instance_Id
649
+ // already held keeps its first object, so a revival that gives back a different object at that
650
+ // place encodes without the id and shows as a difference.
651
+ function keep(recorded, live, counterparts) {
652
+ if (recorded === undefined)
653
+ return;
654
+ const stack = [{ node: recorded, value: live }];
655
+ for (let item = stack.pop(); item !== undefined; item = stack.pop()) {
656
+ const node = follow(item.node);
657
+ const value = item.value;
658
+ if (node === undefined || !isObjectLike(value))
659
+ continue;
660
+ const id = instanceIdOf(node);
661
+ if (id !== undefined && !instances.has(id)) {
662
+ instances.set(id, value);
663
+ if (!liveIds.has(value))
664
+ liveIds.set(value, id);
665
+ }
666
+ if ((node.t === "promise" || node.t === "iterator") && counterparts !== undefined && !counterparts.has(value)) {
667
+ counterparts.set(value, node);
668
+ }
669
+ if (node.t === "ref" || isProxy(value))
670
+ continue;
671
+ for (const child of childrenOf(node, value, liveKeys).children)
672
+ stack.push(child);
673
+ }
674
+ }
675
+ // ---------------------------------------------------------------------------------------------
676
+ // Encoding live values
677
+ // Gives each function the package made `cb0`, `cb1` and so on in document order, skipping every
678
+ // Callback_Id the value already holds. That is what `encode` does by default with an empty
679
+ // `idPrefix`, so such a function gets the same id on both sides and in a soul recorded with the defaults.
680
+ function numberFreshCallbacks(root) {
681
+ const fresh = [];
682
+ const held = new Set();
683
+ const stack = [root];
684
+ for (let item = stack.pop(); item !== undefined; item = stack.pop()) {
685
+ if (typeof item !== "object" || item === null)
686
+ continue;
687
+ const fields = item;
688
+ if (fields.t === "function" && typeof fields.callbackId === "string") {
689
+ if (fields.callbackId === FRESH_CALLBACK)
690
+ fresh.push(fields);
691
+ else
692
+ held.add(fields.callbackId);
693
+ }
694
+ const values = Object.values(fields);
695
+ for (let i = values.length - 1; i >= 0; i--)
696
+ stack.push(values[i]);
697
+ }
698
+ let next = 0;
699
+ for (const fn of fresh) {
700
+ let id;
701
+ do {
702
+ id = `cb${next}`;
703
+ next += 1;
704
+ } while (held.has(id));
705
+ fn.callbackId = id;
706
+ }
707
+ }
708
+ function encodeLive(value) {
709
+ const encoded = core.encode(value, {
710
+ instanceIdFor: (obj) => liveIds.get(obj),
711
+ callbackIdFor: (fn) => standInIds.get(fn) ?? FRESH_CALLBACK,
712
+ isProxy,
713
+ bufferPrototype,
714
+ });
715
+ numberFreshCallbacks(encoded.value);
716
+ return encoded;
717
+ }
718
+ function readState(members, target) {
719
+ const proxy = isProxy(target);
720
+ const values = Object.keys(members).map((member) => [member, proxy ? undefined : ownData(target, member)]);
721
+ return { proxy, values };
722
+ }
723
+ function encodeState(raw) {
724
+ const out = {};
725
+ for (const [member, value] of raw.values) {
726
+ const tagged = raw.proxy ? proxyMarker() : encodeLive(value).value;
727
+ // A data property, so a member named `__proto__` cannot reach the prototype setter.
728
+ Object.defineProperty(out, member, { value: tagged, writable: true, enumerable: true, configurable: true });
729
+ }
730
+ return out;
731
+ }
732
+ // ---------------------------------------------------------------------------------------------
733
+ // Sandbox_Block
734
+ // Node writes Windows paths in permission errors in the long form, which a reader does not expect.
735
+ function plainPath(resource) {
736
+ if (resource.startsWith("\\\\?\\UNC\\"))
737
+ return `\\\\${resource.slice(8)}`;
738
+ if (resource.startsWith("\\\\?\\"))
739
+ return resource.slice(4);
740
+ return resource;
741
+ }
742
+ function classifyBlock(thrown) {
743
+ if (!isObjectLike(thrown) || isProxy(thrown))
744
+ return undefined;
745
+ const code = ownData(thrown, "code");
746
+ const message = ownData(thrown, "message");
747
+ const text = typeof message === "string" ? message : "";
748
+ if (code === "ERR_ACCESS_DENIED") {
749
+ const permission = ownData(thrown, "permission");
750
+ const resource = ownData(thrown, "resource");
751
+ const restriction = permission === "FileSystemRead" || permission === "FileSystemWrite" ? "file-access" : "process";
752
+ const name = typeof permission === "string" && permission !== "" ? permission : code;
753
+ const where = typeof resource === "string" && resource !== "" ? ` ${plainPath(resource)}` : "";
754
+ return { restriction, detail: oneLine(`${name}${where}`) };
755
+ }
756
+ if (code === "ERR_DLOPEN_DISABLED")
757
+ return { restriction: "process", detail: oneLine(text || code) };
758
+ // The guard's message already says "network blocked by a guard". The fallback keeps that wording
759
+ // for an error that lost its message.
760
+ if (code === "ERR_LICH_NETWORK_BLOCKED") {
761
+ return { restriction: "network", detail: oneLine(text || "network blocked by a guard") };
762
+ }
763
+ if (inheritsFrom(thrown, evalErrorPrototype) && /code generation from strings disallowed/i.test(text)) {
764
+ return { restriction: "code-generation", detail: oneLine(text) };
765
+ }
766
+ return undefined;
767
+ }
768
+ // A `member` of the form `Symbol.<name>` names that well-known symbol, such as `Symbol.match`.
769
+ function memberKey(member) {
770
+ return wellKnownSymbols.get(member) ?? member;
771
+ }
772
+ function prepare(position, current) {
773
+ const call = current.soul.calls[position];
774
+ if (call === undefined)
775
+ throw new BrokenMessage(`no call at Call_Position ${position}`);
776
+ if (call.kind === "callback")
777
+ throw new BrokenMessage(`call ${position} is a callback call, which is never sent`);
778
+ const onInstance = call.kind === "method" || call.kind === "set" || (call.kind === "get" && call.instanceId !== undefined);
779
+ let target;
780
+ let key;
781
+ if (onInstance) {
782
+ if (call.instanceId === undefined || call.member === undefined) {
783
+ throw new Error(`call ${position} names no instanceId and member`);
784
+ }
785
+ target = instances.get(call.instanceId);
786
+ if (target === undefined)
787
+ return { kind: "missing-instance", call };
788
+ key = memberKey(call.member);
789
+ }
790
+ else if (call.exportPath === undefined) {
791
+ throw new Error(`call ${position} names no exportPath`);
792
+ }
793
+ const checks = { isProxy, bufferPrototype };
794
+ const args = call.args.map((arg) => substitute(arg, core.decode(arg, current.soul.valueTable, checks)));
795
+ return { kind: "ready", call, target, key, args };
796
+ }
797
+ // A module value with no own `default` is its own default, as Node's `import x from` gives
798
+ // for a CommonJS module.
799
+ function exportTarget(moduleValue, exportPath) {
800
+ const skipDefault = exportPath[0] === "default" && !(isObjectLike(moduleValue) && Object.hasOwn(moduleValue, "default"));
801
+ let holder = undefined;
802
+ let value = moduleValue;
803
+ for (const segment of skipDefault ? exportPath.slice(1) : exportPath) {
804
+ holder = value;
805
+ // A plain property read, so getters run and a missing holder throws, as in the app.
806
+ value = value[segment];
807
+ }
808
+ return { holder, value };
809
+ }
810
+ function invoke(prepared, moduleValue) {
811
+ const { call, target, key, args } = prepared;
812
+ const instance = target;
813
+ switch (call.kind) {
814
+ case "call": {
815
+ const { holder, value } = exportTarget(moduleValue, call.exportPath ?? []);
816
+ return Reflect.apply(value, holder, args);
817
+ }
818
+ case "construct": {
819
+ const { value } = exportTarget(moduleValue, call.exportPath ?? []);
820
+ return Reflect.construct(value, args);
821
+ }
822
+ case "get":
823
+ if (key === undefined)
824
+ return exportTarget(moduleValue, call.exportPath ?? []).value;
825
+ return instance[key];
826
+ case "method":
827
+ return Reflect.apply(instance[key], target, args);
828
+ case "set":
829
+ // Strict mode, so a failed assignment throws as it would in an ES module.
830
+ instance[key] = args[0];
831
+ return undefined;
832
+ case "callback":
833
+ throw new BrokenMessage("a callback call is never sent");
834
+ }
835
+ }
836
+ // Every outcome carries the guard's attempts since the last call, so an attempt the package
837
+ // caught still shows.
838
+ function withAttempts(parts) {
839
+ const attempts = guard.takeAttempts();
840
+ if (attempts.length > 0)
841
+ parts.networkAttempts = attempts;
842
+ return parts;
843
+ }
844
+ function execute(prepared, current) {
845
+ if (prepared.kind === "missing-instance") {
846
+ return { outcome: { kind: "not-run", reason: "missing-instance", ...withAttempts({}) }, pending: [] };
847
+ }
848
+ const { call, target } = prepared;
849
+ const parts = {};
850
+ // Instance_State is read only for a call on a kept live object, the only target a soul's
851
+ // stateBefore and stateAfter describe.
852
+ if (call.stateBefore !== undefined && target !== undefined) {
853
+ parts.stateBefore = encodeState(readState(call.stateBefore, target));
854
+ }
855
+ let threw = false;
856
+ let value;
857
+ const start = now();
858
+ try {
859
+ value = invoke(prepared, current.moduleValue);
860
+ }
861
+ catch (error) {
862
+ threw = true;
863
+ value = error;
864
+ }
865
+ parts.ms = now() - start;
866
+ const after = call.stateAfter !== undefined && target !== undefined ? readState(call.stateAfter, target) : undefined;
867
+ withAttempts(parts);
868
+ const block = threw ? classifyBlock(value) : undefined;
869
+ const counterparts = new Map();
870
+ if (block === undefined)
871
+ keep(threw ? call.thrown : call.result, value, counterparts);
872
+ // Encoded after the result walk, so a member that holds a kept object carries its Instance_Id.
873
+ if (after !== undefined)
874
+ parts.stateAfter = encodeState(after);
875
+ if (block !== undefined) {
876
+ return { outcome: { kind: "blocked", restriction: block.restriction, detail: block.detail, ...parts }, pending: [] };
877
+ }
878
+ const encoded = encodeLive(value);
879
+ const outcome = threw
880
+ ? { kind: "threw", value: encoded.value, ...parts }
881
+ : { kind: "returned", value: encoded.value, ...parts };
882
+ return { outcome, live: value, pending: encoded.pending, counterparts };
883
+ }
884
+ // ---------------------------------------------------------------------------------------------
885
+ // Callback_Stand_Ins
886
+ function standInFor(node) {
887
+ const known = callbackStandIns.get(node.callbackId);
888
+ if (known !== undefined)
889
+ return known;
890
+ const callbackId = node.callbackId;
891
+ // A plain function and not an arrow, so the package can still call it with `new`.
892
+ const standIn = function (...args) {
893
+ return answer(callbackId, args);
894
+ };
895
+ // Some packages read a callback's `length` to choose how to call it, so it keeps the recorded one.
896
+ Object.defineProperty(standIn, "name", { value: node.name, configurable: true });
897
+ Object.defineProperty(standIn, "length", { value: node.length, configurable: true });
898
+ callbackStandIns.set(callbackId, standIn);
899
+ standInIds.set(standIn, callbackId);
900
+ return standIn;
901
+ }
902
+ function noMoreCalls(callbackId) {
903
+ return new Error(`the soul records no more calls of Callback_Id ${callbackId}`);
904
+ }
905
+ // Invocation k of a Callback_Id answers as the k-th recorded call of it did.
906
+ function answer(callbackId, args) {
907
+ const current = session;
908
+ if (current === undefined)
909
+ throw new Error(`Callback_Id ${callbackId} was called before the package loaded`);
910
+ const during = running ?? lastStarted;
911
+ if (rebuilding)
912
+ return answerInRebuild(current, callbackId, args, during);
913
+ const index = invocationCounts.get(callbackId) ?? 0;
914
+ invocationCounts.set(callbackId, index + 1);
915
+ const recorded = current.callbacks.get(callbackId)?.[index];
916
+ if (recorded !== undefined)
917
+ args.forEach((arg, i) => keep(recorded.args[i], arg));
918
+ // Each argument gets its own encode, as the recorder writes them, so no two share Reference_Ids.
919
+ const encodedArgs = args.map((arg) => encodeLive(arg).value);
920
+ const invocation = { callbackId, index, args: encodedArgs };
921
+ if (during !== undefined)
922
+ invocation.during = during;
923
+ if (recorded === undefined)
924
+ invocation.extra = true;
925
+ invocations.push(invocation);
926
+ if (recorded === undefined)
927
+ throw noMoreCalls(callbackId);
928
+ return reply(recorded, current);
929
+ }
930
+ // A Rebuild_Call only has to bring the state back, so it answers from the calls recorded during
931
+ // that same Call_Position and logs nothing. Its invocations were logged before the restart.
932
+ function answerInRebuild(current, callbackId, args, during) {
933
+ if (during === undefined)
934
+ throw noMoreCalls(callbackId);
935
+ let counts = rebuildCounts.get(during);
936
+ if (counts === undefined) {
937
+ counts = new Map();
938
+ rebuildCounts.set(during, counts);
939
+ }
940
+ const index = counts.get(callbackId) ?? 0;
941
+ counts.set(callbackId, index + 1);
942
+ const recorded = current.callbacksDuring.get(during)?.get(callbackId)?.[index];
943
+ if (recorded === undefined)
944
+ throw noMoreCalls(callbackId);
945
+ args.forEach((arg, i) => keep(recorded.args[i], arg));
946
+ return reply(recorded, current);
947
+ }
948
+ // Gives back the recorded result, or throws the recorded thrown value, as the app's function did.
949
+ function reply(recorded, current) {
950
+ const checks = { isProxy, bufferPrototype };
951
+ if (recorded.thrown !== undefined) {
952
+ throw substitute(recorded.thrown, core.decode(recorded.thrown, current.soul.valueTable, checks));
953
+ }
954
+ if (recorded.result === undefined)
955
+ return undefined;
956
+ return substitute(recorded.result, core.decode(recorded.result, current.soul.valueTable, checks));
957
+ }
958
+ let watchedPromises = [];
959
+ let watchedIterators = [];
960
+ // The outcome value of each reported call that holds a promise or an iterator, and the calls
961
+ // whose value moved on since the last reply.
962
+ const outcomeValues = new Map();
963
+ const moved = new Set();
964
+ const TIMED_OUT = Symbol("timed out");
965
+ function nextTurn() {
966
+ return new Promise((resolve) => {
967
+ setTurn(() => resolve());
968
+ });
969
+ }
970
+ async function withDeadline(value, deadline) {
971
+ let timer;
972
+ const late = new Promise((resolve) => {
973
+ timer = setTimer(() => resolve(TIMED_OUT), Math.max(0, deadline - now()));
974
+ });
975
+ try {
976
+ // The race handles a rejection that comes after the deadline too, so it is never unhandled.
977
+ return await Promise.race([Promise.resolve(value).then((settled) => ({ value: settled })), late]);
978
+ }
979
+ finally {
980
+ clearTimer(timer);
981
+ }
982
+ }
983
+ // The node a pending handle's JSON Pointer names.
984
+ function nodeAt(root, pointer) {
985
+ let at = root;
986
+ if (pointer === "")
987
+ return at;
988
+ for (const raw of pointer.slice(1).split("/")) {
989
+ if (typeof at !== "object" || at === null)
990
+ return undefined;
991
+ at = at[raw.replaceAll("~1", "/").replaceAll("~0", "~")];
992
+ }
993
+ return at;
994
+ }
995
+ // The live promise or iterator at each pending node of a value just encoded from `live`. Encode
996
+ // read the same object a moment ago, so the k-th symbol entry is its k-th own symbol.
997
+ function livePending(root, live) {
998
+ const out = new Map();
999
+ const stack = [{ node: root, value: live }];
1000
+ for (let item = stack.pop(); item !== undefined; item = stack.pop()) {
1001
+ const { node, value } = item;
1002
+ if (!isObjectLike(value))
1003
+ continue;
1004
+ if (node.t === "promise" || node.t === "iterator") {
1005
+ out.set(node, value);
1006
+ continue;
1007
+ }
1008
+ if (node.t === "ref" || isProxy(value))
1009
+ continue;
1010
+ for (const child of childrenOf(node, value, decodedKeys).children)
1011
+ stack.push(child);
1012
+ }
1013
+ return out;
1014
+ }
1015
+ // Watches every promise and iterator in an encoded value, paired with its recorded counterpart.
1016
+ function watch(root, live, pending, counterparts, owner) {
1017
+ if (pending.length === 0)
1018
+ return;
1019
+ const lives = livePending(root, live);
1020
+ for (const handle of pending) {
1021
+ const node = nodeAt(root, handle.pointer);
1022
+ const object = lives.get(node);
1023
+ if (object === undefined)
1024
+ continue;
1025
+ const recorded = counterparts?.get(object);
1026
+ if (handle.kind === "promise") {
1027
+ watchPromise(handle, object, recorded?.t === "promise" ? recorded : undefined, owner);
1028
+ }
1029
+ else {
1030
+ const recordedIterator = recorded?.t === "iterator" ? recorded : undefined;
1031
+ const async = node.async;
1032
+ // With no recorded iterator at its place, the recording gives no way to read it.
1033
+ watchedIterators.push({ handle, owner, live: object, async, recorded: recordedIterator, pulled: 0, stopped: recordedIterator === undefined });
1034
+ }
1035
+ }
1036
+ }
1037
+ function markMoved(owner) {
1038
+ if (owner.reported)
1039
+ moved.add(owner.position);
1040
+ }
1041
+ function watchPromise(handle, promise, recorded, owner) {
1042
+ const { promise: done, resolve } = Promise.withResolvers();
1043
+ const entry = { handle, owner, recorded: recorded?.state, done, settled: false, givenUp: false };
1044
+ const settle = (kind, value) => {
1045
+ entry.settled = true;
1046
+ try {
1047
+ completeSettlement(entry, kind, value);
1048
+ }
1049
+ catch (error) {
1050
+ die(71, `the Worker failed: ${describe(error)}`);
1051
+ }
1052
+ resolve();
1053
+ };
1054
+ try {
1055
+ // The built-in `then`, attached at once, so a rejection is never unhandled and a package that
1056
+ // replaces `then` cannot hide the settlement.
1057
+ Reflect.apply(promiseThen, promise, [
1058
+ (value) => settle("fulfilled", value),
1059
+ (reason) => settle("rejected", reason),
1060
+ ]);
1061
+ }
1062
+ catch {
1063
+ // An object that inherits from Promise.prototype without being a promise never settles.
1064
+ return;
1065
+ }
1066
+ watchedPromises.push(entry);
1067
+ }
1068
+ function completeSettlement(entry, kind, value) {
1069
+ const state = entry.recorded;
1070
+ const recordedValue = state?.status === "fulfilled" ? state.value : state?.status === "rejected" ? state.reason : undefined;
1071
+ const counterparts = new Map();
1072
+ keep(recordedValue, value, counterparts);
1073
+ const encoded = encodeLive(value);
1074
+ watch(encoded.value, value, encoded.pending, counterparts, entry.owner);
1075
+ const at = started;
1076
+ core.completePending(entry.handle, kind === "fulfilled" ? { kind, value: encoded.value, at } : { kind, reason: encoded.value, at });
1077
+ markMoved(entry.owner);
1078
+ }
1079
+ function iteratorYielded(entry, value) {
1080
+ const recorded = entry.recorded?.yields[entry.pulled]?.value;
1081
+ entry.pulled += 1;
1082
+ const counterparts = new Map();
1083
+ keep(recorded, value, counterparts);
1084
+ const encoded = encodeLive(value);
1085
+ watch(encoded.value, value, encoded.pending, counterparts, entry.owner);
1086
+ core.completePending(entry.handle, { kind: "yield", value: encoded.value, at: started });
1087
+ markMoved(entry.owner);
1088
+ }
1089
+ function iteratorEnded(entry, end, value) {
1090
+ entry.stopped = true;
1091
+ if (end === "early") {
1092
+ core.completePending(entry.handle, { kind: "end", end, at: started });
1093
+ }
1094
+ else {
1095
+ const counterparts = new Map();
1096
+ keep(entry.recorded?.end.value, value, counterparts);
1097
+ const encoded = encodeLive(value);
1098
+ watch(encoded.value, value, encoded.pending, counterparts, entry.owner);
1099
+ // A return or a throw always has a value, even undefined, as the recorder writes it.
1100
+ core.completePending(entry.handle, { kind: "end", end, value: encoded.value, at: started });
1101
+ }
1102
+ markMoved(entry.owner);
1103
+ }
1104
+ // One `next` call, read as a `for...of` loop reads it. With `last` set, this is the pull that
1105
+ // should find the recorded end, so the iterator is not pulled again whatever it gives.
1106
+ async function pull(entry, deadline, last) {
1107
+ let step;
1108
+ try {
1109
+ let result = Reflect.apply(entry.live.next, entry.live, []);
1110
+ if (entry.async) {
1111
+ const settled = await withDeadline(result, deadline);
1112
+ if (settled === TIMED_OUT) {
1113
+ entry.stopped = true;
1114
+ return;
1115
+ }
1116
+ result = settled.value;
1117
+ }
1118
+ if (!isObjectLike(result))
1119
+ throw new TypeError("the iterator result is not an object");
1120
+ const fields = result;
1121
+ step = { done: Boolean(fields.done), value: fields.value };
1122
+ }
1123
+ catch (error) {
1124
+ step = { threw: error };
1125
+ }
1126
+ if ("threw" in step)
1127
+ iteratorEnded(entry, "throw", step.threw);
1128
+ else if (step.done)
1129
+ iteratorEnded(entry, "return", step.value);
1130
+ else {
1131
+ iteratorYielded(entry, step.value);
1132
+ if (last)
1133
+ entry.stopped = true;
1134
+ }
1135
+ }
1136
+ // What a `break` out of a `for...of` loop does: call `return` when the iterator has one.
1137
+ async function stopEarly(entry, deadline) {
1138
+ try {
1139
+ const stop = entry.live.return;
1140
+ if (typeof stop === "function") {
1141
+ const result = Reflect.apply(stop, entry.live, []);
1142
+ if (entry.async && (await withDeadline(result, deadline)) === TIMED_OUT) {
1143
+ entry.stopped = true;
1144
+ return;
1145
+ }
1146
+ }
1147
+ }
1148
+ catch (error) {
1149
+ iteratorEnded(entry, "throw", error);
1150
+ return;
1151
+ }
1152
+ iteratorEnded(entry, "early");
1153
+ }
1154
+ // Pulls every recorded yield with an `at` of `limit` or less, then ends the iterator the recorded
1155
+ // way once its recorded end is due. Returns whether it pulled or ended anything.
1156
+ async function advance(entry, limit, deadline) {
1157
+ const recorded = entry.recorded;
1158
+ let acted = false;
1159
+ while (!entry.stopped && recorded !== undefined) {
1160
+ const next = recorded.yields[entry.pulled];
1161
+ if (next !== undefined) {
1162
+ if (next.at > limit)
1163
+ break;
1164
+ await pull(entry, deadline, false);
1165
+ acted = true;
1166
+ continue;
1167
+ }
1168
+ const end = recorded.end;
1169
+ if (end.kind === "unfinished") {
1170
+ entry.stopped = true;
1171
+ break;
1172
+ }
1173
+ if (end.at > limit)
1174
+ break;
1175
+ if (end.kind === "early")
1176
+ await stopEarly(entry, deadline);
1177
+ else
1178
+ await pull(entry, deadline, true);
1179
+ acted = true;
1180
+ }
1181
+ return acted;
1182
+ }
1183
+ // Brings the live promises and iterators to where the recording had them by Settlement_Position
1184
+ // `limit`. A settlement or a yield can hold another promise or iterator, so this repeats until a
1185
+ // round finds nothing more to do. Each wait shares one deadline.
1186
+ async function settleUpTo(limit, deadline) {
1187
+ for (;;) {
1188
+ const waiting = watchedPromises.filter((entry) => !entry.settled && !entry.givenUp && entry.recorded !== undefined && entry.recorded.status !== "pending" && entry.recorded.at <= limit);
1189
+ if (waiting.length > 0 && (await withDeadline(Promise.all(waiting.map((entry) => entry.done)), deadline)) === TIMED_OUT) {
1190
+ for (const entry of waiting)
1191
+ if (!entry.settled)
1192
+ entry.givenUp = true;
1193
+ }
1194
+ let acted = false;
1195
+ for (const entry of [...watchedIterators]) {
1196
+ if (await advance(entry, limit, deadline))
1197
+ acted = true;
1198
+ }
1199
+ watchedPromises = watchedPromises.filter((entry) => !entry.settled && !entry.givenUp);
1200
+ watchedIterators = watchedIterators.filter((entry) => !entry.stopped);
1201
+ if (waiting.length === 0 && !acted)
1202
+ return;
1203
+ }
1204
+ }
1205
+ // Before call p. The turn of the event loop comes while Started still counts the calls before,
1206
+ // as the pause between two messages does when calls go one at a time, so work the package put on
1207
+ // a microtask or setImmediate lands at the same Settlement_Position in a Batch. Then Started is
1208
+ // p and the settlements the recording had by then are awaited.
1209
+ async function beforeCall(position, current) {
1210
+ await nextTurn();
1211
+ started = position;
1212
+ await settleUpTo(position, now() + current.perCallMs);
1213
+ }
1214
+ function takeInvocations() {
1215
+ const out = invocations;
1216
+ invocations = [];
1217
+ return out;
1218
+ }
1219
+ // The latest value of each call whose promise or iterator moved on, except the calls whose
1220
+ // outcome goes in the same reply and so already holds it.
1221
+ function takeUpdates(sent) {
1222
+ const updates = [];
1223
+ for (const position of [...moved].sort((a, b) => a - b)) {
1224
+ const value = outcomeValues.get(position);
1225
+ if (value !== undefined && !sent.has(position))
1226
+ updates.push({ position, value });
1227
+ }
1228
+ moved.clear();
1229
+ return updates;
1230
+ }
1231
+ // ---------------------------------------------------------------------------------------------
1232
+ // Messages that run calls
1233
+ // One path for a Batch, one call at a time and a State_Rebuild, so the outcomes never depend on
1234
+ // Batch_Size and a Rebuild_Call does what the call did the first time.
1235
+ async function runPositions(positions, single, current) {
1236
+ const ran = [];
1237
+ for (const position of positions) {
1238
+ // Before prepare, because a settlement can keep the live object this call targets.
1239
+ await beforeCall(position, current);
1240
+ const prepared = prepare(position, current);
1241
+ // The parent starts the Per_Call_Limit timer when this arrives, so it goes out just before the call.
1242
+ if (single)
1243
+ await send({ op: "running", position });
1244
+ started = position + 1;
1245
+ lastStarted = position;
1246
+ running = position;
1247
+ let item;
1248
+ try {
1249
+ item = execute(prepared, current);
1250
+ }
1251
+ finally {
1252
+ running = undefined;
1253
+ }
1254
+ const outcome = item.outcome;
1255
+ if (outcome.kind === "returned" || outcome.kind === "threw") {
1256
+ const owner = { position, reported: !rebuilding };
1257
+ if (owner.reported && item.pending.length > 0)
1258
+ outcomeValues.set(position, outcome.value);
1259
+ // At once, before any microtask runs, so no settlement is missed and no rejection is unhandled.
1260
+ watch(outcome.value, item.live, item.pending, item.counterparts, owner);
1261
+ }
1262
+ ran.push(item);
1263
+ }
1264
+ return ran;
1265
+ }
1266
+ async function run(message) {
1267
+ if (session === undefined)
1268
+ throw new BrokenMessage(`${message.op} before the package loaded`);
1269
+ if (message.op === "rebuild")
1270
+ rebuilding = true;
1271
+ else
1272
+ rebuildClosed = true;
1273
+ const ran = await runPositions(message.positions, message.single, session);
1274
+ if (message.op === "rebuild") {
1275
+ await send({ op: "rebuilt", ms: ran.map((item) => item.outcome.ms ?? 0) });
1276
+ return;
1277
+ }
1278
+ const outcomes = ran.map((item) => item.outcome);
1279
+ await send({ op: "ran", outcomes, invocations: takeInvocations(), updates: takeUpdates(new Set(message.positions)), ...newRegExps() });
1280
+ }
1281
+ function resume(message) {
1282
+ rebuilding = false;
1283
+ rebuildClosed = true;
1284
+ rebuildCounts.clear();
1285
+ started = message.next;
1286
+ invocationCounts.clear();
1287
+ for (const [callbackId, count] of Object.entries(message.callbackCounts))
1288
+ invocationCounts.set(callbackId, count);
1289
+ }
1290
+ // The settlements still to come, then the final value of every call that moved on. A promise
1291
+ // that has not settled by then stays pending.
1292
+ async function finish() {
1293
+ if (session === undefined)
1294
+ throw new BrokenMessage("finish before the package loaded");
1295
+ await nextTurn();
1296
+ started = session.soul.calls.length;
1297
+ await settleUpTo(Infinity, now() + session.perCallMs);
1298
+ await send({ op: "finished", invocations: takeInvocations(), updates: takeUpdates(new Set()), ...newRegExps() });
1299
+ }
1300
+ // ---------------------------------------------------------------------------------------------
1301
+ // Start-up
1302
+ function start() {
1303
+ // First, so the token is out of the environment before core or any package code loads.
1304
+ const token = process.env.LICH_REPLY_TOKEN;
1305
+ delete process.env.LICH_REPLY_TOKEN;
1306
+ if (token === undefined || token === "") {
1307
+ die(71, "the Worker was started without a Reply_Token");
1308
+ return;
1309
+ }
1310
+ replyToken = token;
1311
+ // The parent passes core's entry file by absolute path, because the repo's node_modules link
1312
+ // to it is outside the read list.
1313
+ const corePath = process.argv[2];
1314
+ if (corePath === undefined || !nodePath.isAbsolute(corePath)) {
1315
+ die(71, "the Worker was started without the absolute path of @lich/core");
1316
+ return;
1317
+ }
1318
+ try {
1319
+ core = nodeModule.createRequire(__filename)(corePath);
1320
+ }
1321
+ catch (error) {
1322
+ die(71, `the Worker could not load @lich/core: ${describe(error)}`);
1323
+ return;
1324
+ }
1325
+ // Messages run one after another, because a load or a run can wait on the event loop.
1326
+ let queue = Promise.resolve();
1327
+ process.on("message", (raw) => {
1328
+ queue = queue
1329
+ .then(() => (dying ? undefined : handle(raw)))
1330
+ .catch((error) => {
1331
+ const reason = error instanceof BrokenMessage ? `a broken message from the parent: ${error.message}` : `the Worker failed: ${describe(error)}`;
1332
+ die(71, reason);
1333
+ });
1334
+ });
1335
+ // After the listener, which Node keeps calling through its own closure, and before any
1336
+ // message is read, so the package never loads while the channel is in reach.
1337
+ try {
1338
+ closeChannelToPackage();
1339
+ }
1340
+ catch (error) {
1341
+ die(71, describe(error));
1342
+ }
1343
+ }
1344
+ start();
1345
+ //# sourceMappingURL=worker.cjs.map