@threadedstack/wmd-web 0.1.30 → 0.1.32

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.
Files changed (62) hide show
  1. package/README.md +23 -2
  2. package/RELEASE.json +123 -16
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +47 -2
  8. package/src/edge/bridge.js +297 -0
  9. package/src/edge/codes.js +10 -0
  10. package/src/edge/ctl.js +199 -0
  11. package/src/edge/error-kind.js +4 -0
  12. package/src/edge/frame.html +4 -0
  13. package/src/edge/frame.js +48 -0
  14. package/src/edge/fs-route.js +301 -0
  15. package/src/edge/hist.js +46 -0
  16. package/src/edge/msg.js +106 -0
  17. package/src/edge/node-args.js +194 -0
  18. package/src/edge/node-guest-opts.js +108 -0
  19. package/src/edge/node-opts.js +82 -0
  20. package/src/edge/own/adapter.js +271 -0
  21. package/src/edge/own/capi.js +200 -0
  22. package/src/edge/own/child-host.js +196 -0
  23. package/src/edge/own/fs-bridge.js +71 -0
  24. package/src/edge/own/fs-own-route.js +356 -0
  25. package/src/edge/own/guest-spawner.js +235 -0
  26. package/src/edge/own/hub.js +430 -0
  27. package/src/edge/own/loader.js +81 -0
  28. package/src/edge/own/memcap.js +95 -0
  29. package/src/edge/own/payload-size.js +15 -0
  30. package/src/edge/own/pool.js +160 -0
  31. package/src/edge/own/procfs.js +84 -0
  32. package/src/edge/own/serdes-codec.js +317 -0
  33. package/src/edge/own/service-receiver.js +98 -0
  34. package/src/edge/own/shim-post.js +185 -0
  35. package/src/edge/own/stack-fix.js +36 -0
  36. package/src/edge/own/stdio-pipe.js +80 -0
  37. package/src/edge/own/v8-serdes.js +970 -0
  38. package/src/edge/own/wasm-counters.js +144 -0
  39. package/src/edge/own/worker.js +97 -0
  40. package/src/edge/page.js +162 -0
  41. package/src/edge/plan.js +65 -0
  42. package/src/edge/resolve.js +44 -0
  43. package/src/edge/runtime.js +94 -0
  44. package/src/edge/sdk/adapter.js +151 -0
  45. package/src/edge/sdk/forward.js +80 -0
  46. package/src/edge/sdk/napi-stub.js +50 -0
  47. package/src/edge/sdk/relay.js +17 -0
  48. package/src/edge/service-host.js +382 -0
  49. package/src/edge/service-port.js +245 -0
  50. package/src/edge/shim.js +161 -0
  51. package/src/edge/site.js +106 -0
  52. package/src/edge/spawn-guard.js +80 -0
  53. package/src/edge/tz.js +103 -0
  54. package/src/edge/worker.js +121 -0
  55. package/src/edge/workers.js +27 -0
  56. package/src/host/chan-service.js +75 -8
  57. package/src/host/chan-services.js +77 -3
  58. package/src/host/ctl.js +26 -5
  59. package/src/host/edge-go.js +7 -3
  60. package/src/host/edge-host.js +327 -0
  61. package/src/host/yamux.js +21 -8
  62. package/wmdpack.wasm +0 -0
