@threadedstack/wmd-web 0.1.39 → 0.1.41

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 (57) hide show
  1. package/README.md +236 -1
  2. package/RELEASE.json +84 -49
  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 +231 -4
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +208 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +125 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +13 -2
  38. package/src/edge/sbx/cap.js +36 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +275 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/setup.js +9 -6
  54. package/src/host/chan-service.js +8 -5
  55. package/src/host/chan-services.js +29 -4
  56. package/src/host/edge-host.js +58 -3
  57. package/wmdpack.wasm +0 -0
@@ -0,0 +1,142 @@
1
+ // The names of node's global object: Object.getOwnPropertyNames(globalThis) of node 24.22.3 in the guest (the image's node, the only major the frame runs:
2
+ // plan.js NODE_MAJOR), read in the page's own guest with `node -e` (the names `-e` adds for the builtin modules, __dirname, __filename, exports, module and require are taken out: a script file has none) (X5 fix3 R6, docs/research/browser-speed-2026-11/x5/default1/fix3/runs/t2-chromium-E-G.json,
3
+ // the TABLE row `globals`, arm G). The runtime's glue (edge/browser/patched/wasmer-napi, __wmdNodeGlobals) shows a name of the worker's own global
4
+ // (USB, VideoDecoder, importScripts, indexedDB, caches, ...) to the program only when it is in this list; node's own names and the names the core
5
+ // defines itself are not affected.
6
+ export const NODE_GLOBALS = Object.freeze([
7
+ 'AbortController',
8
+ 'AbortSignal',
9
+ 'AggregateError',
10
+ 'Array',
11
+ 'ArrayBuffer',
12
+ 'AsyncDisposableStack',
13
+ 'Atomics',
14
+ 'BigInt',
15
+ 'BigInt64Array',
16
+ 'BigUint64Array',
17
+ 'Blob',
18
+ 'Boolean',
19
+ 'BroadcastChannel',
20
+ 'Buffer',
21
+ 'ByteLengthQueuingStrategy',
22
+ 'CloseEvent',
23
+ 'CompressionStream',
24
+ 'CountQueuingStrategy',
25
+ 'Crypto',
26
+ 'CryptoKey',
27
+ 'CustomEvent',
28
+ 'DOMException',
29
+ 'DataView',
30
+ 'Date',
31
+ 'DecompressionStream',
32
+ 'DisposableStack',
33
+ 'Error',
34
+ 'EvalError',
35
+ 'Event',
36
+ 'EventTarget',
37
+ 'File',
38
+ 'FinalizationRegistry',
39
+ 'Float16Array',
40
+ 'Float32Array',
41
+ 'Float64Array',
42
+ 'FormData',
43
+ 'Function',
44
+ 'Headers',
45
+ 'Infinity',
46
+ 'Int16Array',
47
+ 'Int32Array',
48
+ 'Int8Array',
49
+ 'Intl',
50
+ 'Iterator',
51
+ 'JSON',
52
+ 'Map',
53
+ 'Math',
54
+ 'MessageChannel',
55
+ 'MessageEvent',
56
+ 'MessagePort',
57
+ 'NaN',
58
+ 'Navigator',
59
+ 'Number',
60
+ 'Object',
61
+ 'Performance',
62
+ 'PerformanceEntry',
63
+ 'PerformanceMark',
64
+ 'PerformanceMeasure',
65
+ 'PerformanceObserver',
66
+ 'PerformanceObserverEntryList',
67
+ 'PerformanceResourceTiming',
68
+ 'Promise',
69
+ 'Proxy',
70
+ 'RangeError',
71
+ 'ReadableByteStreamController',
72
+ 'ReadableStream',
73
+ 'ReadableStreamBYOBReader',
74
+ 'ReadableStreamBYOBRequest',
75
+ 'ReadableStreamDefaultController',
76
+ 'ReadableStreamDefaultReader',
77
+ 'ReferenceError',
78
+ 'Reflect',
79
+ 'RegExp',
80
+ 'Request',
81
+ 'Response',
82
+ 'Set',
83
+ 'SharedArrayBuffer',
84
+ 'String',
85
+ 'SubtleCrypto',
86
+ 'SuppressedError',
87
+ 'Symbol',
88
+ 'SyntaxError',
89
+ 'TextDecoder',
90
+ 'TextDecoderStream',
91
+ 'TextEncoder',
92
+ 'TextEncoderStream',
93
+ 'TransformStream',
94
+ 'TransformStreamDefaultController',
95
+ 'TypeError',
96
+ 'URIError',
97
+ 'URL',
98
+ 'URLPattern',
99
+ 'URLSearchParams',
100
+ 'Uint16Array',
101
+ 'Uint32Array',
102
+ 'Uint8Array',
103
+ 'Uint8ClampedArray',
104
+ 'WeakMap',
105
+ 'WeakRef',
106
+ 'WeakSet',
107
+ 'WebAssembly',
108
+ 'WebSocket',
109
+ 'WritableStream',
110
+ 'WritableStreamDefaultController',
111
+ 'WritableStreamDefaultWriter',
112
+ 'atob',
113
+ 'btoa',
114
+ 'clearImmediate',
115
+ 'clearInterval',
116
+ 'clearTimeout',
117
+ 'console',
118
+ 'crypto',
119
+ 'decodeURI',
120
+ 'decodeURIComponent',
121
+ 'encodeURI',
122
+ 'encodeURIComponent',
123
+ 'escape',
124
+ 'eval',
125
+ 'fetch',
126
+ 'global',
127
+ 'globalThis',
128
+ 'isFinite',
129
+ 'isNaN',
130
+ 'navigator',
131
+ 'parseFloat',
132
+ 'parseInt',
133
+ 'performance',
134
+ 'process',
135
+ 'queueMicrotask',
136
+ 'setImmediate',
137
+ 'setInterval',
138
+ 'setTimeout',
139
+ 'structuredClone',
140
+ 'undefined',
141
+ 'unescape',
142
+ ])
@@ -22,13 +22,18 @@ export class WorkerPool {
22
22
  #slots = new Map()
23
23
  #next = 1
24
24
  #closed = false
25
+ #idleMs
26
+ #onRetire
25
27
  created = 0
28
+ retired = 0
26
29
 
27
- constructor({ create, init = () => {}, spare = 0, max = 256, onMessage = () => {}, onFailure = () => {} }) {
30
+ constructor({ create, init = () => {}, spare = 0, max = 256, idleMs = 0, onRetire = () => {}, onMessage = () => {}, onFailure = () => {} }) {
28
31
  this.#create = create
29
32
  this.#init = init
30
33
  this.#spare = spare
31
34
  this.#max = max
35
+ this.#idleMs = idleMs
36
+ this.#onRetire = onRetire
32
37
  this.#onMessage = onMessage
33
38
  this.#onFailure = onFailure
34
39
  }
@@ -111,7 +116,27 @@ export class WorkerPool {
111
116
  return slot.id
112
117
  }
113
118
 
119
+ // idleMs (0 = off): a Worker that has been idle that long, when more than `spare` Workers are available, is ended. A Worker made from a data: URL keeps
120
+ // memory for the module graph it loaded (about 7 MiB in WebKit) until it is ended, and the pool otherwise keeps every Worker its busiest moment needed.
121
+ #idle(slot) {
122
+ clearTimeout(slot.timer)
123
+ slot.timer = null
124
+ if (!this.#idleMs) return
125
+ slot.timer = setTimeout(() => {
126
+ slot.timer = null
127
+ if (this.#closed || slot.state !== 'idle' || !this.#slots.has(slot.id) || this.#available() <= this.#spare) return
128
+ this.#slots.delete(slot.id)
129
+ this.retired++
130
+ try {
131
+ slot.worker.terminate()
132
+ } catch {}
133
+ this.#onRetire(slot.id, slot.worker)
134
+ }, this.#idleMs)
135
+ }
136
+
114
137
  #send(slot, task, transfer) {
138
+ clearTimeout(slot.timer)
139
+ slot.timer = null
115
140
  slot.state = 'busy'
116
141
  slot.task = task
117
142
  slot.worker.postMessage(task, transfer)
@@ -125,9 +150,11 @@ export class WorkerPool {
125
150
  slot.state = 'idle'
126
151
  const next = slot.queue.shift()
127
152
  if (next) this.#send(slot, next.task, next.transfer)
153
+ else this.#idle(slot)
128
154
  } else if (type === 'done') {
129
155
  slot.state = 'idle'
130
156
  slot.task = null
157
+ this.#idle(slot)
131
158
  } else if (type === 'crash') {
132
159
  this.#crash(slot, { message: data.error })
133
160
  } else {
@@ -138,6 +165,7 @@ export class WorkerPool {
138
165
  #crash(slot, e) {
139
166
  if (this.#closed || !this.#slots.has(slot.id)) return
140
167
  this.#slots.delete(slot.id)
168
+ clearTimeout(slot.timer)
141
169
  try {
142
170
  slot.worker.terminate()
143
171
  } catch {}
@@ -151,6 +179,7 @@ export class WorkerPool {
151
179
  terminateAll() {
152
180
  this.#closed = true
153
181
  for (const s of this.#slots.values()) {
182
+ clearTimeout(s.timer)
154
183
  try {
155
184
  s.worker.terminate()
156
185
  } catch {}
@@ -28,7 +28,7 @@ export function ownFsMessage(route, m) {
28
28
  * @param {{onClose?: () => void, onError?: (e: unknown) => void, onTraffic?: () => void}} [o]
29
29
  * @returns {{close: () => void, stats: () => {served: number, waiting: number, bad: number}}}
30
30
  */
31
- export function serveOwnFs(port, route, { onClose, onError, onTraffic, kickAll = false } = {}) {
31
+ export function serveOwnFs(port, route, { onClose, onError, onTraffic, onCall, kickAll = false } = {}) {
32
32
  let served = 0
33
33
  let waiting = 0
34
34
  let bad = 0
@@ -42,6 +42,11 @@ export function serveOwnFs(port, route, { onClose, onError, onTraffic, kickAll =
42
42
  } catch (e) {
43
43
  onError?.(e)
44
44
  }
45
+ try {
46
+ route.net?.close?.() // X5 net: the run's sockets are reset, a waiting poll gets BYE
47
+ } catch (e) {
48
+ onError?.(e)
49
+ }
45
50
  onClose?.()
46
51
  }
47
52
  const answer = (id, reply, method) => {
@@ -73,6 +78,7 @@ export function serveOwnFs(port, route, { onClose, onError, onTraffic, kickAll =
73
78
  }
74
79
  return
75
80
  }
81
+ onCall?.(m.method, m.args) // the page's count of the calls by method (service-port.js, key own:<method>)
76
82
  if (route.timing && typeof m.t0 === 'number') {
77
83
  // fix5 round 6 (counters on): how long the message took to be taken up here, from the Worker's post to this handler
78
84
  const h = (route.timing['hop1'] ||= { n: 0, ms: 0, inB: 0, outB: 0 })
@@ -82,6 +82,44 @@ export function ownShimPost(process, realGlobal, g, utcClock, utcNames = [], req
82
82
  }
83
83
  }
84
84
 
85
+ // X5 net: process.exit is final (round 2). The engine's native exit records the exit and asks the embedder to terminate the JavaScript, which the browser
86
+ // cannot do (snapi_bridge_unofficial_terminate_execution answers GENERIC_FAILURE), so it returns and the program's next statements, callbacks and
87
+ // reactions still ran; a later process.exit(0) replaced the code of the first. When the engine's call has returned, the Worker is told the code
88
+ // (`__wmdExitNow`, own/worker.js, the main Worker only): it ends the run and stops running JavaScript for good. Without that hook (a thread Worker, a page
89
+ // that predates it) the first exit decides the code and a later call, reachable only in this engine, is ignored. A call inside the first (an 'exit'
90
+ // listener calling process.exit(2)) is node's own nested case and still goes through, and with the hook it is the one that ends the program.
91
+ // process.exit and process.reallyExit share the state: a signal to the program itself above ends in reallyExit.
92
+ {
93
+ let state = 0 // 0: no exit asked, 1: inside the native call, 2: the native call returned
94
+ // the run ends with the program's first process (pid 1); a node started by node ends that process only (the Worker's hook tells them apart by the pid), and a worker thread's exit is node's own
95
+ const mainThread = () => {
96
+ try {
97
+ const wt = typeof req === 'function' ? req('worker_threads') : null
98
+ return !wt || wt.isMainThread !== false
99
+ } catch {
100
+ return true
101
+ }
102
+ }
103
+ for (const name of ['exit', 'reallyExit']) {
104
+ const native = process[name]
105
+ if (typeof native !== 'function') continue
106
+ process[name] = function () {
107
+ if (state === 2) return undefined
108
+ const outer = state === 0
109
+ state = 1
110
+ let ret
111
+ try {
112
+ ret = native.apply(process, arguments)
113
+ } finally {
114
+ if (outer) state = 2
115
+ }
116
+ const now = realGlobal && realGlobal.__wmdExitNow
117
+ if (typeof now === 'function' && mainThread()) now(name === 'reallyExit' ? arguments[0] : process.exitCode, process.pid)
118
+ return ret
119
+ }
120
+ }
121
+ }
122
+
85
123
  if (realGlobal && typeof realGlobal.addEventListener === 'function') {
86
124
  realGlobal.addEventListener('unhandledrejection', (ev) => {
87
125
  ev.preventDefault()
@@ -11,6 +11,8 @@ import { checkInit, loadRuntime } from './loader.js'
11
11
  import { installCapi, installSerdesState } from './capi.js'
12
12
  import { installWasmCounters } from './wasm-counters.js'
13
13
  import { installStackHeader } from './stack-fix.js'
14
+ import { at, installMarks } from './marks.js'
15
+ import { makeExitNow, parkForever } from './exit-now.js'
14
16
 
15
17
  // node prints an uncaught error from its stack; Firefox and Safari leave the message out of it (stack-fix.js)
16
18
  installStackHeader(globalThis)
@@ -22,6 +24,9 @@ let debug = false
22
24
  let role = ''
23
25
  let capi = null
24
26
  let counters = null
27
+ let marks = false
28
+ let calls = null // X25 gate 2c item 2: the program's call ring (own/marks.js), the main Worker only, with edgeMarks=2 (the program's own instance is made on a pool Worker, so every Worker has it; the hub keeps the run's biggest)
29
+ let runId = 0
25
30
 
26
31
  const text = (err) => String((err && err.stack) || err)
27
32
 
@@ -34,11 +39,17 @@ self.addEventListener('message', async (e) => {
34
39
  if (debug) console.log(`[w] performance.memory ${typeof performance.memory} used ${performance.memory && performance.memory.usedJSHeapSize}`)
35
40
  role = m.role
36
41
  counters = installWasmCounters(globalThis) // fix7 item 15: the numbers of WebAssembly objects made by this Worker
42
+ // X5 default1 round 2 (B2.1): marks of the program's compile and instances (before the runtime loads, see marks.js), only with the option
43
+ if (m.marks) (marks = true), (calls = installMarks(globalThis, (name, t) => self.postMessage({ type: 'mark', name, t }), { calls: m.marks === 2, postCalls: (snap) => self.postMessage({ type: 'calls', ...snap }) }) || null)
44
+ if (calls && typeof calls.snapshot !== 'function') calls = null
45
+ if (marks) self.postMessage({ type: 'mark', name: m.role === 'main' ? 'mInit0' : 'tInit0', t: at() })
37
46
  if (m.fsTime) {
38
47
  // fix5 round 6 (only with the frame's __wmdFsTime): every file call carries the time it was posted, on the clock all Workers share
39
48
  const post = self.postMessage.bind(self)
40
49
  self.postMessage = (msg, t) => post(msg && msg.type === 'fs' ? { ...msg, t0: performance.timeOrigin + performance.now() } : msg, t)
41
50
  }
51
+ // X5 fix3 R6: node's global names; the runtime's global context shows no other name of this Worker's global (patched/wasmer-napi snapi_js.rs)
52
+ if (Array.isArray(m.nodeGlobals)) globalThis.__wmdNodeGlobals = m.nodeGlobals
42
53
  // before the runtime loads: the napi engine reads these when its module is evaluated
43
54
  if (m.capi) capi = installCapi(globalThis, { channel: m.capi, scope: m.scope % 4096, relay: (msg) => self.postMessage({ type: 'capi', msg }), log: m.debug ? (t) => console.log(`[capi s${m.scope}] ${t}`) : null })
44
55
  if (capi) installSerdesState(globalThis, { scope: m.scope % 4096, note: m.fsTime ? (text) => self.postMessage({ type: 'note', text }) : null })
@@ -46,7 +57,11 @@ self.addEventListener('message', async (e) => {
46
57
  glue = r.glue
47
58
  exports = r.exports
48
59
  turning = r.turning
60
+ if (marks) self.postMessage({ type: 'mark', name: m.role === 'main' ? 'mReady' : 'tReady', t: at() })
49
61
  glue.wmd_set_trace(m.trace | 0)
62
+ // X5 net round 2: process.exit is final in the program (shim-post.js calls this once the engine's exit returned; exit-now.js). The program's JavaScript
63
+ // runs on a thread Worker (the main context is a pool job), so every Worker has it; the page fills in the run for a thread's message (hub.js).
64
+ globalThis.__wmdExitNow = makeExitNow({ runId: () => (role === 'main' ? runId : undefined), post: (msg) => self.postMessage(msg), outs: () => glue.wmd_out_count(), endProcess: (pid, code) => (typeof glue.wmd_exit_process === 'function' ? glue.wmd_exit_process(pid, code) : false), park: parkForever })
50
65
  if (m.calltrace) glue.wmd_set_calltrace(true)
51
66
  if (m.napifixOff) glue.wmd_set_napifix_off(true)
52
67
  // linux.cjs's `__wmdCtl(pid, json)`: one synchronous control request to the page's file route (the shim takes it off
@@ -66,6 +81,8 @@ self.addEventListener('message', async (e) => {
66
81
  } else if (m.type === 'task') {
67
82
  try {
68
83
  if (debug) console.log('[w thread] task start')
84
+ if (marks) self.postMessage({ type: 'mark', name: 'task0', t: at() })
85
+ if (calls) calls.reset()
69
86
  if (turning) {
70
87
  // through WebAssembly.promising: the job may suspend to let this Worker's event loop run (see loader.js)
71
88
  const ptr = glue.wmd_thread_prepare(m.msg)
@@ -78,14 +95,30 @@ self.addEventListener('message', async (e) => {
78
95
  self.postMessage({ type: 'crash', error: text(err) })
79
96
  return
80
97
  }
98
+ if (calls && calls.taken) self.postMessage({ type: 'calls', ...calls.snapshot() })
81
99
  if (debug) console.log('[w thread] task done')
82
100
  self.postMessage({ type: 'done' })
83
101
  } else if (m.type === 'run') {
102
+ runId = m.id
84
103
  try {
85
104
  if (debug) console.log('[w main] run start')
105
+ if (marks) self.postMessage({ type: 'mark', name: 'runRecv', t: at() })
106
+ if (calls) calls.reset()
86
107
  const run = m.node ? glue.wmd_run_node : glue.wmd_run
87
108
  if (!run) throw new Error('this build has no N-API support (build edge/browser with --features napi)')
88
- const code = run(new Uint8Array(m.program), m.args || [], m.env || [], m.opts || '')
109
+ let code
110
+ if (m.module && !m.node && glue.wmd_run_ready) {
111
+ // X25 gate 1: a plain WASIX program (CPython) whose module the frame kept
112
+ code = glue.wmd_run_ready(m.module, m.hash, m.program, m.args || [], m.env || [], m.opts || '')
113
+ } else if (m.module && m.node && glue.wmd_run_node_ready) {
114
+ // X5 default1 round 2 (B2.1): the program compiled already (hub.js OwnRuntime.prepare): the runtime neither compiles nor hashes it.
115
+ // A runtime built before wmd_run_node_ready compiles the same bytes itself (the branch below).
116
+ code = glue.wmd_run_node_ready(m.module, m.hash, m.program, m.args || [], m.env || [], m.opts || '')
117
+ } else {
118
+ code = run(new Uint8Array(m.program), m.args || [], m.env || [], m.opts || '')
119
+ }
120
+ if (calls) self.postMessage({ type: 'calls', ...calls.snapshot() })
121
+ if (marks) self.postMessage({ type: 'mark', name: 'exitPost', t: at() })
89
122
  self.postMessage({ type: 'exit', id: m.id, code, outs: glue.wmd_out_count() })
90
123
  } catch (err) {
91
124
  self.postMessage({ type: 'run-error', id: m.id, error: text(err), outs: glue.wmd_out_count() })