@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,185 @@
1
+ import { UTC_NAME_LIST, utcClock } from '../tz.js'
2
+ import { SIG_NAMES_LINUX, SIG_IGNORED_LINUX } from '../shim.js'
3
+
4
+ // What the own runtime adds at the end of linux.cjs (the shim itself is not changed): the places where the browser's engine is not node.
5
+ //
6
+ // 1. process.memoryUsage.rss() asks process.memoryUsage() (the shim patches the second only; the engine's rss reads 0).
7
+ // 2. Unhandled promise rejections. The engine cannot report them (snapi_js.rs: set_promise_reject_callback answers failure), but the
8
+ // browser raises `unhandledrejection` on the Worker's global. They become node's: 'unhandledRejection' listeners, then
9
+ // 'uncaughtException' listeners, then the error on stderr and exit code 1.
10
+ // 3. The time zone. A container's zone is UTC unless TZ says otherwise; the browser's engine uses the browser's zone and has no way
11
+ // to be told another. With TZ unset or UTC the local-time parts of Date and the default zone of Intl.DateTimeFormat are made UTC.
12
+ // Another TZ is not supported here: the hello check sends that container to the guest (helloRefusal).
13
+ // The code is src/edge/tz.js utcClock (also what the SDK arm runs); it is handed in, so that this function stays one piece of text.
14
+ //
15
+ // 0. v8.serialize gives a Buffer (the serializer is the host's: v8-serdes.js).
16
+ // 4. rename of a file over a directory. Linux says EISDIR; WASIX turns the file system's "is a directory" into EINVAL on this target (virtual-fs has no error that maps
17
+ // to EISDIR, edge/vendor/wasmer-wasix src/fs/mod.rs fs_error_into_wasi_err), so the error is made EISDIR here when it is that case and no other (check5 F1).
18
+ //
19
+ // `ownShimPost(process, realGlobal, g, utcClock, utcNames, req)` is a plain function so that a unit test can run it; SHIM_POST is its text for the shim file.
20
+ export function ownShimPost(process, realGlobal, g, utcClock, utcNames = [], req = null, sigNames = null, sigIgnored = null) {
21
+ process.memoryUsage.rss = function rss() {
22
+ return process.memoryUsage().rss
23
+ }
24
+
25
+ // fix7 (item 10): the numbers follow the instance. The engine's heap and external numbers never change (0); the browser's JS heap (performance.memory:
26
+ // Chromium only, the Worker's isolate) is the program's heap, and the resident size is the module's memory (the shim's rss) plus that heap. Without
27
+ // performance.memory (Firefox, WebKit) the engine's numbers stay and rss follows the module's memory alone. external and arrayBuffers stay 0: the engine does
28
+ // not count them.
29
+ {
30
+ const engineMemory = process.memoryUsage
31
+ const memoryUsage = function memoryUsage() {
32
+ const m = engineMemory.apply(process, arguments)
33
+ const js = realGlobal && realGlobal.performance && realGlobal.performance.memory
34
+ if (m && js && js.usedJSHeapSize > 0) {
35
+ m.heapUsed = js.usedJSHeapSize
36
+ m.heapTotal = js.totalJSHeapSize || js.usedJSHeapSize
37
+ m.rss = (m.rss || 0) + m.heapTotal
38
+ }
39
+ return m
40
+ }
41
+ memoryUsage.rss = function rss() {
42
+ return process.memoryUsage().rss
43
+ }
44
+ process.memoryUsage = memoryUsage
45
+ }
46
+
47
+ // fix7 (F3): v8.serialize gives a Buffer, as node's does. The serializer lives in the Worker's realm (src/edge/own/v8-serdes.js) and makes the
48
+ // Buffer with the program's own class, which only the program's realm has.
49
+ try {
50
+ const st = realGlobal && realGlobal[Symbol.for('wasmer.napi.serdes.state')]
51
+ const B = g && g.Buffer
52
+ if (st && typeof B === 'function') st.bufferOf = (u8) => B.from(u8.buffer, u8.byteOffset, u8.byteLength)
53
+ } catch {
54
+ // no state: the engine's own serializer is in use
55
+ }
56
+
57
+ // fix7 (F2/F14): process.kill on the program's own pid. The engine's native call ends in a panic of the runtime (exit 45). Node delivers a handled signal to its
58
+ // handler after the call, does nothing for the signals whose default is to be ignored (and for USR1, where node starts an inspector that the frame does not have),
59
+ // and ends the program with 128+n for the rest (a program killed by a signal runs no 'exit' listeners).
60
+ if (sigNames && typeof process.kill === 'function') {
61
+ const nativeKill = process.kill
62
+ const byName = {}
63
+ for (const n of Object.keys(sigNames)) byName[sigNames[n]] = Number(n)
64
+ byName.SIGKILL = 9
65
+ const ignored = new Set(sigIgnored || [])
66
+ const later = (f) => (typeof g.setImmediate === 'function' ? g.setImmediate(f) : setTimeout(f, 0))
67
+ process.kill = function kill(pid, sig) {
68
+ // fix 11 (F-E): -pid is the program's own group (it leads it in the frame), so it is the program too; any other negative pid goes to the native call
69
+ const mine = pid === process.pid || pid === 0 || pid === '0' || String(pid) === String(process.pid) || String(pid) === '-' + process.pid
70
+ if (!mine) return nativeKill.apply(process, arguments)
71
+ if (sig === 0 || sig === '0') return true
72
+ const num = sig === undefined ? 15 : typeof sig === 'number' ? sig : byName[sig]
73
+ const name = num === 9 ? 'SIGKILL' : sigNames[num]
74
+ if (!name) return nativeKill.apply(process, arguments)
75
+ if (num !== 9 && process.listenerCount(name) > 0) {
76
+ later(() => process.emit(name, name, num))
77
+ return true
78
+ }
79
+ if (num !== 9 && (ignored.has(num) || num === 10)) return true
80
+ process.reallyExit(128 + num)
81
+ return true
82
+ }
83
+ }
84
+
85
+ if (realGlobal && typeof realGlobal.addEventListener === 'function') {
86
+ realGlobal.addEventListener('unhandledrejection', (ev) => {
87
+ ev.preventDefault()
88
+ const reason = ev.reason
89
+ if (process.emit('unhandledRejection', reason, ev.promise)) return
90
+ if (process.listenerCount('uncaughtException') > 0) {
91
+ process.emit('uncaughtException', reason, 'unhandledRejection')
92
+ return
93
+ }
94
+ const text = reason instanceof Error ? String(reason.stack || reason) : `[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${String(reason)}".] { code: 'ERR_UNHANDLED_REJECTION' }`
95
+ process.stderr.write(text + '\n')
96
+ process.exit(1)
97
+ })
98
+ }
99
+
100
+ // The container's zone is UTC unless TZ says another (and a container with another TZ never runs here: src/host/edge-host.js helloRefusal sends it to
101
+ // the guest). The clock is src/edge/tz.js utcClock, the code the SDK arm runs and the tests compare with plain node in 30 zones, so a legacy date text
102
+ // ('Jul 4, 2024 10:00', '2024/07/04') is read as node reads it with TZ=UTC (check5 F10); it is given as the 4th argument, with the UTC names.
103
+ const fs = typeof req === 'function' ? req('fs') : null
104
+ if (fs && typeof fs.renameSync === 'function') {
105
+ const isDir = (p) => {
106
+ try {
107
+ return fs.lstatSync(p).isDirectory()
108
+ } catch {
109
+ return false
110
+ }
111
+ }
112
+ const fixed = (e, from, to) => {
113
+ if (!e || e.code !== 'EINVAL' || !isDir(to) || isDir(from)) return e
114
+ const x = new Error(`EISDIR: illegal operation on a directory, rename '${from}' -> '${to}'`)
115
+ return Object.assign(x, { errno: -21, code: 'EISDIR', syscall: 'rename', path: String(from), dest: String(to) })
116
+ }
117
+ // A symbolic link whose target does not exist: WASIX looks at the target and answers ENOENT. The link is moved by making the same link at the new name and removing
118
+ // the old one (what rename does to a link: the text is kept, the target is never opened).
119
+ const moveLink = (from, to) => {
120
+ let text
121
+ try {
122
+ if (!fs.lstatSync(from).isSymbolicLink()) return false
123
+ text = fs.readlinkSync(from)
124
+ let there = null
125
+ try {
126
+ there = fs.lstatSync(to)
127
+ } catch {
128
+ // nothing at the new name
129
+ }
130
+ if (there && there.isDirectory()) return false
131
+ if (there) fs.unlinkSync(to)
132
+ fs.symlinkSync(text, to)
133
+ fs.unlinkSync(from)
134
+ return true
135
+ } catch {
136
+ return false
137
+ }
138
+ }
139
+ // A symbolic link renamed over an existing file: WASIX follows the link, so the link stays and the file at the new name is not a link (check, F1 on rt=own).
140
+ // A link is therefore always moved by moveLink (an lstat of the old name first; a name that is not a link takes the real rename).
141
+ const isLink = (p) => {
142
+ try {
143
+ return fs.lstatSync(p).isSymbolicLink()
144
+ } catch {
145
+ return false
146
+ }
147
+ }
148
+ const renameSync = fs.renameSync
149
+ fs.renameSync = function (from, to) {
150
+ if (isLink(from) && moveLink(from, to)) return undefined
151
+ try {
152
+ return renameSync.call(fs, from, to)
153
+ } catch (e) {
154
+ if (e && e.code === 'ENOENT' && moveLink(from, to)) return undefined
155
+ throw fixed(e, from, to)
156
+ }
157
+ }
158
+ const rename = fs.rename
159
+ fs.rename = function (from, to, cb) {
160
+ if (typeof cb !== 'function') return rename.call(fs, from, to, cb)
161
+ if (isLink(from) && moveLink(from, to)) return void queueMicrotask(() => cb(null))
162
+ return rename.call(fs, from, to, function (e, ...a) {
163
+ if (e && e.code === 'ENOENT' && moveLink(from, to)) return cb(null)
164
+ cb(e ? fixed(e, from, to) : e, ...a)
165
+ })
166
+ }
167
+ if (fs.promises && typeof fs.promises.rename === 'function') {
168
+ const prename = fs.promises.rename
169
+ fs.promises.rename = async function (from, to) {
170
+ if (isLink(from) && moveLink(from, to)) return undefined
171
+ try {
172
+ return await prename.call(fs.promises, from, to)
173
+ } catch (e) {
174
+ if (e && e.code === 'ENOENT' && moveLink(from, to)) return undefined
175
+ throw fixed(e, from, to)
176
+ }
177
+ }
178
+ }
179
+ }
180
+
181
+ const tz = process.env && process.env.TZ
182
+ if (typeof utcClock === 'function' && utcNames.includes(String(tz == null ? '' : tz).trim())) utcClock(g)
183
+ }
184
+
185
+ export const SHIM_POST = `\n;(${ownShimPost.toString()})(process, Function('return this')(), globalThis, ${utcClock.toString()}, ${JSON.stringify(UTC_NAME_LIST)}, typeof require === 'function' ? require : null, ${JSON.stringify(SIG_NAMES_LINUX)}, ${JSON.stringify(SIG_IGNORED_LINUX)});\n`
@@ -0,0 +1,36 @@
1
+ // Firefox and Safari write `Error.stack` as frames only (V8 writes "Name: message" first). node prints an uncaught error from its
2
+ // stack, so on those engines the program's own error message never reached stderr (node.spec.js, "a program that throws").
3
+ // This puts the header back on errors the program makes with `new Error(...)` and the other standard error classes, in the
4
+ // realm that evaluates the program's JavaScript. Errors the engine itself throws are not touched.
5
+ //
6
+ // installStackHeader(globalThis) -> true when it changed something (false when the engine already writes the header)
7
+
8
+ const NAMES = ['Error', 'TypeError', 'RangeError', 'SyntaxError', 'ReferenceError', 'EvalError', 'URIError']
9
+
10
+ export function withHeader(e) {
11
+ try {
12
+ const s = e.stack
13
+ if (typeof s !== 'string') return e
14
+ const name = String(e.name)
15
+ if (s.startsWith(name)) return e
16
+ const head = e.message ? `${name}: ${e.message}` : name
17
+ Object.defineProperty(e, 'stack', { value: `${head}\n${s}`, writable: true, configurable: true, enumerable: false })
18
+ } catch {}
19
+ return e
20
+ }
21
+
22
+ export function installStackHeader(g) {
23
+ // an engine that already writes the header (V8) needs nothing; the probe is the stack itself, not a feature test (Firefox and
24
+ // Safari have Error.captureStackTrace and still write frames only)
25
+ const probe = new g.Error('wmd-probe').stack
26
+ if (typeof probe === 'string' && probe.startsWith('Error: wmd-probe')) return false
27
+ for (const n of NAMES) {
28
+ const C = g[n]
29
+ if (typeof C !== 'function') continue
30
+ g[n] = new Proxy(C, {
31
+ construct: (target, args, newTarget) => withHeader(Reflect.construct(target, args, newTarget === g[n] ? target : newTarget)),
32
+ apply: (target, thisArg, args) => withHeader(Reflect.apply(target, thisArg, args)),
33
+ })
34
+ }
35
+ return true
36
+ }
@@ -0,0 +1,80 @@
1
+ // The page's end of the program's standard input and of the terminal's size, both in the runtime's shared memory
2
+ // (edge/browser/src/stdio.rs `StdinRing` and `TTY`).
3
+ //
4
+ // StdinRing: u32 words head (bytes the program read), tail (bytes written), closed, and the buffer at `off` bytes from `addr`,
5
+ // `cap` bytes long. The counters only grow and wrap at 2^32; the byte of counter n is at n % cap. This side writes tail and
6
+ // closed. Input that does not fit is held and written as the program reads (a timer looks again).
7
+
8
+ export class StdinPipe {
9
+ #mem
10
+ #addr
11
+ #cap
12
+ #off
13
+ #queue = []
14
+ #closing = false
15
+ #timer = null
16
+ #sleep
17
+
18
+ constructor(memory, info, { sleep = (fn, ms) => setTimeout(fn, ms) } = {}) {
19
+ this.#mem = memory
20
+ this.#addr = info.addr
21
+ this.#cap = info.cap
22
+ this.#off = info.off
23
+ this.#sleep = sleep
24
+ }
25
+
26
+ write(bytes) {
27
+ if (this.#closing) throw new Error('stdin is closed')
28
+ if (bytes.length) this.#queue.push(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))
29
+ this.#pump()
30
+ }
31
+
32
+ close() {
33
+ this.#closing = true
34
+ this.#pump()
35
+ }
36
+
37
+ /** Bytes held back because the ring is full. */
38
+ get pending() {
39
+ return this.#queue.reduce((a, b) => a + b.length, 0)
40
+ }
41
+
42
+ #pump() {
43
+ const words = new Int32Array(this.#mem.buffer, this.#addr, 3)
44
+ const data = new Uint8Array(this.#mem.buffer)
45
+ const base = this.#addr + this.#off
46
+ while (this.#queue.length) {
47
+ const head = Atomics.load(words, 0) >>> 0
48
+ const tail = Atomics.load(words, 1) >>> 0
49
+ const free = this.#cap - ((tail - head) >>> 0)
50
+ if (free <= 0) break
51
+ const chunk = this.#queue[0]
52
+ const n = Math.min(free, chunk.length)
53
+ const start = tail % this.#cap
54
+ const first = Math.min(n, this.#cap - start)
55
+ data.set(chunk.subarray(0, first), base + start)
56
+ if (n > first) data.set(chunk.subarray(first, n), base)
57
+ Atomics.store(words, 1, (tail + n) | 0)
58
+ if (n === chunk.length) this.#queue.shift()
59
+ else this.#queue[0] = chunk.subarray(n)
60
+ }
61
+ if (this.#queue.length) {
62
+ if (!this.#timer) {
63
+ this.#timer = this.#sleep(() => {
64
+ this.#timer = null
65
+ this.#pump()
66
+ }, 5)
67
+ }
68
+ return
69
+ }
70
+ if (this.#closing) Atomics.store(words, 2, 1)
71
+ }
72
+ }
73
+
74
+ /** Sets the terminal's size (word 0 columns, word 1 rows) and counts the change (word 3). */
75
+ export function setTtySize(memory, addr, cols, rows) {
76
+ const w = new Int32Array(memory.buffer, addr, 4)
77
+ Atomics.store(w, 0, cols | 0)
78
+ Atomics.store(w, 1, rows | 0)
79
+ Atomics.add(w, 3, 1)
80
+ }