@@ -0,0 +1,161 @@
1
+ // X5 part B (switch edge=1): wmd-edge's shim (edge/src/linux.cjs) as the browser runs it. The file is the desktop's, unchanged
2
+ // in the repo; this builds the text node gets:
3
+ // - the container's settings written in place of the shim's config object (as wmd-edge does);
4
+ // - `__wmdCtl` taken from the Worker's real global too. node's global is not the Worker's (a separate realm in Edge.js,
5
+ // x5-gate2a.md A1 "Globals"), so the function sdk/napi-stub.js defines on the Worker is not on the shim's `globalThis`; the
6
+ // real global is reached with Function('return this')(). The shim removes the function from both before the program runs.
7
+ export const SETTINGS_MARKER = '/*__WMD_EDGE_CONFIG__*/{}'
8
+ const TAKE = 'const hostCtl = globalThis.__wmdCtl;\n delete globalThis.__wmdCtl;'
9
+ const TAKE_HERE =
10
+ "const realGlobal = Function('return this')();\n const hostCtl = globalThis.__wmdCtl || realGlobal.__wmdCtl;\n delete globalThis.__wmdCtl;\n delete realGlobal.__wmdCtl;"
11
+
12
+ // The SDK's host mount shows a link as the file it leads to and has no readlink, so node's own realpath and readlink do not follow a link
13
+ // (`/usr/local/bin/npm` is a link to ../lib/node_modules/npm/bin/npm-cli.js; run as itself, its `../lib` is the wrong directory). These
14
+ // take them from the control requests (src/edge/ctl.js `realpath`, `readlink`), falling back to node's own for a path outside the mounts or
15
+ // for any error, which then throws what node throws. Put before `function ctlError`, inside the shim's closure (it needs `fs`, `ctl`).
16
+ const LINKS_MARKER = ' function ctlError(r, syscall, p) {'
17
+ export const BROWSER_LINKS = ` {
18
+ const pathOf = p => (typeof p === 'string' ? p : Buffer.isBuffer(p) ? p.toString() : null);
19
+ const viaCtl = (op, p, key) => {
20
+ const s = pathOf(p);
21
+ if (s === null) return null;
22
+ try { const r = ctl({ op, path: require('path').resolve(s) }); return r.err ? null : r[key]; } catch (_) { return null; }
23
+ };
24
+ const origRealpathSync = fs.realpathSync;
25
+ const realpathSync = function realpathSync(p, o) {
26
+ const r = viaCtl('realpath', p, 'path');
27
+ if (r === null) return origRealpathSync.apply(fs, arguments);
28
+ return o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r;
29
+ };
30
+ realpathSync.native = realpathSync;
31
+ fs.realpathSync = realpathSync;
32
+ const realpath = function realpath(p, o, cb) {
33
+ if (typeof o === 'function') { cb = o; o = undefined; }
34
+ let r;
35
+ try { r = realpathSync(p, o); } catch (e) { return process.nextTick(cb, e); }
36
+ process.nextTick(cb, null, r);
37
+ };
38
+ realpath.native = realpath;
39
+ fs.realpath = realpath;
40
+ const origReadlinkSync = fs.readlinkSync;
41
+ const readlinkSync = function readlinkSync(p, o) {
42
+ const r = viaCtl('readlink', p, 'target');
43
+ return r === null ? origReadlinkSync.apply(fs, arguments) : (o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r);
44
+ };
45
+ fs.readlinkSync = readlinkSync;
46
+ const origReadlink = fs.readlink;
47
+ fs.readlink = function readlink(p, o, cb) {
48
+ if (typeof o === 'function') { cb = o; o = undefined; }
49
+ if (viaCtl('readlink', p, 'target') === null) return origReadlink.apply(fs, arguments);
50
+ let r;
51
+ try { r = readlinkSync(p, o); } catch (e) { return process.nextTick(cb, e); }
52
+ process.nextTick(cb, null, r);
53
+ };
54
+ // The mount has no symlink call either; a link is made by the control request (npm's node_modules/.bin links).
55
+ const symlinkSync = function symlinkSync(target, path) {
56
+ const s = pathOf(path);
57
+ if (s === null) return origSymlinkSync.apply(fs, arguments);
58
+ const full = require('path').resolve(s);
59
+ const r = ctl({ op: 'symlink', path: full, target: String(pathOf(target) === null ? target : pathOf(target)) });
60
+ if (r.err) throw ctlError(r, 'symlink', s);
61
+ };
62
+ const origSymlinkSync = fs.symlinkSync;
63
+ fs.symlinkSync = symlinkSync;
64
+ fs.symlink = function symlink(target, path, type, cb) {
65
+ if (typeof type === 'function') cb = type;
66
+ try { symlinkSync(target, path); } catch (e) { return process.nextTick(cb, e); }
67
+ process.nextTick(cb, null);
68
+ };
69
+ if (fs.promises) {
70
+ fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };
71
+ fs.promises.realpath = async function realpath(p, o) { return realpathSync(p, o); };
72
+ const origP = fs.promises.readlink;
73
+ fs.promises.readlink = async function readlink(p, o) { return viaCtl('readlink', p, 'target') === null ? origP.apply(fs.promises, arguments) : readlinkSync(p, o); };
74
+ }
75
+ // The page's run has pipes for stdio (the stub sent a terminal's run to the guest's own node), but the SDK's pipes look like a
76
+ // character device to node, so process.stdout.isTTY is true and npm would draw progress. The guest's node says undefined.
77
+ for (const name of ['stdin', 'stdout', 'stderr']) {
78
+ const d = Object.getOwnPropertyDescriptor(process, name);
79
+ if (!d || !d.get) continue;
80
+ Object.defineProperty(process, name, {
81
+ configurable: true,
82
+ enumerable: d.enumerable,
83
+ get() {
84
+ const st = d.get.call(process);
85
+ if (st && st.isTTY) { try { delete st.isTTY; } catch (_) {} if (st.isTTY) { try { Object.defineProperty(st, 'isTTY', { value: undefined, configurable: true }); } catch (_) {} } }
86
+ return st;
87
+ },
88
+ });
89
+ }
90
+ }
91
+ `
92
+
93
+ // The version the program reports (check5 F5). The frame's node is Edge.js's build (v24.21.0 in the pinned program); the container's node is the image's
94
+ // (v24.22.3), and `npm ci` of a project with "engines": {"node": ">=24.22.0"} stops in the frame. The desktop's node reports the image's version from the
95
+ // program itself (Edge.js patch 24, WMD_NODE_VERSION); the program the browser loads has no such patch, so the shim gives the same two values, read-only and
96
+ // configurable as node's are. Only a release version of the same major is taken (the plan sends another major to the guest: src/edge/plan.js).
97
+ export const NODE_VERSION = /^v\d+\.\d+\.\d+$/
98
+ export function nodeVersionJs(v) {
99
+ if (typeof v !== 'string' || !NODE_VERSION.test(v)) return ''
100
+ return `\n;(() => {
101
+ const version = ${JSON.stringify(v)};
102
+ const hide = (o, k, value) => Object.defineProperty(o, k, { value, writable: false, enumerable: true, configurable: true });
103
+ hide(process, 'version', version);
104
+ if (process.versions) hide(process.versions, 'node', version.slice(1));
105
+ })();\n`
106
+ }
107
+
108
+ // The own runtime's file route makes links itself (the route's `symlink`), and the program's directory then knows them: a link made by the control request
109
+ // is unknown to WASIX's tables, and a rename of it gave ENOENT (fix5 F1, the real guest: `ring` in runs/f5-kids-chromium.json). The own runtime's shim takes the
110
+ // symlink block out and keeps the reading ones (realpath, readlink).
111
+ const SYMLINK_FROM = ' // The mount has no symlink call either; a link is made by the control request'
112
+ const SYMLINK_TO = ' // The page\'s run has pipes for stdio'
113
+ const PROMISE_SYMLINK = " fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };\n"
114
+ export function withoutSymlinkOverride(links) {
115
+ const a = links.indexOf(SYMLINK_FROM)
116
+ const b = links.indexOf(SYMLINK_TO)
117
+ if (a < 0 || b < a || links.split(PROMISE_SYMLINK).length !== 2) throw new Error('shim.js: the symlink block of BROWSER_LINKS moved; withoutSymlinkOverride needs a change')
118
+ const middle = links.slice(a, b)
119
+ // inside the block only the `if (fs.promises)` part stays, without its symlink line
120
+ const at = middle.indexOf(' if (fs.promises) {')
121
+ return links.slice(0, a) + middle.slice(at).replace(PROMISE_SYMLINK, '') + links.slice(b)
122
+ }
123
+
124
+ // Signals (fix7 F2, F14). The shim polls the page's queue for signals of the guest and knows four of them (HUP, INT, QUIT, TERM); a handler for USR1,
125
+ // USR2 or WINCH never ran and USR2 ended the program after the page's grace period. In the browser the table is Linux's whole list, a handler gets
126
+ // (name, number) as node's does, and a signal without a handler does what Linux does for it: nothing for CHLD, CONT, URG, WINCH, PIPE (node ignores it),
127
+ // the stops, and USR1 (node starts its inspector, which the frame does not have); the program ends with 128+n for the others.
128
+ const SIG_TABLE_FROM = " const SIG_NAMES = { 1: 'SIGHUP', 2: 'SIGINT', 3: 'SIGQUIT', 15: 'SIGTERM' };"
129
+ export const SIG_NAMES_LINUX = {
130
+ 1: 'SIGHUP', 2: 'SIGINT', 3: 'SIGQUIT', 4: 'SIGILL', 5: 'SIGTRAP', 6: 'SIGABRT', 7: 'SIGBUS', 8: 'SIGFPE', 10: 'SIGUSR1', 11: 'SIGSEGV', 12: 'SIGUSR2',
131
+ 13: 'SIGPIPE', 14: 'SIGALRM', 15: 'SIGTERM', 16: 'SIGSTKFLT', 17: 'SIGCHLD', 18: 'SIGCONT', 19: 'SIGSTOP', 20: 'SIGTSTP', 21: 'SIGTTIN', 22: 'SIGTTOU', 23: 'SIGURG',
132
+ 24: 'SIGXCPU', 25: 'SIGXFSZ', 26: 'SIGVTALRM', 27: 'SIGPROF', 28: 'SIGWINCH', 29: 'SIGIO', 30: 'SIGPWR', 31: 'SIGSYS',
133
+ }
134
+ /** The signals whose default action leaves the program running. */
135
+ export const SIG_IGNORED_LINUX = [10, 13, 17, 18, 19, 20, 21, 22, 23, 28]
136
+ const SIG_TABLE_TO = ` const SIG_NAMES = ${JSON.stringify(SIG_NAMES_LINUX)};\n const SIG_IGNORED = new Set(${JSON.stringify(SIG_IGNORED_LINUX)});`
137
+ const SIG_EMIT_FROM = ` if (process.listenerCount(name) > 0) {
138
+ process.emit(name, name);
139
+ } else {`
140
+ const SIG_EMIT_TO = ` if (process.listenerCount(name) > 0) {
141
+ // tell the page that a handler takes it: the program is not stuck and is not cut off after the grace period (fix7)
142
+ try { ctl({ op: 'signal_taken', n: sig, handled: true }); } catch (_) {}
143
+ process.emit(name, name, sig);
144
+ } else if (SIG_IGNORED.has(sig)) {
145
+ // the default action of this signal leaves the program running
146
+ } else {`
147
+
148
+ export function shimSource(src, settings, { symlinks = true } = {}) {
149
+ for (const [name, text] of [['settings marker', SETTINGS_MARKER], ['__wmdCtl take', TAKE], ['ctlError', LINKS_MARKER], ['signal table', SIG_TABLE_FROM], ['signal emit', SIG_EMIT_FROM]]) {
150
+ const n = src.split(text).length - 1
151
+ if (n !== 1) throw new Error(`linux.cjs: the ${name} is there ${n} times, not once; the browser shim needs a change`)
152
+ }
153
+ return (
154
+ src
155
+ .replace(SETTINGS_MARKER, () => JSON.stringify(settings))
156
+ .replace(TAKE, () => TAKE_HERE)
157
+ .replace(SIG_TABLE_FROM, () => SIG_TABLE_TO)
158
+ .replace(SIG_EMIT_FROM, () => SIG_EMIT_TO)
159
+ .replace(LINKS_MARKER, () => (symlinks ? BROWSER_LINKS : withoutSymlinkOverride(BROWSER_LINKS)) + LINKS_MARKER) + nodeVersionJs(settings && settings.nodeVersion)
160
+ )
161
+ }
@@ -0,0 +1,106 @@
1
+ // X5 part B (edge=1 only): what the page remembers about the frame's site (check4 F3). A start that timed out because the frame never loaded
2
+ // (its server is down, the name does not resolve) used to cost its 30 s again at every later node run. The site is now marked down at the first
3
+ // such start; later runs go to the guest's node at once, with the reason, and the page tries the site again in the background every
4
+ // retryMs (5 minutes) with a probe that no run waits for. One site per page: the bridges of the page's machines share it (page/ckpt.js).
5
+ //
6
+ // const site = frameSite({origin, probe, onEvent, retryMs, now, setTimer, clearTimer})
7
+ // site.isDown() -> null | {since, why} site.markDown(why) site.markUp() site.stats() site.stop()
8
+ // probe(origin) -> Promise<boolean>: true when the frame's page loads and says it is ready (iframeProbe is the real one)
9
+ // onEvent({type: 'site', down: true, why} | {type: 'site', down: false, afterMs, probes} | {type: 'site', down: true, retry: n, why})
10
+
11
+ export const SITE_RETRY_MS = 300_000
12
+
13
+ export function frameSite({ origin, probe, onEvent = () => {}, retryMs = SITE_RETRY_MS, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout }) {
14
+ let down = null
15
+ let timer = null
16
+ let probes = 0
17
+ let inFlight = false
18
+ const emit = e => {
19
+ try {
20
+ onEvent({ type: 'site', ...e })
21
+ } catch {
22
+ // the listener's own business
23
+ }
24
+ }
25
+ const schedule = () => {
26
+ if (timer !== null || !down) return
27
+ timer = setTimer(() => {
28
+ timer = null
29
+ void again()
30
+ }, retryMs)
31
+ }
32
+ async function again() {
33
+ if (!down || inFlight) return
34
+ inFlight = true
35
+ probes++
36
+ let ok = false
37
+ try {
38
+ ok = !!(await probe(origin))
39
+ } catch {
40
+ ok = false
41
+ }
42
+ inFlight = false
43
+ if (!down) return
44
+ if (ok) return site.markUp()
45
+ emit({ down: true, retry: probes, why: down.why, kind: down.kind })
46
+ schedule()
47
+ }
48
+ const site = {
49
+ retryMs,
50
+ isDown() {
51
+ // a runtime that failed to load (fix7 F12) is remembered for retryMs; the frame's probe cannot tell it from a working one
52
+ if (down && down.kind === 'runtime' && now() - down.since >= retryMs) site.markUp()
53
+ return down
54
+ },
55
+ /** opts.kind 'runtime': the frame loads but the runtime's files do not (no probe; forgotten after retryMs). opts.probeNow: probe the frame at once (a slow frame is found again). */
56
+ markDown(why, { kind = 'frame', probeNow = false } = {}) {
57
+ if (down) return
58
+ down = { since: now(), why: String(why), kind }
59
+ emit({ down: true, why: down.why, kind })
60
+ if (kind === 'runtime') return
61
+ if (probeNow) void again()
62
+ else schedule()
63
+ },
64
+ markUp() {
65
+ if (!down) return
66
+ const was = down
67
+ down = null
68
+ if (timer !== null) (clearTimer(timer), (timer = null))
69
+ emit({ down: false, afterMs: now() - was.since, probes })
70
+ },
71
+ stats: () => ({ down: !!down, since: down ? down.since : 0, why: down ? down.why : '', kind: down ? down.kind : '', probes }),
72
+ stop() {
73
+ down = null
74
+ if (timer !== null) (clearTimer(timer), (timer = null))
75
+ },
76
+ }
77
+ return site
78
+ }
79
+
80
+ /** The real probe: the frame's page in a hidden iframe, which must post x5-frame-ready within timeoutMs; the iframe is removed after. */
81
+ export function iframeProbe({ doc = globalThis.document, win = globalThis, timeoutMs = 20_000 } = {}) {
82
+ return origin =>
83
+ new Promise(resolve => {
84
+ const f = doc.createElement('iframe')
85
+ f.style.display = 'none'
86
+ f.allow = 'cross-origin-isolated'
87
+ f.src = origin + '/edge/frame.html'
88
+ let t = null
89
+ const end = ok => {
90
+ win.removeEventListener('message', onMessage)
91
+ if (t !== null) win.clearTimeout(t)
92
+ try {
93
+ f.remove()
94
+ } catch {
95
+ // already gone
96
+ }
97
+ resolve(ok)
98
+ }
99
+ const onMessage = ({ data, origin: o, source }) => {
100
+ if (o === origin && source === f.contentWindow && data === 'x5-frame-ready') end(true)
101
+ }
102
+ win.addEventListener('message', onMessage)
103
+ t = win.setTimeout(() => end(false), timeoutMs)
104
+ doc.body.append(f)
105
+ })
106
+ }
@@ -0,0 +1,80 @@
1
+ // X5 part B (switch edge=1): a program that starts a process inside the frame. The frame's runtime cannot serve a spawn (it has no `sh`, no
2
+ // second node, no container to run them in; on the desktop wmd-edge relays them to the guest through the stub: docs/DECISIONS.md D-323 and
3
+ // D-330). Left alone, a spawn comes back ENOEXEC and the program may carry on, so the run can end as a success with other output than the
4
+ // guest's. The guard makes it end instead, at the first spawn, with a clear line and exit code 126 ("cannot execute"); the line also starts with
5
+ // SPAWN_MARK, which worker.js reads, so that the next run of the same program is planned into the guest (src/edge/service-host.js).
6
+ // It is put after wmd-edge's shim (withSpawnGuard), which has patched child_process for the desktop; every spawn call of child_process ends here.
7
+
8
+ export const SPAWN_MARK = 'wmd: spawn refused: '
9
+
10
+ /**
11
+ * The mark of one run: the fixed words and a random part made by the frame's worker (not by the container), so that a program that prints the words
12
+ * by accident, or on purpose without knowing the random part, is not taken for a refused spawn (check4 F10). A program that reads the random
13
+ * part (it is in the guard's text inside the frame's runtime) can only make its own run end as a refused spawn: the next run of that same program
14
+ * then goes to the guest. It harms no other program and no other run.
15
+ */
16
+ export function newSpawnMark() {
17
+ const b = crypto.getRandomValues(new Uint8Array(6))
18
+ return `${SPAWN_MARK.slice(0, -2)} [${Array.from(b, x => x.toString(16).padStart(2, '0')).join('')}]: `
19
+ }
20
+
21
+ /**
22
+ * Finds the mark in a stream of stderr text that arrives in chunks: a mark cut between two chunks is found, and so is a command that goes on in the
23
+ * next chunk. push(text) returns the command (the rest of the mark's line) once its line is complete, else undefined; finish() returns what is
24
+ * there when the stream ends without a newline, else undefined.
25
+ */
26
+ export function markScanner(mark) {
27
+ let carry = ''
28
+ let line = null
29
+ let done = false
30
+ return {
31
+ push(text) {
32
+ if (done) return undefined
33
+ if (line === null) {
34
+ const all = carry + text
35
+ const at = all.indexOf(mark)
36
+ if (at < 0) {
37
+ carry = all.slice(Math.max(0, all.length - (mark.length - 1)))
38
+ return undefined
39
+ }
40
+ line = all.slice(at + mark.length)
41
+ carry = ''
42
+ } else line += text
43
+ const nl = line.indexOf('\n')
44
+ if (nl < 0) return undefined
45
+ done = true
46
+ return line.slice(0, nl)
47
+ },
48
+ finish: () => (!done && line !== null ? ((done = true), line) : undefined),
49
+ }
50
+ }
51
+ export const SPAWN_EXIT = 126
52
+
53
+ /** The function the frame runs after the shim (also run by the tests with fakes). req is `require`, proc is `process`. */
54
+ export function spawnGuard(req, proc, mark, code) {
55
+ const cp = req('child_process')
56
+ const fs = req('fs')
57
+ let refused = false
58
+ const refuse = (name, cmd) => {
59
+ // process.exit does not stop the program at once under this runtime: a second call before it ends is refused too, and says nothing again
60
+ if (refused) throw new Error('spawn refused')
61
+ refused = true
62
+ const c = String(cmd == null ? '' : cmd).replace(/\s+/g, ' ').slice(0, 200)
63
+ const text = `${mark}${c}\nwmd: this program started a process (${name}), which node cannot do in the browser frame. It ends here. The next run of this program goes to the guest.\n`
64
+ try {
65
+ fs.writeSync(2, text)
66
+ } catch {
67
+ // stderr is gone
68
+ }
69
+ proc.exit(code)
70
+ throw new Error('spawn refused: ' + c)
71
+ }
72
+ for (const name of ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork']) {
73
+ if (typeof cp[name] === 'function') cp[name] = function (cmd) { return refuse(name, cmd) }
74
+ }
75
+ }
76
+
77
+ /** wmd-edge's shim with the guard run after it; `mark` is the run's own mark (newSpawnMark). */
78
+ export function withSpawnGuard(src, mark = SPAWN_MARK) {
79
+ return src + `\n;(${spawnGuard})(require, process, ${JSON.stringify(mark)}, ${SPAWN_EXIT});\n`
80
+ }
package/src/edge/tz.js ADDED
@@ -0,0 +1,103 @@
1
+ // X5 part B (switch edge=1): the container's clock zone. The frame's JavaScript runs on the browser's engine, so `Date` uses the browser's
2
+ // time zone (America/Phoenix on one machine) and the TZ variable has no effect. The guest's node says UTC unless the container sets TZ.
3
+ // utcClock(global) makes the local-time parts of Date and Intl.DateTimeFormat UTC. It is put in front of wmd-edge's shim (withUtcClock) for a
4
+ // container whose TZ is unset or UTC; any other TZ is refused by the hello check (src/host/edge-host.js helloRefusal), the zone being a
5
+ // table the engine has and the container's TZ names one this code does not carry.
6
+
7
+ export const UTC_NAME_LIST = ['', 'UTC', 'UTC0', 'Etc/UTC', 'GMT', 'GMT0', 'Etc/GMT', 'Etc/GMT0', 'Etc/Universal', 'Etc/Zulu', 'Universal', 'Zulu', 'Z', ':UTC']
8
+ const UTC_NAMES = new Set(UTC_NAME_LIST)
9
+
10
+ /** True when a container with this TZ value has UTC as its zone. */
11
+ export const isUtcZone = tz => UTC_NAMES.has(String(tz ?? '').trim())
12
+
13
+ /** The function the frame runs (also run here by the tests). It patches the Date and Intl of `g` and returns nothing. */
14
+ export function utcClock(g) {
15
+ const RealDate = g.Date
16
+ const proto = RealDate.prototype
17
+ const realOffset = proto.getTimezoneOffset
18
+ const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
19
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
20
+ const p2 = n => String(n).padStart(2, '0')
21
+ const pairs = [['FullYear'], ['Month'], ['Date'], ['Day'], ['Hours'], ['Minutes'], ['Seconds'], ['Milliseconds']]
22
+ const def = (name, fn) => Object.defineProperty(proto, name, { value: fn, writable: true, configurable: true, enumerable: false })
23
+ for (const [n] of pairs) {
24
+ def('get' + n, function () { return this['getUTC' + n]() })
25
+ if (n !== 'Day') def('set' + n, function (...a) { return this['setUTC' + n](...a) })
26
+ }
27
+ def('getYear', function () { return this.getUTCFullYear() - 1900 })
28
+ def('setYear', function (y) { return this.setUTCFullYear(y >= 0 && y <= 99 ? 1900 + y : y) })
29
+ def('getTimezoneOffset', function () { return Number.isNaN(this.getTime()) ? NaN : 0 })
30
+ const year = y => (y >= 0 ? String(y).padStart(4, '0') : '-' + String(-y).padStart(4, '0')) // node: -0001 for the year before 0
31
+ const dateText = d => `${DAYS[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${p2(d.getUTCDate())} ${year(d.getUTCFullYear())}`
32
+ const timeText = d => `${p2(d.getUTCHours())}:${p2(d.getUTCMinutes())}:${p2(d.getUTCSeconds())} GMT+0000 (Coordinated Universal Time)`
33
+ const valid = (d, f) => (Number.isNaN(d.getTime()) ? 'Invalid Date' : f(d))
34
+ def('toString', function () { return valid(this, d => dateText(d) + ' ' + timeText(d)) })
35
+ def('toDateString', function () { return valid(this, dateText) })
36
+ def('toTimeString', function () { return valid(this, timeText) })
37
+ for (const name of ['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString']) {
38
+ const orig = proto[name]
39
+ def(name, function (loc, opt) { return orig.call(this, loc, { timeZone: 'UTC', ...opt }) })
40
+ }
41
+ // The engine reads a date string in its own zone unless the string says a zone (an offset, Z, GMT, UTC, EST...) or is one of the ISO date-only
42
+ // forms (YYYY, YYYY-MM, YYYY-MM-DD: UTC in every engine). The container's zone is UTC, so a string with no zone is read again with the
43
+ // zone said in words: 'Z' after an ISO date-time, ' GMT' after anything else. The engine then does its own parsing (and its own rules for
44
+ // a local time in a gap or overlap of ITS zone never apply), instead of this code shifting the answer by the zone's offset afterwards.
45
+ // `-000000` is no ISO year (Firefox reads it as the legacy text it is, in its own zone), so it is not in this list.
46
+ const isoDate = /^(?:\+\d{6}|-(?!000000)\d{6}|\d{4})(?:-\d\d(?:-\d\d)?)?$/
47
+ const isoLocalTime = /^(?:[+-]\d{6}|\d{4})-\d\d-\d\dT\d\d:\d\d(?::\d\d(?:\.\d+)?)?$/i
48
+ const hasZone = /(\dZ|\b(?:GMT|UTC|UT|[ECMP][SD]T|Z)\b|(?:\b(?:GMT|UTC|UT)|\d:\d\d(?::\d\d(?:\.\d+)?)?\s*|\s)[+-]\d{1,2}(?::?\d{2})?)\s*(\([^)]*\))?\s*$/i
49
+ const zonedInside = /\b(?:GMT|UTC|UT)\b|\b[ECMP][SD]T\b|\dZ\b|\s[+-]\d{2}:?\d{2}\b/i
50
+ // the engine's offset a day before t: a text in a gap of its zone gives the same number with and without the tail when the zone is UTC on one side of the gap
51
+ // (Dublin), and also when the engine ignores the tail (WebKit in Los Angeles); the first is right, the second is not
52
+ const dayBefore = t => realOffset.call(new RealDate(t - 86400000))
53
+ const parse = v => {
54
+ const s = String(v)
55
+ const t = RealDate.parse(s)
56
+ if (isoDate.test(s) || hasZone.test(s)) return t
57
+ // An engine may take the tail and still read the text in its zone (WebKit: '2024-3-10 2:30Z' is the same number as '2024-3-10 2:30'), so a number equal to the
58
+ // zoneless one counts only where the engine's zone is UTC at that time (then both are the same time) or the text names a zone inside ('Mar 10 2024 GMT 02:30').
59
+ const off = Number.isNaN(t) || zonedInside.test(s) ? 0 : realOffset.call(new RealDate(t))
60
+ const iso = isoLocalTime.test(s) // an ISO date-time is read right by every engine (and in a gap of the engine's zone the two numbers can be equal)
61
+ for (const tail of iso ? ['Z'] : [' GMT', 'Z']) {
62
+ const u = RealDate.parse(s + tail)
63
+ if (!Number.isNaN(u) && (iso || u !== t || off === 0 || dayBefore(t) === 0)) return u
64
+ }
65
+ if (Number.isNaN(t)) return NaN
66
+ // WebKit reads a bare number ('99', '12345', '-1', '24-03-10') as UTC midnight whatever its zone is; a zoneless text read in the zone is midnight there, which is
67
+ // not a multiple of a day in a zone with an offset. No time in the text and UTC midnight: the engine did not use its zone.
68
+ if (!zonedInside.test(s) && !s.includes(':') && t % 86400000 === 0 && realOffset.call(new RealDate(t)) !== 0) return t
69
+ // a form the engine takes only without a zone: its zone's offset at that time. In a gap of its zone the engine moved the text forward (2:30 became 3:30 in Los Angeles on
70
+ // the day the clocks go forward) and the offset before the gap is the right one; the text tells: when its hour and minute are not the engine's wall time, the text was moved.
71
+ const offT = realOffset.call(new RealDate(t))
72
+ let c = t - offT * 60000
73
+ const offB = dayBefore(t)
74
+ if (offB !== offT) {
75
+ const d = new RealDate(c)
76
+ if (!new RegExp('(^|\\D)0?' + d.getUTCHours() + ':' + p2(d.getUTCMinutes()) + '(\\D|$)').test(s)) c = t - offB * 60000
77
+ }
78
+ return new RealDate(c).getTime()
79
+ }
80
+ const D = new Proxy(RealDate, {
81
+ construct(t, a, nt) {
82
+ if (a.length >= 2) return Reflect.construct(t, [RealDate.UTC(...a)], nt)
83
+ if (a.length === 1 && typeof a[0] === 'string') return Reflect.construct(t, [parse(a[0])], nt)
84
+ return Reflect.construct(t, a, nt)
85
+ },
86
+ apply: () => new D().toString(),
87
+ get: (t, k, r) => (k === 'parse' ? parse : Reflect.get(t, k, t)),
88
+ })
89
+ Object.defineProperty(proto, 'constructor', { value: D, writable: true, configurable: true, enumerable: false })
90
+ g.Date = D
91
+ const DTF = g.Intl.DateTimeFormat
92
+ g.Intl.DateTimeFormat = new Proxy(DTF, {
93
+ construct: (t, [loc, opt], nt) => Reflect.construct(t, [loc, { timeZone: 'UTC', ...opt }], nt),
94
+ apply: (t, th, [loc, opt]) => t(loc, { timeZone: 'UTC', ...opt }),
95
+ })
96
+ }
97
+
98
+ /** wmd-edge's shim with the UTC clock run first (after its 'use strict'). */
99
+ export function withUtcClock(src) {
100
+ const head = "'use strict';"
101
+ if (src.split(head).length !== 2 || !src.startsWith(head)) throw new Error("linux.cjs: 'use strict' is not the first statement, once; the browser's clock needs a change")
102
+ return head + `\n(${utcClock})(globalThis);` + src.slice(head.length)
103
+ }
@@ -0,0 +1,121 @@
1
+ // X5 part B (switch edge=1): node in the isolated frame's Worker, on whatever runtime the page chose (src/edge/runtime.js, cfg.rt).
2
+ //
3
+ // Takes {cfg, ports: [portA, portB]} from frame.js. The ports lead to the channel service (the file route). What a port is used for is the
4
+ // adapter's business (the SDK adapter wants two: src/edge/sdk/adapter.js). This file knows no runtime: it loads the adapter, starts the
5
+ // program, moves stdio and signals, and reports.
6
+ //
7
+ // cfg: {rt, edgeWasm: '/wasm/edgejs.wasm', mounts: [[path, id, readOnly]], files: {path: text},
8
+ // env: {}, args: [], cwd, timeoutMs, parallelism, spawn, stdin, stream, linux}
9
+ // Messages out: {type: 'log', text}, {type: 'step', name: 'ready'}, {type: 'out', kind, bytes}, {type: 'done', ...}
10
+ import { RT_DEFAULT, loadAdapter } from './runtime.js'
11
+ import { errorKindOf } from './error-kind.js'
12
+ import { installWasmCounters } from './own/wasm-counters.js'
13
+ import { SPAWN_EXIT, markScanner, newSpawnMark } from './spawn-guard.js'
14
+
15
+ installWasmCounters(globalThis) // fix7 item 15
16
+ const log = text => postMessage({ type: 'log', text })
17
+ const dec = new TextDecoder()
18
+ const enc = new TextEncoder()
19
+ let adapter = null
20
+ let finished = false
21
+ // X5 fix9 (docs/research/browser-speed-2026-11/x5/gate2b/fix9/fix9.md, the keeper): this Worker ends nothing itself. A Worker that terminates the
22
+ // runtime's Workers and closes itself in the same task leaves their threads and memory alive in Chromium (about 290 MiB and 7 threads a start).
23
+ // `done` is its last act: the frame terminates it from outside when it gets done (src/edge/frame.js), and the browser ends the Workers under it with it.
24
+ const done = d => {
25
+ if (finished) return
26
+ finished = true
27
+ postMessage({ type: 'done', ...d })
28
+ }
29
+
30
+ // the page's input to a running program (page.js control): stdin bytes, end of input, a signal; held until the process exists
31
+ let proc = null
32
+ const early = []
33
+ async function input(m) {
34
+ if (!proc) return early.push(m)
35
+ if (m.stdin) await proc.writeStdin(m.stdin)
36
+ else if (m.stdinEnd) await proc.closeStdin()
37
+ else if (m.signal) await adapter.signal(proc, m.signal) // the page sends only the signals that end a program (src/edge/bridge.js)
38
+ }
39
+
40
+ onmessage = async ({ data: { cfg, ports, in: inp } }) => {
41
+ if (inp) return input(inp)
42
+ const res = {}
43
+ let loading = true // fix7 F12: an error while the runtime's files load is told to the page as such (it remembers it)
44
+ try {
45
+ const t0 = performance.now()
46
+ adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg)
47
+ const loaded = await adapter.load({
48
+ cfg,
49
+ ports,
50
+ log,
51
+ onWorkerError: why => done({ error: 'the runtime lost a Worker: ' + why }),
52
+ })
53
+ loading = false
54
+ if (loaded.fallback) return done({ fallback: true, ...loaded.fallback })
55
+ const spawnMark = newSpawnMark() // this run's own mark: what the guard prints when a program starts a process (src/edge/spawn-guard.js)
56
+ proc = await adapter.start({
57
+ spawnMark,
58
+ module: cfg.edgeWasm,
59
+ argv: cfg.args,
60
+ env: cfg.env,
61
+ cwd: cfg.cwd,
62
+ mounts: cfg.mounts,
63
+ files: cfg.files,
64
+ linux: cfg.linux,
65
+ linuxSrc: cfg.linuxSrc,
66
+ stdin: cfg.stdin || 'closed',
67
+ timeoutMs: cfg.timeoutMs,
68
+ parallelism: cfg.parallelism,
69
+ })
70
+ res.setupMs = performance.now() - t0
71
+ log('process started after ' + res.setupMs.toFixed(0) + ' ms')
72
+ const t1 = performance.now()
73
+ postMessage({ type: 'step', name: 'ready', ms: res.setupMs }) // the process runs: the page may tell the guest it has started
74
+ for (const m of early.splice(0)) await input(m)
75
+ const outs = []
76
+ const errs = []
77
+ let spawnRefused // the command the program tried to start, once the guard has ended it (src/edge/spawn-guard.js)
78
+ const scanner = markScanner(spawnMark) // finds the mark across chunks of stderr
79
+ const sdec = new TextDecoder()
80
+ // fix7 (F1): the bytes each stream gave here and posted; the page compares them with what it took (bridge.js outBytes)
81
+ const sent = (res.outBytes = { stdout: 0, stderr: 0 })
82
+ const pump = async (read, into, kind) => {
83
+ for (let n = 0; n < 1_000_000; n++) {
84
+ const b = await read(65536)
85
+ if (b == null) return
86
+ if (!b.length) continue // an empty chunk is not the end (fix7 F1)
87
+ sent[kind] += b.length
88
+ if (kind === 'stderr' && spawnRefused === undefined) spawnRefused = scanner.push(sdec.decode(b, { stream: true }))
89
+ if (cfg.stream) {
90
+ const c = b.slice()
91
+ postMessage({ type: 'out', kind, bytes: c }, [c.buffer])
92
+ } // streamed to the page as it comes
93
+ else into.push(b)
94
+ }
95
+ }
96
+ if (cfg.stdinBytes) await proc.writeStdin(enc.encode(cfg.stdinBytes))
97
+ if (cfg.stdinBytes && cfg.stdin === 'pipe') await proc.closeStdin()
98
+ await Promise.all([pump(proc.readStdout, outs, 'stdout'), pump(proc.readStderr, errs, 'stderr')])
99
+ const w = await adapter.exit(proc)
100
+ const join = chunks => {
101
+ const all = new Uint8Array(chunks.reduce((a, c) => a + c.length, 0))
102
+ let at = 0
103
+ for (const c of chunks) (all.set(c, at), (at += c.length))
104
+ return all
105
+ }
106
+ if (spawnRefused === undefined) spawnRefused = scanner.finish()
107
+ res.runMs = performance.now() - t1
108
+ res.exitCode = w.exitCode
109
+ if (spawnRefused !== undefined && w.exitCode === SPAWN_EXIT) res.spawnRefused = spawnRefused
110
+ res.reason = w.reason
111
+ res.stdout = dec.decode(join(outs)).slice(-8000)
112
+ res.stderr = dec.decode(join(errs)).slice(-8000)
113
+ Object.assign(res, await adapter.stats())
114
+ // no adapter.teardown(): the runtime's Workers end when the frame terminates this one (fix9, see done)
115
+ } catch (e) {
116
+ res.error = String((e && e.stack) || e)
117
+ const kind = errorKindOf(e, loading) // fix 11 (F-M): the runtime's wasm that is missing is found in start(), after load()
118
+ if (kind) res.errorKind = kind
119
+ }
120
+ done(res)
121
+ }
@@ -0,0 +1,27 @@
1
+ // X5 part B (switch edge=1): the Workers an adapter makes inside the frame's worker (the runtime's own thread Workers and the adapter's relay).
2
+ // Every one is remembered, and release() terminates the ones still alive, so that they end before the frame's worker does and not by the
3
+ // frame's worker going away under them (round 3, item 1). size() is what the tests read: zero after release.
4
+ export function workerRegistry() {
5
+ const made = new Set()
6
+ return {
7
+ /** remember a Worker; returns it */
8
+ track(w) {
9
+ made.add(w)
10
+ return w
11
+ },
12
+ /** terminate every remembered Worker and forget it; returns how many were still remembered */
13
+ release() {
14
+ const n = made.size
15
+ for (const w of [...made]) {
16
+ made.delete(w)
17
+ try {
18
+ w.terminate()
19
+ } catch {
20
+ // already gone
21
+ }
22
+ }
23
+ return n
24
+ },
25
+ size: () => made.size,
26
+ }
27
+ }