@threadedstack/wmd-web 0.1.39 → 0.1.42
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.
- package/README.md +243 -1
- package/RELEASE.json +84 -49
- package/guest/arm64/Image +1 -1
- package/guest/arm64/Image-4k +1 -1
- package/guest/arm64/initramfs.cpio.gz +0 -0
- package/package.json +3 -3
- package/src/boot.js +231 -4
- package/src/edge/auto.js +77 -0
- package/src/edge/base.js +10 -0
- package/src/edge/bridge.js +76 -7
- package/src/edge/ctl.js +21 -4
- package/src/edge/error-kind.js +6 -0
- package/src/edge/frame-code.gen.js +6 -0
- package/src/edge/frame.js +58 -15
- package/src/edge/msg.js +3 -0
- package/src/edge/own/adapter.js +223 -19
- package/src/edge/own/exit-now.js +62 -0
- package/src/edge/own/fs-own-route.js +40 -3
- package/src/edge/own/fs-stats.js +11 -0
- package/src/edge/own/hub.js +126 -14
- package/src/edge/own/loader.js +3 -2
- package/src/edge/own/marks.js +158 -0
- package/src/edge/own/net-host.js +873 -0
- package/src/edge/own/node-globals.js +142 -0
- package/src/edge/own/pool.js +30 -1
- package/src/edge/own/service-receiver.js +7 -1
- package/src/edge/own/shim-post.js +38 -0
- package/src/edge/own/worker.js +34 -1
- package/src/edge/page.js +448 -25
- package/src/edge/pins.gen.js +17 -0
- package/src/edge/pins.js +21 -0
- package/src/edge/plan.js +45 -9
- package/src/edge/python-module.js +18 -0
- package/src/edge/python-pins.js +64 -0
- package/src/edge/python-plan.js +280 -0
- package/src/edge/python-source.js +34 -0
- package/src/edge/runtime.js +15 -2
- package/src/edge/sbx/cap.js +48 -0
- package/src/edge/sbx/common.js +186 -0
- package/src/edge/sbx/doc.js +121 -0
- package/src/edge/sbx/files.js +112 -0
- package/src/edge/sbx/frame.js +126 -0
- package/src/edge/sbx/gate.js +115 -0
- package/src/edge/sbx/sha256.js +68 -0
- package/src/edge/sbx/worker-entry.js +36 -0
- package/src/edge/sems.js +113 -0
- package/src/edge/service-host.js +57 -5
- package/src/edge/service-port.js +79 -5
- package/src/edge/setup.js +278 -0
- package/src/edge/shim.js +3 -1
- package/src/edge/watch.js +101 -0
- package/src/edge/worker.js +31 -2
- package/src/gowasm/setup.js +9 -6
- package/src/host/chan-service.js +8 -5
- package/src/host/chan-services.js +29 -4
- package/src/host/edge-host.js +58 -3
- package/wmdpack.wasm +0 -0
package/src/edge/ctl.js
CHANGED
|
@@ -9,10 +9,13 @@
|
|
|
9
9
|
// the desktop: the program runs as the container's root and changes no owner), stat, lstat (mode with the type bits, uid, gid,
|
|
10
10
|
// size, rdev, nlink, blksize, blocks, ino, times), utimes, lutimes, statvfs, meminfo, and the three the SDK's memory has
|
|
11
11
|
// no way to keep for the guest: symlink {path (the link), target}, link {path (the new name), from}, readlink {path}.
|
|
12
|
-
// The ops the desktop uses for child processes (alloc_exec_id, pending_signal, exitsig
|
|
12
|
+
// The ops the desktop uses for child processes (alloc_exec_id, pending_signal, exitsig) answer with nothing to do; watch_start, watch_poll_all and
|
|
13
|
+
// watch_stop are the watchers of fs.watch (watch.js, X5 fix3 R5).
|
|
13
14
|
// A reply is the op's JSON, or {err: 'ENOENT'} (a code name, which linux.cjs's ctlError reads).
|
|
14
15
|
|
|
15
16
|
import { CODES } from './codes.js'
|
|
17
|
+
import { Sems, semOp } from './sems.js'
|
|
18
|
+
import { PathWatches } from './watch.js'
|
|
16
19
|
import { resolveIn } from './resolve.js'
|
|
17
20
|
import { S_IFLNK, S_IFMT, byteStr } from '../fs/pack.js'
|
|
18
21
|
import { MAX_SYMLINKS } from '../fs/overlay.js'
|
|
@@ -27,11 +30,13 @@ export class EdgeCtl {
|
|
|
27
30
|
* @param {{root?: string, mounts: Object<string, {path: string, ro?: boolean}>}} o `mounts` as the file route has them: the
|
|
28
31
|
* container paths the SDK's mounts show. A path outside every mount is not the frame's to change (ENOENT).
|
|
29
32
|
*/
|
|
30
|
-
constructor(fs, { root = '', mounts }) {
|
|
33
|
+
constructor(fs, { root = '', mounts, now = () => performance.now() }) {
|
|
31
34
|
this.fs = fs
|
|
35
|
+
this.watches = new PathWatches(fs, now)
|
|
32
36
|
this.rootPath = root
|
|
33
37
|
this.areas = Object.values(mounts).map(m => ({ prefix: '/' + m.path.replace(/^\/+|\/+$/g, ''), ro: !!m.ro }))
|
|
34
38
|
this.execId = 0
|
|
39
|
+
this.sems = new Sems() // named semaphores of the run's processes (python's multiprocessing), sems.js
|
|
35
40
|
}
|
|
36
41
|
|
|
37
42
|
#root() {
|
|
@@ -107,6 +112,7 @@ export class EdgeCtl {
|
|
|
107
112
|
#op(r) {
|
|
108
113
|
const fs = this.fs
|
|
109
114
|
const p = String(r.path ?? '')
|
|
115
|
+
if (typeof r.op === 'string' && r.op.startsWith('sem_')) return semOp(this.sems, r) ?? { err: 'ENOSYS' }
|
|
110
116
|
switch (r.op) {
|
|
111
117
|
case 'chmod':
|
|
112
118
|
case 'lchmod': {
|
|
@@ -174,11 +180,22 @@ export class EdgeCtl {
|
|
|
174
180
|
}
|
|
175
181
|
case 'alloc_exec_id':
|
|
176
182
|
return { id: ++this.execId }
|
|
183
|
+
case 'watch_start': {
|
|
184
|
+
// X5 fix3 R5: compared scans of the Overlay (src/edge/watch.js), not an error that ends a dev server
|
|
185
|
+
const n = this.#node(p, true, false)
|
|
186
|
+
const id = this.watches.start(n, p.split('/').filter(x => x !== '').at(-1) ?? '', r.recursive)
|
|
187
|
+
return id === null ? { err: 'ENOSPC' } : { id }
|
|
188
|
+
}
|
|
189
|
+
case 'watch_poll_all': {
|
|
190
|
+
const events = this.watches.poll()
|
|
191
|
+
return events.length ? { events } : {}
|
|
192
|
+
}
|
|
193
|
+
case 'watch_stop':
|
|
194
|
+
this.watches.stop(r.id)
|
|
195
|
+
return {}
|
|
177
196
|
case 'pending_signal':
|
|
178
197
|
case 'exitsig':
|
|
179
198
|
case 'set_exitsig':
|
|
180
|
-
case 'watch_poll_all':
|
|
181
|
-
case 'watch_stop':
|
|
182
199
|
return {}
|
|
183
200
|
default:
|
|
184
201
|
return { err: 'ENOSYS' }
|
package/src/edge/error-kind.js
CHANGED
|
@@ -2,3 +2,9 @@
|
|
|
2
2
|
// runtime failure, the next nodes go to the guest until the retry time) and says what failed. An error while load() runs is one; so is an error that
|
|
3
3
|
// carries `runtimeFiles` (src/edge/own/hub.js: the runtime's wasm was not there or did not compile; it comes in start(), after load()).
|
|
4
4
|
export const errorKindOf = (e, loading) => (loading || (e && e.runtimeFiles === true) ? 'runtime' : undefined)
|
|
5
|
+
/**
|
|
6
|
+
* X5 fix2 F4: the words an errorKind may be when it travels (frame -> page): the page and the frame both keep a value only when it is one of these, never
|
|
7
|
+
* free text that decides behaviour. 'runtime': the runtime's, the program's or the settings file's fetch failed (a missing file, an answer that is not ok).
|
|
8
|
+
*/
|
|
9
|
+
export const ERROR_KINDS = new Set(['runtime'])
|
|
10
|
+
export const kindWord = k => (typeof k === 'string' && ERROR_KINDS.has(k) ? k : undefined)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// GENERATED by scripts/build-frame-code.mjs (make edge-frame-code); never edited, never committed.
|
|
2
|
+
// frame 93d986542ee0fe1a 8315; worker 1849ffec0f1d2f37 102758; ownWorker e31fb4869ca0889d 61503
|
|
3
|
+
const FRAME = "// src/edge/error-kind.js\nvar ERROR_KINDS = new Set([\"runtime\"]);\nvar kindWord = (k) => typeof k === \"string\" && ERROR_KINDS.has(k) ? k : undefined;\n\n// src/edge/sbx/common.js\nvar STRATEGIES = [\"module\", \"boot\", \"data\"];\nvar b64 = (text) => {\n const bytes = new TextEncoder().encode(text);\n let s = \"\";\n for (let i = 0;i < bytes.length; i += 32768)\n s += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));\n return btoa(s);\n};\nvar dataUrl = (text) => \"data:text/javascript;base64,\" + b64(text).replace(/\\//g, \"%2F\");\nvar blobUrl = (text) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\nvar bootSrc = (url) => `var q = []; var h = function (e) { q.push(e) }; self.addEventListener(\"message\", h);\n` + \"import(\" + JSON.stringify(url) + `).then(function () { self.removeEventListener(\"message\", h); for (var i = 0; i < q.length; i++) self.dispatchEvent(new MessageEvent(\"message\", { data: q[i].data, ports: q[i].ports })) },\n` + ` function (e) { postMessage({ type: \"done\", error: \"the frame's Worker code did not load: \" + String(e && e.message || e) }) })`;\nvar SCRIPT_LOADER = 'onmessage = e => { const d = e.data; if (d && typeof d.__wmdScript === \"string\") { onmessage = null; (0, eval)(d.__wmdScript + \"\\\\n//# sourceURL=wmd-worker.js\") } }';\nvar SCRIPT_PREFIX = \"wmd-script:\";\nfunction makeFactory(name) {\n if (name === \"data\") {\n const scripts = new Map;\n const loader = \"data:text/javascript,\" + encodeURIComponent(SCRIPT_LOADER);\n return {\n name,\n url: dataUrl,\n script: (t) => {\n const n = SCRIPT_PREFIX + scripts.size;\n scripts.set(n, t);\n return n;\n },\n make: (u, o) => {\n const t = scripts.get(u);\n if (t === undefined)\n return new Worker(u, { name: o && o.name, type: \"module\" });\n const w = new Worker(loader, { name: o && o.name, type: \"module\" });\n w.postMessage({ __wmdScript: '\"use strict\";' + t });\n return w;\n }\n };\n }\n if (name === \"boot\")\n return { name, url: blobUrl, make: (u, o) => new Worker(blobUrl(bootSrc(u)), { name: o && o.name }) };\n return { name: \"module\", url: blobUrl, make: (u, o) => new Worker(u, { name: o && o.name, type: \"module\" }) };\n}\nvar dec = new TextDecoder;\nasync function probeStrategy({ hint = \"\", timeoutMs = 1500, make = makeFactory } = {}) {\n const order = [...STRATEGIES.includes(hint) ? [hint] : [], ...STRATEGIES.filter((s) => s !== hint)];\n const first = STRATEGIES.includes(hint) ? await probeForms([hint], timeoutMs, make) : null;\n if (first && first.name)\n return first;\n const rest = await probeForms(first ? order.slice(1) : order, timeoutMs, make);\n return first ? { name: rest.name, tried: [...first.tried, ...rest.tried] } : rest;\n}\nasync function probeForms(order, timeoutMs, make) {\n const runs = order.map((name) => {\n const f = make(name);\n let w = null;\n const p = new Promise((resolve) => {\n const timer = setTimeout(() => resolve({ name, ok: false, why: `no answer in ${timeoutMs} ms` }), timeoutMs);\n const end = (r) => (clearTimeout(timer), resolve({ name, ...r }));\n try {\n const a = f.url(\"export const v = 7\");\n const b = f.url(`import { v } from ${JSON.stringify(a)}; postMessage(v)`);\n w = f.make(b, { name: \"wmd-probe\" });\n w.onmessage = (e) => end(e.data === 7 ? { ok: true } : { ok: false, why: \"a wrong answer\" });\n w.onerror = (e) => {\n e?.preventDefault?.();\n end({ ok: false, why: String(e && e.message || \"the Worker did not start\") });\n };\n } catch (e) {\n end({ ok: false, why: String(e && e.message || e).slice(0, 120) });\n }\n });\n return p.then((r) => (w && w.terminate(), r));\n });\n const tried = [];\n for (const run of runs) {\n const r = await run;\n tried.push(r);\n if (r.ok) {\n runs.forEach((x) => x.catch(() => {}));\n return { name: r.name, tried };\n }\n }\n return { name: null, tried };\n}\n\n// src/edge/sbx/frame.js\nfunction start({ port, worker, ownWorker, hint = \"\" }) {\n let w = null;\n let cur = 0;\n const live = new Set;\n globalThis.x5live = live;\n let kept = null;\n globalThis.x5kept = () => kept;\n let held = null;\n let mk = null;\n let workerUrl = \"\";\n const up = (msg) => port.postMessage(msg);\n const endWorker = (x) => {\n if (!x || !live.delete(x))\n return;\n x.onmessage = null;\n x.onerror = null;\n if (x === w)\n w = null, cur = 0;\n try {\n x.terminate();\n } catch {}\n };\n const endAll = () => {\n for (const x of [...live])\n endWorker(x);\n };\n const payload = () => {\n if (!held)\n throw new Error(\"the page handed in no files\");\n const files = { glue: held.glue, snippet: held.snippet, acorn: held.acorn, linux: held.linux, hashes: held.hashes, ...held.linuxpy ? { linuxpy: held.linuxpy } : {} };\n if (held.python)\n files.python = held.python;\n if (!(kept && kept.rtModule))\n files.wasm = held.wasm;\n if (!(kept && kept.prog))\n files.edgejs = held.edgejs;\n return { strategy: mk.name, ownWorker, files };\n };\n const spawn = () => {\n const x = mk.make(workerUrl, { name: \"wmd-edge\" });\n live.add(x);\n return x;\n };\n let prepW = null;\n let waiting = null;\n const prepDone = (r) => {\n if (!prepW)\n return;\n const p = prepW;\n prepW = null;\n endWorker(p);\n up({ x5prepared: r });\n if (waiting) {\n const d = waiting;\n waiting = null;\n begin(d);\n }\n };\n const prepare = (cfg) => {\n if (prepW || w || waiting || kept)\n return up({ x5prepared: { ok: !!kept, already: true } });\n const p = prepW = spawn();\n p.onmessage = ({ data: d }) => {\n if (d && d.type === \"keep\")\n return void (kept = d.keep);\n if (d && d.type === \"done\")\n prepDone({ ok: !!d.prepared && !d.error, ...d.error ? { error: String(d.error).slice(0, 300) } : {}, ...kindWord(d.errorKind) ? { errorKind: d.errorKind } : {}, ms: d.prepareMs });\n };\n p.onerror = (e) => prepDone({ ok: false, error: \"worker error: \" + e.message });\n try {\n p.postMessage({ cfg, ports: [], prepare: true, kept, tf: performance.timeOrigin + performance.now(), x5sbx: payload() });\n } catch (e) {\n prepDone({ ok: false, error: String(e && e.message || e).slice(0, 200), errorKind: \"runtime\" });\n }\n };\n function begin(data) {\n const run = data.run;\n cur = run;\n const mine = w = spawn();\n mine.onmessage = ({ data: d }) => {\n if (d && d.type === \"keep\")\n return void (kept = d.keep);\n up({ x5relay: d, x5run: run });\n if (d && d.type === \"done\")\n endWorker(mine);\n };\n mine.onerror = (e) => {\n up({ x5relay: { type: \"done\", error: \"worker error: \" + e.message }, x5run: run });\n endWorker(mine);\n };\n try {\n mine.postMessage({ cfg: data.cfg, ports: data.ports, tf: performance.timeOrigin + performance.now(), kept, x5sbx: payload() }, data.ports);\n } catch (e) {\n up({ x5relay: { type: \"done\", error: String(e && e.message || e).slice(0, 300), errorKind: \"runtime\" }, x5run: run });\n endWorker(mine);\n }\n }\n addEventListener(\"pagehide\", endAll);\n port.onmessage = ({ data }) => {\n if (!data)\n return;\n if (data.x5sbx === \"files\")\n return void (held = data.files);\n if (data.x5edge === \"ping\")\n return up(data.check !== undefined ? { x5pong: data.check } : \"x5-pong\");\n if (data.x5edge === \"stop\")\n return waiting = null, prepW = null, endAll();\n if (data.x5edge === \"prepare\")\n return prepare(data.cfg);\n if (data.x5edge === \"in\")\n return w && cur !== 0 && data.run === cur ? w.postMessage({ in: data.in }) : undefined;\n if (w || waiting || data.x5edge !== \"start\")\n return;\n if (prepW)\n return void (waiting = data);\n begin(data);\n };\n const evalOk = () => {\n try {\n return new Function(\"return 7\")() === 7;\n } catch {\n return false;\n }\n };\n probeStrategy({ hint }).then((r) => {\n mk = r.name ? makeFactory(r.name) : null;\n if (mk)\n workerUrl = mk.url(worker);\n up({ x5sbx: \"ready\", caps: { worker: r.name, tried: r.tried, eval: evalOk(), sab: typeof SharedArrayBuffer === \"function\", coi: globalThis.crossOriginIsolated === true } });\n });\n}\nexport {\n start as default\n};\n"
|
|
4
|
+
const WORKER = "var __defProp = Object.defineProperty;\nvar __returnValue = (v) => v;\nfunction __exportSetter(name, newValue) {\n this[name] = __returnValue.bind(null, newValue);\n}\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, {\n get: all[name],\n enumerable: true,\n configurable: true,\n set: __exportSetter.bind(all, name)\n });\n};\nvar __esm = (fn, res, err) => () => {\n if (fn)\n try {\n res = fn(fn = 0);\n } catch (e) {\n err = [e];\n }\n if (err)\n throw err[0];\n return res;\n};\n\n// src/edge/own/exit-now.js\nfunction exitOfRun(data, waiting) {\n if (data.id != null)\n return data;\n const first = waiting.keys().next();\n return first.done ? null : { ...data, id: first.value };\n}\n\n// src/edge/own/payload-size.js\nfunction payloadBytes(v, depth = 0, seen = new Set) {\n if (!v || typeof v !== \"object\" || depth > 6 || seen.has(v))\n return 0;\n if (ArrayBuffer.isView(v))\n return v.byteLength;\n if (v instanceof ArrayBuffer || typeof SharedArrayBuffer !== \"undefined\" && v instanceof SharedArrayBuffer)\n return v.byteLength;\n seen.add(v);\n let n = 0;\n for (const k of Object.keys(v))\n n += payloadBytes(v[k], depth + 1, seen);\n return n;\n}\nvar BIG_SHARE;\nvar init_payload_size = __esm(() => {\n BIG_SHARE = 1 << 20;\n});\n\n// src/edge/own/pool.js\nclass WorkerPool {\n #create;\n #init;\n #onMessage;\n #onFailure;\n #spare;\n #max;\n #slots = new Map;\n #next = 1;\n #closed = false;\n #idleMs;\n #onRetire;\n created = 0;\n retired = 0;\n constructor({ create, init = () => {}, spare = 0, max = 256, idleMs = 0, onRetire = () => {}, onMessage = () => {}, onFailure = () => {} }) {\n this.#create = create;\n this.#init = init;\n this.#spare = spare;\n this.#max = max;\n this.#idleMs = idleMs;\n this.#onRetire = onRetire;\n this.#onMessage = onMessage;\n this.#onFailure = onFailure;\n }\n get live() {\n return this.#slots.size;\n }\n get starting() {\n return this.#count(\"starting\");\n }\n get idle() {\n return this.#count(\"idle\");\n }\n get busy() {\n return this.#count(\"busy\");\n }\n get workers() {\n return [...this.#slots.values()].map((s) => s.worker);\n }\n get closed() {\n return this.#closed;\n }\n #count(state) {\n let n = 0;\n for (const s of this.#slots.values())\n if (s.state === state)\n n++;\n return n;\n }\n #available() {\n let n = 0;\n for (const s of this.#slots.values())\n if (s.state === \"idle\" || s.state === \"starting\" && s.queue.length === 0)\n n++;\n return n;\n }\n warm(n = this.#spare) {\n if (this.#closed)\n throw new Error(\"pool closed\");\n while (this.#available() < n && this.#slots.size < this.#max)\n this.#start();\n }\n #start() {\n const worker = this.#create();\n const slot = { id: this.#next++, worker, state: \"starting\", queue: [], task: null };\n this.#slots.set(slot.id, slot);\n this.created++;\n worker.addEventListener(\"message\", (e) => this.#message(slot, e.data));\n worker.addEventListener(\"error\", (e) => this.#crash(slot, e));\n this.#init(worker, slot.id);\n return slot;\n }\n dispatch(task, transfer) {\n if (this.#closed)\n throw new Error(\"pool closed\");\n let slot;\n for (const s of this.#slots.values()) {\n if (s.state === \"idle\") {\n slot = s;\n break;\n }\n }\n if (!slot) {\n for (const s of this.#slots.values()) {\n if (s.state === \"starting\" && s.queue.length === 0) {\n slot = s;\n break;\n }\n }\n }\n if (!slot) {\n if (this.#slots.size >= this.#max)\n throw new RangeError(\"worker limit reached (\" + this.#max + \")\");\n slot = this.#start();\n }\n if (slot.state === \"idle\")\n this.#send(slot, task, transfer);\n else\n slot.queue.push({ task, transfer });\n if (this.#spare)\n this.warm();\n return slot.id;\n }\n #idle(slot) {\n clearTimeout(slot.timer);\n slot.timer = null;\n if (!this.#idleMs)\n return;\n slot.timer = setTimeout(() => {\n slot.timer = null;\n if (this.#closed || slot.state !== \"idle\" || !this.#slots.has(slot.id) || this.#available() <= this.#spare)\n return;\n this.#slots.delete(slot.id);\n this.retired++;\n try {\n slot.worker.terminate();\n } catch {}\n this.#onRetire(slot.id, slot.worker);\n }, this.#idleMs);\n }\n #send(slot, task, transfer) {\n clearTimeout(slot.timer);\n slot.timer = null;\n slot.state = \"busy\";\n slot.task = task;\n slot.worker.postMessage(task, transfer);\n }\n #message(slot, data) {\n if (this.#closed || !this.#slots.has(slot.id))\n return;\n const type = data && data.type;\n if (type === \"ready\") {\n if (slot.state !== \"starting\")\n return;\n slot.state = \"idle\";\n const next = slot.queue.shift();\n if (next)\n this.#send(slot, next.task, next.transfer);\n else\n this.#idle(slot);\n } else if (type === \"done\") {\n slot.state = \"idle\";\n slot.task = null;\n this.#idle(slot);\n } else if (type === \"crash\") {\n this.#crash(slot, { message: data.error });\n } else {\n this.#onMessage(slot.id, data);\n }\n }\n #crash(slot, e) {\n if (this.#closed || !this.#slots.has(slot.id))\n return;\n this.#slots.delete(slot.id);\n clearTimeout(slot.timer);\n try {\n slot.worker.terminate();\n } catch {}\n const lost = [];\n if (slot.task)\n lost.push(slot.task);\n for (const q of slot.queue)\n lost.push(q.task);\n this.#onFailure(slot.id, lost, new Error(String(e && e.message || e || \"worker error\")));\n }\n terminateAll() {\n this.#closed = true;\n for (const s of this.#slots.values()) {\n clearTimeout(s.timer);\n try {\n s.worker.terminate();\n } catch {}\n }\n this.#slots.clear();\n }\n}\n\n// src/edge/own/fs-bridge.js\nfunction encodeReply(res) {\n if (res && res.error)\n return { kind: 0, bytes: enc.encode(JSON.stringify({ e: res.error.code, m: res.error.message })) };\n const v = res ? res.value : null;\n if (v instanceof Uint8Array)\n return { kind: 1, bytes: v };\n return { kind: 0, bytes: enc.encode(JSON.stringify({ v: v === undefined ? null : v })) };\n}\nasync function serveFsCall(memory, slot, route, onDone) {\n const slotWords = () => new Int32Array(memory.buffer, slot, 9);\n const w = slotWords();\n const cap = w[3];\n const replyPtr = w[4];\n const inLen = w[6] + w[8];\n let outLen = 0;\n let method = \"\";\n let result;\n try {\n const bytes = new Uint8Array(memory.buffer);\n const req = JSON.parse(dec.decode(bytes.slice(w[5], w[5] + w[6])));\n method = req.m;\n const data = w[8] ? bytes.slice(w[7], w[7] + w[8]) : new Uint8Array(0);\n result = await route.handle(req.m, req.a, data);\n } catch (e) {\n result = { error: { code: \"EIO\", message: String(e && e.message || e) } };\n }\n let failed = null;\n try {\n const { kind, bytes } = encodeReply(result);\n const out = slotWords();\n outLen = bytes.length;\n if (bytes.length > cap) {\n Atomics.store(out, 2, bytes.length);\n Atomics.store(out, 0, 2);\n } else {\n new Uint8Array(memory.buffer, replyPtr, bytes.length).set(bytes);\n Atomics.store(out, 2, bytes.length);\n Atomics.store(out, 1, kind);\n Atomics.store(out, 0, 1);\n }\n } catch (e) {\n failed = e;\n const out = slotWords();\n const err = enc.encode(JSON.stringify({ e: \"EIO\", m: \"reply failed: \" + String(e && e.message || e).slice(0, 120) }));\n if (err.length <= cap) {\n new Uint8Array(memory.buffer, replyPtr, err.length).set(err);\n Atomics.store(out, 2, err.length);\n Atomics.store(out, 1, 0);\n Atomics.store(out, 0, 1);\n } else {\n Atomics.store(out, 2, err.length);\n Atomics.store(out, 0, 2);\n }\n }\n Atomics.notify(slotWords(), 0);\n if (onDone)\n onDone(method, inLen, outLen);\n if (failed)\n throw failed;\n return method;\n}\nvar enc, dec;\nvar init_fs_bridge = __esm(() => {\n enc = new TextEncoder;\n dec = new TextDecoder;\n});\n\n// src/edge/own/stdio-pipe.js\nclass StdinPipe {\n #mem;\n #addr;\n #cap;\n #off;\n #queue = [];\n #closing = false;\n #timer = null;\n #sleep;\n constructor(memory, info, { sleep = (fn, ms) => setTimeout(fn, ms) } = {}) {\n this.#mem = memory;\n this.#addr = info.addr;\n this.#cap = info.cap;\n this.#off = info.off;\n this.#sleep = sleep;\n }\n write(bytes) {\n if (this.#closing)\n throw new Error(\"stdin is closed\");\n if (bytes.length)\n this.#queue.push(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));\n this.#pump();\n }\n close() {\n this.#closing = true;\n this.#pump();\n }\n get pending() {\n return this.#queue.reduce((a, b) => a + b.length, 0);\n }\n #pump() {\n const words = new Int32Array(this.#mem.buffer, this.#addr, 3);\n const data = new Uint8Array(this.#mem.buffer);\n const base = this.#addr + this.#off;\n while (this.#queue.length) {\n const head = Atomics.load(words, 0) >>> 0;\n const tail = Atomics.load(words, 1) >>> 0;\n const free = this.#cap - (tail - head >>> 0);\n if (free <= 0)\n break;\n const chunk = this.#queue[0];\n const n = Math.min(free, chunk.length);\n const start = tail % this.#cap;\n const first = Math.min(n, this.#cap - start);\n data.set(chunk.subarray(0, first), base + start);\n if (n > first)\n data.set(chunk.subarray(first, n), base);\n Atomics.store(words, 1, tail + n | 0);\n if (n === chunk.length)\n this.#queue.shift();\n else\n this.#queue[0] = chunk.subarray(n);\n }\n if (this.#queue.length) {\n if (!this.#timer) {\n this.#timer = this.#sleep(() => {\n this.#timer = null;\n this.#pump();\n }, 5);\n }\n return;\n }\n if (this.#closing)\n Atomics.store(words, 2, 1);\n }\n}\nfunction setTtySize(memory, addr, cols, rows) {\n const w = new Int32Array(memory.buffer, addr, 4);\n Atomics.store(w, 0, cols | 0);\n Atomics.store(w, 1, rows | 0);\n Atomics.add(w, 3, 1);\n}\n\n// src/edge/own/memcap.js\nfunction readLeb(b, i) {\n let r = 0;\n let s = 0;\n for (;; ) {\n const x = b[i++];\n r += (x & 127) * 2 ** s;\n s += 7;\n if (!(x & 128))\n return [r, i];\n }\n}\nfunction writePadded(b, at, len, value) {\n for (let k = 0;k < len; k++) {\n const part = value % 128;\n value = Math.floor(value / 128);\n b[at + k] = part | (k < len - 1 ? 128 : 0);\n }\n}\nfunction capMemoryMax(wasm, maxPages) {\n const b = wasm instanceof Uint8Array ? wasm : new Uint8Array(wasm);\n let i = 8;\n while (i < b.length) {\n const id = b[i++];\n let size;\n [size, i] = readLeb(b, i);\n const end = i + size;\n if (id === 2) {\n let [count, j] = readLeb(b, i);\n for (let n = 0;n < count; n++) {\n let l;\n [l, j] = readLeb(b, j);\n j += l;\n [l, j] = readLeb(b, j);\n j += l;\n const kind = b[j++];\n if (kind === 0)\n [, j] = readLeb(b, j);\n else if (kind === 1) {\n j++;\n const [fl, k] = readLeb(b, j);\n j = k;\n [, j] = readLeb(b, j);\n if (fl & 1)\n [, j] = readLeb(b, j);\n } else if (kind === 2) {\n const r = capLimits(b, j, maxPages);\n if (r.done)\n return r;\n j = r.next;\n } else if (kind === 3)\n j += 2;\n else {\n j++;\n [, j] = readLeb(b, j);\n }\n }\n } else if (id === 5) {\n const [count, j0] = readLeb(b, i);\n let j = j0;\n for (let n = 0;n < count; n++) {\n const r = capLimits(b, j, maxPages);\n if (r.done)\n return r;\n j = r.next;\n }\n }\n i = end;\n }\n return { bytes: b, before: null, after: null };\n}\nfunction capLimits(b, j, maxPages) {\n const [flags, a] = readLeb(b, j);\n const [min, c] = readLeb(b, a);\n if (!(flags & 1))\n return { done: false, next: c };\n const [max, d] = readLeb(b, c);\n const len = d - c;\n const cap = Math.max(maxPages, min);\n if (max <= cap)\n return { done: true, bytes: b, before: max, after: max };\n if (cap >= 128 ** len)\n throw new Error(\"memory cap does not fit the number it replaces\");\n const out = b.slice();\n writePadded(out, c, len, cap);\n return { done: true, bytes: out, before: max, after: cap };\n}\nvar PAGE = 65536, pagesOfMiB = (mib) => Math.floor(mib * 1024 * 1024 / PAGE);\n\n// src/edge/own/loader.js\nvar hasJspi = () => typeof WebAssembly.promising === \"function\" && typeof WebAssembly.Suspending === \"function\";\n\n// src/edge/own/procfs.js\nfunction content(path, bytes) {\n const pages = Math.ceil(bytes / PAGE_SIZE);\n if (path === \"/proc/self/statm\")\n return enc2.encode(`${pages} ${pages} 0 0 0 ${pages} 0\n`);\n return enc2.encode(`1 (node) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 0 ${bytes} ${pages} 18446744073709551615 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0\n`);\n}\nfunction withProc(route, memoryBytes) {\n const open = new Map;\n let next = FIRST;\n const clean = (p) => String(p ?? \"\").replace(/\\/+$/, \"\") || \"/\";\n const handle = (method, args, data) => {\n if (method === \"ctl\") {\n let q = null;\n try {\n q = JSON.parse(String(args[0] ?? \"\"));\n } catch {}\n if (q && q.op === \"meminfo\")\n return { value: JSON.stringify({ rss: memoryBytes() }) };\n }\n if (method === \"stat\" || method === \"open\" || method === \"readdir\") {\n const p = clean(args[0]);\n if (p === \"/proc/self\" || p === \"/proc\") {\n if (method === \"stat\")\n return { value: statDir(p === \"/proc\" ? 5 : 6) };\n if (method === \"readdir\") {\n const names = p === \"/proc\" ? [[\"self\", \"d\"]] : [[\"stat\", \"f\"], [\"statm\", \"f\"]];\n return { value: { l: names.map(([n, k]) => ({ n, ...k === \"d\" ? statDir(6) : statOf(1, n === \"stat\" ? 3 : 4) })), d: true } };\n }\n }\n if (FILES.has(p)) {\n if (method === \"stat\")\n return { value: statOf(content(p, memoryBytes()).length, p.endsWith(\"m\") ? 4 : 3) };\n const f = args[1] || {};\n if (f.w || f.c || f.cn || f.t || f.a)\n return EROFS;\n const h = next++;\n open.set(h, { p, bytes: content(p, memoryBytes()) });\n return { value: { h } };\n }\n } else if ((method === \"read\" || method === \"fstat\" || method === \"close\" || method === \"write\" || method === \"ftruncate\") && Number(args[0]) >= FIRST) {\n const e = open.get(args[0]);\n if (method === \"close\") {\n open.delete(args[0]);\n return { value: null };\n }\n if (!e)\n return EBADF;\n if (method === \"read\")\n return { value: e.bytes.subarray(Number(args[1] ?? 0), Number(args[1] ?? 0) + Number(args[2] ?? 0)) };\n if (method === \"fstat\")\n return { value: statOf(e.bytes.length, e.p.endsWith(\"m\") ? 4 : 3) };\n return EROFS;\n }\n return route.handle(method, args, data);\n };\n return {\n handle,\n queueSignal: (...a) => route.queueSignal?.(...a),\n get children() {\n return route.children;\n },\n get route() {\n return route;\n }\n };\n}\nvar PAGE_SIZE = 65536, enc2, FIRST, FILES, EROFS, EBADF, statOf = (size, ino) => ({ k: \"f\", s: size, a: \"0\", m: \"0\", c: \"0\", i: ino, nl: 1, md: 33060, u: 0, g: 0, rd: 0 }), statDir = (ino) => ({ k: \"d\", s: 4096, a: \"0\", m: \"0\", c: \"0\", i: ino, nl: 2, md: 16749, u: 0, g: 0, rd: 0 });\nvar init_procfs = __esm(() => {\n enc2 = new TextEncoder;\n FIRST = 2 ** 40;\n FILES = new Set([\"/proc/self/stat\", \"/proc/self/statm\"]);\n EROFS = { error: { code: \"EROFS\", message: \"EROFS\" } };\n EBADF = { error: { code: \"EBADF\", message: \"EBADF\" } };\n});\n\n// src/edge/own/marks.js\nclass MarkBook {\n first = {};\n last = {};\n n = {};\n all = {};\n add(name, t) {\n if (typeof name !== \"string\" || typeof t !== \"number\")\n return;\n if (this.first[name] === undefined)\n this.first[name] = t;\n if (this.last[name] === undefined || t > this.last[name])\n this.last[name] = t;\n this.n[name] = (this.n[name] || 0) + 1;\n const a = this.all[name] ||= [];\n if (a.length < 64)\n a.push(t);\n }\n}\nfunction stagesOf(m) {\n const pick = (k) => Array.isArray(k) ? k.map((x) => m[x]).find((v) => typeof v === \"number\") : m[k];\n const out = {};\n for (const [name, a, b] of STAGES) {\n const x = pick(a);\n const y = pick(b);\n if (typeof x === \"number\" && typeof y === \"number\")\n out[name] = Math.round((y - x) * 10) / 10;\n }\n return out;\n}\nvar PROGRAM_BYTES, at = () => performance.timeOrigin + performance.now(), STAGES;\nvar init_marks = __esm(() => {\n PROGRAM_BYTES = 8 << 20;\n STAGES = [\n [\"fwLoad\", \"frame\", \"fw\"],\n [\"check\", \"load0\", \"checked\"],\n [\"rtCompile\", \"rtc0\", \"rtc1\"],\n [\"program\", \"start0\", \"program\"],\n [\"shim\", \"program\", \"shim\"],\n [\"boot\", \"shim\", \"booted\"],\n [\"toMain\", \"runPost\", \"runRecv\"],\n [\"compile\", \"compile0\", \"compile1\"],\n [\"toInst\", \"compile1\", \"inst0\"],\n [\"inst\", \"inst0\", \"inst1\"],\n [\"toOut\", \"inst1\", \"firstOut\"],\n [\"tail\", [\"firstOut\", \"inst1\"], \"exitRecv\"],\n [\"exitHop\", \"exitPost\", \"exitRecv\"],\n [\"run\", \"runPost\", \"exitRecv\"]\n ];\n});\n\n// src/edge/own/fs-stats.js\nfunction readFsStats(buffer, addr) {\n if (!buffer || !addr || addr % 8 !== 0 || addr + 80 > buffer.byteLength)\n return null;\n const w = new BigUint64Array(buffer, addr, 10);\n const v = (i) => Number(Atomics.load(w, i));\n return {\n n: v(0),\n us: v(1),\n stat: { n: v(2), us: v(3) },\n ctl: { n: v(4), us: v(5) },\n other: { n: v(6), us: v(7) },\n firstMs: v(8) ? v(8) / 1000 : null,\n lastMs: v(9) ? v(9) / 1000 : null\n };\n}\n\n// src/edge/own/hub.js\nfunction runOptionsJson({ fs, cwd, stdin, tty, children, exec, shim, net = false, jspi, argv0, fscache }) {\n return JSON.stringify({ fs, cwd, stdin, tty, children, exec, shim, net: !!net, jspi, ...argv0 ? { argv0 } : {}, ...Number.isInteger(fscache) && fscache >= 0 ? { fscache } : {} });\n}\n\nclass OwnRuntime {\n #opts;\n #create;\n #module = null;\n #memory = null;\n #main = null;\n #pool = null;\n #booted = null;\n #capi = `wmd-own-capi-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n #scopes = 0;\n #byScope = new Map;\n #big = new Map;\n #bigHeld = new Map;\n #wants = new Map;\n #runs = new Map;\n #nextRun = 1;\n #dead = false;\n #outsSeen = 0;\n #capiN = { messages: 0, bytes: 0, copies: 0, copyBytes: 0, maxMessage: 0, maxRecipients: 0, heldBytes: 0, heldPeak: 0 };\n #capiHeld = new Map;\n #countWait = new Map;\n #countSeq = 0;\n #held = [];\n #glue;\n #stdin = null;\n #ttyAddr = 0;\n static async start(opts) {\n const rt = new OwnRuntime(opts);\n await rt.#boot();\n return rt;\n }\n constructor(opts) {\n this.#opts = { spare: 2, max: 128, stack: 4 * 1024 * 1024, memoryMaxMiB: 1024, onOut: () => {}, onLog: () => {}, ...opts };\n this.#create = this.#opts.create || ((url, o) => new Worker(url, o));\n const base = typeof location === \"undefined\" ? undefined : location.href;\n this.#glue = new URL(this.#opts.glueUrl, base).href;\n if (this.#opts.marks)\n this.#marks = new MarkBook;\n }\n #routeCache = null;\n #marks = null;\n #calls = null;\n get marks() {\n if (!this.#marks)\n return null;\n const fs = this.#fsStat && this.#memory ? readFsStats(this.#memory.buffer, this.#fsStat) : null;\n const first = { ...this.#marks.first };\n for (const [k, v] of Object.entries(this.#marks.last))\n if (this.#marks.n[k] > 1)\n first[k + \"Last\"] = v;\n if (fs && fs.firstMs)\n first.fsFirst = fs.firstMs;\n if (fs && fs.lastMs)\n first.fsLast = fs.lastMs;\n return { first, n: { ...this.#marks.n }, series: Object.fromEntries(Object.entries(this.#marks.all).filter(([k, v]) => v.length > 1).map(([k, v]) => [k, [...v]])), fs, memMiB: this.#memory ? Math.round(this.#memory.buffer.byteLength / 1048576) : null, ...this.#calls ? { calls: this.#calls } : {} };\n }\n #fsT = globalThis.__wmdFsTime ? new Map : null;\n #timed(t0) {\n const tr = performance.timeOrigin + performance.now();\n return (method, inB, outB) => {\n const td = performance.timeOrigin + performance.now();\n const m = this.#fsT.get(method) || { n: 0, serveMs: 0, waitMs: 0, postMs: 0, inB: 0, outB: 0 };\n m.n++;\n m.serveMs += td - tr;\n if (typeof t0 === \"number\") {\n m.waitMs += td - t0;\n m.postMs += tr - t0;\n }\n m.inB += inB;\n m.outB += outB;\n this.#fsT.set(method, m);\n };\n }\n get fsTiming() {\n return this.#fsT ? Object.fromEntries(this.#fsT) : null;\n }\n #note(text) {\n try {\n const r = this.#opts.fsRoute && this.#opts.fsRoute.handle && this.#opts.fsRoute.handle(\"note\", [String(text).slice(0, 160)], new Uint8Array(0));\n if (r && typeof r.catch === \"function\")\n r.catch(() => {});\n } catch {}\n }\n #route() {\n if (!this.#opts.fsRoute)\n return NO_ROUTE;\n return this.#routeCache ||= withProc(this.#opts.fsRoute, () => this.#memory.buffer.byteLength);\n }\n async#boot() {\n const { wasmUrl, workerUrl, stack } = this.#opts;\n try {\n this.#module = this.#opts.module || await WebAssembly.compileStreaming(fetch(wasmUrl));\n } catch (e) {\n const err = new Error(`the runtime's wasm did not load (${wasmUrl}): ${String(e && e.message || e)}`);\n err.runtimeFiles = true;\n throw err;\n }\n this.#main = this.#create(workerUrl, { type: \"module\", name: \"wmd-own-main\" });\n this.#main.addEventListener(\"message\", (e) => this.#fromWorker(e.data));\n this.#main.addEventListener(\"error\", (e) => this.#fatal(new Error(\"runtime main worker: \" + (e.message || \"error\"))));\n const ready = new Promise((resolve, reject) => this.#booted = { resolve, reject });\n this.#byScope.set(this.#scopes + 1, this.#main);\n this.#main.postMessage({ type: \"init\", role: \"main\", capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}, fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, glue: this.#glue, ...this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}, module: this.#module, stack });\n const up = await ready;\n this.#memory = up.memory;\n this.#stdin = new StdinPipe(this.#memory, up.stdin);\n this.#ttyAddr = up.tty;\n this.#pool = new WorkerPool({\n create: () => this.#create(workerUrl, { type: \"module\", name: \"wmd-own-thread\" }),\n init: (w) => (this.#byScope.set(this.#scopes + 1, w), w.postMessage({ type: \"init\", role: \"thread\", capi: this.#capi, scope: ++this.#scopes, debug: !!this.#opts.debug, calltrace: !!this.#opts.calltrace, napifixOff: !!this.#opts.napifixOff, ...this.#opts.nodeGlobals ? { nodeGlobals: this.#opts.nodeGlobals } : {}, fsTime: !!this.#fsT, marks: this.#marks ? this.#opts.marks : false, trace: this.#opts.trace | 0, glue: this.#glue, ...this.#opts.glueScript ? { glueScript: this.#opts.glueScript } : {}, module: this.#module, memory: this.#memory, stack })),\n spare: this.#opts.spare,\n max: this.#opts.max,\n idleMs: this.#opts.poolIdleMs | 0,\n onRetire: (_id, w) => {\n for (const [k, v] of this.#byScope)\n if (v === w)\n this.#byScope.delete(k);\n },\n onMessage: (_id, data) => this.#fromWorker(data),\n onFailure: (_id, tasks, err) => {\n this.#note(\"thread ended: \" + String(err && err.message || err).slice(0, 140));\n for (const t of tasks)\n this.#refuse(t.ack, err);\n }\n });\n this.#pool.warm();\n }\n run({ program, ready = null, args = [], env = [], node = false, cwd, stdin = \"null\", tty = {}, children = false, exec, shim = false, net = false, argv0, fscache }) {\n if (this.#dead)\n return Promise.reject(new Error(\"runtime terminated\"));\n const id = this.#nextRun++;\n let buf = null;\n if (ready) {\n this.memoryCap = ready.cap;\n } else {\n buf = program instanceof ArrayBuffer ? program.slice(0) : program.buffer.slice(program.byteOffset, program.byteOffset + program.byteLength);\n if (this.#opts.memoryMaxMiB) {\n const cap = capMemoryMax(new Uint8Array(buf), pagesOfMiB(this.#opts.memoryMaxMiB));\n this.memoryCap = { before: cap.before, after: cap.after };\n if (cap.bytes.buffer !== buf)\n buf = cap.bytes.buffer;\n }\n }\n return new Promise((resolve, reject) => {\n this.#runs.set(id, { resolve, reject });\n const opts = runOptionsJson({ fs: !!this.#opts.fsRoute, cwd, stdin, tty, children, exec, shim, net, jspi: hasJspi(), argv0, fscache });\n if (tty.cols || tty.rows)\n setTtySize(this.#memory, this.#ttyAddr, tty.cols || 80, tty.rows || 24);\n this.#calls = null;\n if (ready)\n this.#main.postMessage({ type: \"run\", id, program: ready.bytes, module: ready.module, hash: ready.hash, args, env, node, opts });\n else\n this.#main.postMessage({ type: \"run\", id, program: buf, args, env, node, opts }, [buf]);\n });\n }\n static async prepare(program, { memoryMaxMiB = 1024, compile = (b) => WebAssembly.compile(b), digest = (b) => crypto.subtle.digest(\"SHA-256\", b) } = {}) {\n let bytes = program instanceof Uint8Array ? program : new Uint8Array(program);\n let cap = { before: null, after: null };\n if (memoryMaxMiB) {\n const c = capMemoryMax(bytes, pagesOfMiB(memoryMaxMiB));\n cap = { before: c.before, after: c.after };\n bytes = c.bytes;\n }\n const plain = typeof SharedArrayBuffer === \"function\" && bytes.buffer instanceof SharedArrayBuffer ? bytes.slice() : bytes;\n const [hash, module] = await Promise.all([digest(plain), compile(plain)]);\n if (typeof SharedArrayBuffer === \"function\" && !(bytes.buffer instanceof SharedArrayBuffer)) {\n try {\n const shared = new Uint8Array(new SharedArrayBuffer(bytes.length));\n shared.set(bytes);\n bytes = shared;\n } catch {}\n }\n return { bytes, hash: new Uint8Array(hash), module, cap, memoryMaxMiB };\n }\n writeStdin(bytes) {\n this.#stdin.write(bytes);\n }\n closeStdin() {\n this.#stdin.close();\n }\n resize(cols, rows) {\n setTtySize(this.#memory, this.#ttyAddr, cols, rows);\n }\n get memoryBytes() {\n return this.#memory ? this.#memory.buffer.byteLength : 0;\n }\n collectCounts(ms = 400) {\n if (this.#dead)\n return Promise.resolve([]);\n const ws = [this.#main, ...this.#pool ? this.#pool.workers : []].filter(Boolean);\n const seq = ++this.#countSeq;\n return new Promise((resolve) => {\n const w = { got: [], want: ws.length };\n const end = () => {\n this.#countWait.delete(seq);\n resolve(w.got);\n };\n w.end = end;\n this.#countWait.set(seq, w);\n const t = setTimeout(end, ms);\n w.clear = () => clearTimeout(t);\n for (const x of ws) {\n try {\n x.postMessage({ type: \"counts\", seq });\n } catch {\n w.want--;\n }\n }\n if (w.got.length >= w.want)\n w.clear(), end();\n });\n }\n #forged = 0;\n get forged() {\n return this.#forged;\n }\n get capiStats() {\n return { ...this.#capiN };\n }\n #capiHold(k, data) {\n const have = this.#big.get(k);\n const e = have ? (have.data = data, have) : { data, size: payloadBytes((data.msg || {}).envelope), sent: new Set };\n if (!have) {\n this.#big.set(k, e);\n const c = this.#capiN;\n c.messages++;\n c.bytes += e.size;\n c.maxMessage = Math.max(c.maxMessage, e.size);\n c.heldBytes += e.size * 2;\n this.#bigHeld.set(k, e.size * 2);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n }\n const asks = this.#wants.get(k);\n if (asks) {\n this.#wants.delete(k);\n for (const sc of asks)\n this.#capiServe(k, e, sc);\n }\n }\n #capiWant(k, scope) {\n const e = this.#big.get(k);\n if (e)\n return this.#capiServe(k, e, scope);\n const asks = this.#wants.get(k) || new Set;\n asks.add(scope);\n this.#wants.set(k, asks);\n if (this.#wants.size > 4096)\n this.#wants.delete(this.#wants.keys().next().value);\n }\n #capiServe(k, e, scope) {\n const w = this.#byScope.get(scope);\n if (!w || e.sent.has(scope))\n return;\n e.sent.add(scope);\n const c = this.#capiN;\n c.copies++;\n c.copyBytes += e.size;\n c.maxRecipients = Math.max(c.maxRecipients, e.sent.size);\n c.heldBytes += e.size;\n this.#bigHeld.set(k, (this.#bigHeld.get(k) || 0) + e.size);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n try {\n w.postMessage(e.data);\n } catch {}\n }\n #countCapi(data) {\n const c = this.#capiN;\n const m = data.msg || {};\n const to = [this.#main, ...this.#pool ? this.#pool.workers : []].filter(Boolean).length;\n const size = payloadBytes(m.envelope);\n const k = `${m.registry}:${m.handle}`;\n if (m.t === \"share\") {\n c.messages++;\n c.bytes += size;\n c.copies += to;\n c.copyBytes += size * to;\n c.maxMessage = Math.max(c.maxMessage, size);\n c.maxRecipients = Math.max(c.maxRecipients, to);\n const held = size * (to + 1);\n c.heldBytes += held - (this.#capiHeld.get(k) || 0);\n this.#capiHeld.set(k, held);\n c.heldPeak = Math.max(c.heldPeak, c.heldBytes);\n } else if (m.t === \"delete\" && this.#capiHeld.has(k)) {\n c.heldBytes -= this.#capiHeld.get(k);\n this.#capiHeld.delete(k);\n }\n if (m.t === \"delete\" && this.#bigHeld.has(k)) {\n c.heldBytes -= this.#bigHeld.get(k);\n this.#bigHeld.delete(k);\n }\n }\n #fsStat = 0;\n #sigWake = 0;\n #sigFlags = [];\n get workerCount() {\n return this.#dead ? 0 : 1 + (this.#pool ? this.#pool.live : 0);\n }\n get pool() {\n return this.#pool;\n }\n signal(n) {\n if (n === 9)\n return this.terminate();\n this.#opts.fsRoute?.queueSignal?.(0, n);\n if (this.#sigWake && this.#memory) {\n const w = new Int32Array(this.#memory.buffer);\n Atomics.add(w, this.#sigWake >> 2, 1);\n Atomics.notify(w, this.#sigWake >> 2);\n }\n }\n terminate() {\n this.#dead = true;\n if (this.#main)\n this.#main.terminate();\n if (this.#pool)\n this.#pool.terminateAll();\n this.#fatal(new Error(\"runtime terminated\"));\n }\n #fromWorker(data) {\n switch (data && data.type) {\n case \"ready\":\n if (this.#booted)\n this.#booted.resolve(data);\n this.#booted = null;\n break;\n case \"out\":\n this.#outsSeen++;\n this.#opts.onOut(data.fd, data.data);\n this.#release();\n break;\n case \"spawn\":\n this.#spawn(data);\n break;\n case \"mark\":\n if (this.#marks)\n this.#marks.add(data.name, data.t);\n break;\n case \"calls\":\n if (this.#marks && (!this.#calls || sumCalls(data.totals) >= sumCalls(this.#calls.totals)))\n this.#calls = { seen: data.seen, wrapped: data.wrapped, ring: data.ring, totals: data.totals, inst: data.inst };\n break;\n case \"counts\": {\n const w = this.#countWait.get(data.seq);\n if (w) {\n w.got.push({ role: data.role, c: data.c });\n if (w.got.length >= w.want)\n w.clear(), w.end();\n }\n break;\n }\n case \"capi\": {\n const m = data.msg || {};\n const k = `${m.registry}:${m.handle}`;\n if (m.t === \"want\")\n return this.#capiWant(k, m.from);\n if (m.t === \"share\" && payloadBytes(m.envelope) >= BIG_SHARE)\n return this.#capiHold(k, data);\n if (m.t === \"share\")\n this.#wants.delete(k);\n if (m.t === \"delete\") {\n this.#big.delete(k);\n this.#wants.delete(k);\n }\n this.#countCapi(data);\n for (const w of [this.#main, ...this.#pool ? this.#pool.workers : []])\n if (w)\n w.postMessage(data);\n break;\n }\n case \"fs\":\n serveFsCall(this.#memory, data.slot, this.#route(), this.#fsT ? this.#timed(data.t0) : undefined).then((m) => {\n if (m === \"peek\")\n this.#note(\"hub: peek answered\");\n }).catch((e) => {\n this.#note(\"fs call failed: \" + String(e && e.message || e).slice(0, 120));\n this.#opts.onLog({ type: \"log\", text: \"fs call failed: \" + (e && e.message) });\n });\n break;\n case \"fsstat\":\n if (Number.isInteger(data.addr))\n this.#fsStat = data.addr;\n break;\n case \"sigflag\":\n if (data.wake)\n this.#sigWake = data.wake;\n if (data.buffer && data.buffer.byteLength >= data.addr + 4 && data.addr % 4 === 0)\n this.#sigFlags.push({ words: new Int32Array(data.buffer), at: data.addr >> 2, bits: data.bits | 0 });\n break;\n case \"sigraise\":\n for (const f of this.#sigFlags)\n Atomics.or(f.words, f.at, f.bits);\n break;\n case \"note\": {\n this.#note(String(data.text));\n break;\n }\n case \"exit\":\n case \"run-error\": {\n const end = exitOfRun(data, this.#runs);\n if (end)\n this.#held.push(end);\n this.#release();\n break;\n }\n case \"fatal\":\n this.#fatal(new Error(data.error));\n break;\n default:\n this.#forged++;\n }\n }\n #release() {\n const ready = this.#held.filter((d) => this.#outsSeen >= (d.outs || 0));\n if (!ready.length)\n return;\n this.#held = this.#held.filter((d) => !ready.includes(d));\n for (const d of ready) {\n const run = this.#runs.get(d.id);\n this.#runs.delete(d.id);\n if (!run)\n continue;\n if (d.type === \"exit\")\n run.resolve({ code: d.code });\n else\n run.reject(new Error(d.error));\n }\n }\n #spawn(data) {\n if (this.#marks)\n this.#marks.add(\"spawnReq\", performance.timeOrigin + performance.now());\n if (this.#opts.debug)\n console.log(\"[hub] spawn request, ack\", data.ack, \"pool\", JSON.stringify({ live: this.#pool.live, idle: this.#pool.idle, busy: this.#pool.busy, starting: this.#pool.starting }));\n try {\n this.#pool.dispatch({ type: \"task\", msg: data.msg, ack: data.ack });\n } catch (err) {\n this.#refuse(data.ack, err);\n }\n }\n #refuse(ack, err) {\n this.#opts.onLog({ type: \"log\", text: \"spawn refused: \" + (err && err.message) });\n if (!ack || !this.#memory)\n return;\n const words = new Int32Array(this.#memory.buffer);\n Atomics.compareExchange(words, ack >> 2, 0, 2);\n Atomics.notify(words, ack >> 2);\n }\n #fatal(err) {\n if (this.#booted)\n this.#booted.reject(err);\n this.#booted = null;\n for (const run of this.#runs.values())\n run.reject(err);\n this.#runs.clear();\n }\n}\nvar NO_ROUTE, sumCalls = (t) => Object.values(t || {}).reduce((s, v) => s + (parseInt(v, 10) || 0), 0);\nvar init_hub = __esm(() => {\n init_payload_size();\n init_fs_bridge();\n init_procfs();\n init_marks();\n NO_ROUTE = { handle: () => ({ error: { code: \"ENOSYS\", message: \"this runtime has no file route\" } }) };\n});\n\n// src/edge/own/wasm-counters.js\nfunction installWasmCounters(g) {\n if (g.__wmdWasmCounters)\n return g.__wmdWasmCounters;\n const W = g.WebAssembly;\n const c = {\n compile: { calls: 0, bytes: 0, ms: 0 },\n stream: { calls: 0, bytes: 0, ms: 0 },\n instantiate: { calls: 0, bytes: 0, ms: 0 },\n module: { calls: 0, bytes: 0, ms: 0, maxMs: 0 },\n memory: { made: 0, shared: 0, madeBytes: 0 },\n fetched: {}\n };\n const refs = [];\n const kinds = [];\n const wrapAsync = (name, slot, bytesOf) => {\n const orig = W[name];\n if (typeof orig !== \"function\")\n return;\n W[name] = function(...a) {\n c[slot].calls++;\n c[slot].bytes += bytesOf ? bytesOf(a[0]) : 0;\n const t0 = performance.now();\n const p = orig.apply(this, a);\n return p && typeof p.then === \"function\" ? p.finally(() => c[slot].ms += performance.now() - t0) : p;\n };\n };\n wrapAsync(\"compile\", \"compile\", sizeOf);\n wrapAsync(\"instantiate\", \"instantiate\", sizeOf);\n const streamBytes = (r) => {\n try {\n return Number(r && r.headers && r.headers.get && r.headers.get(\"content-length\")) || 0;\n } catch {\n return 0;\n }\n };\n wrapAsync(\"compileStreaming\", \"stream\", null);\n wrapAsync(\"instantiateStreaming\", \"stream\", null);\n if (W.Module) {\n W.Module = new Proxy(W.Module, {\n construct(target, args) {\n const t0 = performance.now();\n const m = Reflect.construct(target, args);\n const ms = performance.now() - t0;\n c.module.calls++;\n c.module.bytes += sizeOf(args[0]);\n c.module.ms += ms;\n c.module.maxMs = Math.max(c.module.maxMs, ms);\n return m;\n }\n });\n }\n if (W.Memory) {\n W.Memory = new Proxy(W.Memory, {\n construct(target, args) {\n const d = args[0] || {};\n const m = Reflect.construct(target, args);\n c.memory.made++;\n if (d.shared)\n c.memory.shared++;\n refs.push(new WeakRef(m));\n kinds.push({ ref: new WeakRef(m), initial: d.initial | 0, maximum: d.maximum, shared: !!d.shared });\n return m;\n }\n });\n }\n const R = g.Response && g.Response.prototype;\n if (R && R.arrayBuffer) {\n const orig = R.arrayBuffer;\n R.arrayBuffer = async function() {\n const b = await orig.call(this);\n const k = kind(this.url);\n const f = c.fetched[k] ||= { calls: 0, bytes: 0 };\n f.calls++;\n f.bytes += b.byteLength;\n return b;\n };\n }\n const api = {\n kinds() {\n return kinds.map((k) => {\n const m = k.ref.deref();\n return { initial: k.initial, maximum: k.maximum, shared: k.shared, pages: m ? m.buffer.byteLength / 65536 : null };\n });\n },\n snapshot() {\n let live = 0;\n let liveBytes = 0;\n for (let i = refs.length - 1;i >= 0; i--) {\n const m = refs[i].deref();\n if (!m)\n continue;\n live++;\n try {\n liveBytes += m.buffer.byteLength;\n } catch {}\n }\n return JSON.parse(JSON.stringify({ ...c, memory: { ...c.memory, live, liveBytes }, kinds: api.kinds() }));\n }\n };\n g.__wmdWasmCounters = api;\n return api;\n}\nfunction addCounts(a, b) {\n const out = JSON.parse(JSON.stringify(a || {}));\n const walk = (dst, src) => {\n for (const [k, v] of Object.entries(src || {})) {\n if (v && typeof v === \"object\")\n walk(dst[k] ||= {}, v);\n else\n dst[k] = (Number(dst[k]) || 0) + (Number(v) || 0);\n }\n };\n walk(out, b);\n return out;\n}\nvar kind = (url) => {\n const u = String(url || \"\");\n if (/edgejs\\.wasm/.test(u))\n return \"program\";\n if (/wmd_browser_bg\\.wasm/.test(u))\n return \"runtime\";\n if (/wmd_browser\\.js/.test(u))\n return \"glue\";\n if (/HASHES\\.txt/.test(u))\n return \"hashes\";\n if (/linux\\.cjs/.test(u))\n return \"shim\";\n return \"other\";\n}, sizeOf = (src) => {\n try {\n if (src && typeof src.byteLength === \"number\")\n return src.byteLength;\n if (src && src.buffer && typeof src.buffer.byteLength === \"number\")\n return src.buffer.byteLength;\n } catch {}\n return 0;\n};\n\n// src/edge/own/node-globals.js\nvar NODE_GLOBALS;\nvar init_node_globals = __esm(() => {\n NODE_GLOBALS = Object.freeze([\n \"AbortController\",\n \"AbortSignal\",\n \"AggregateError\",\n \"Array\",\n \"ArrayBuffer\",\n \"AsyncDisposableStack\",\n \"Atomics\",\n \"BigInt\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Blob\",\n \"Boolean\",\n \"BroadcastChannel\",\n \"Buffer\",\n \"ByteLengthQueuingStrategy\",\n \"CloseEvent\",\n \"CompressionStream\",\n \"CountQueuingStrategy\",\n \"Crypto\",\n \"CryptoKey\",\n \"CustomEvent\",\n \"DOMException\",\n \"DataView\",\n \"Date\",\n \"DecompressionStream\",\n \"DisposableStack\",\n \"Error\",\n \"EvalError\",\n \"Event\",\n \"EventTarget\",\n \"File\",\n \"FinalizationRegistry\",\n \"Float16Array\",\n \"Float32Array\",\n \"Float64Array\",\n \"FormData\",\n \"Function\",\n \"Headers\",\n \"Infinity\",\n \"Int16Array\",\n \"Int32Array\",\n \"Int8Array\",\n \"Intl\",\n \"Iterator\",\n \"JSON\",\n \"Map\",\n \"Math\",\n \"MessageChannel\",\n \"MessageEvent\",\n \"MessagePort\",\n \"NaN\",\n \"Navigator\",\n \"Number\",\n \"Object\",\n \"Performance\",\n \"PerformanceEntry\",\n \"PerformanceMark\",\n \"PerformanceMeasure\",\n \"PerformanceObserver\",\n \"PerformanceObserverEntryList\",\n \"PerformanceResourceTiming\",\n \"Promise\",\n \"Proxy\",\n \"RangeError\",\n \"ReadableByteStreamController\",\n \"ReadableStream\",\n \"ReadableStreamBYOBReader\",\n \"ReadableStreamBYOBRequest\",\n \"ReadableStreamDefaultController\",\n \"ReadableStreamDefaultReader\",\n \"ReferenceError\",\n \"Reflect\",\n \"RegExp\",\n \"Request\",\n \"Response\",\n \"Set\",\n \"SharedArrayBuffer\",\n \"String\",\n \"SubtleCrypto\",\n \"SuppressedError\",\n \"Symbol\",\n \"SyntaxError\",\n \"TextDecoder\",\n \"TextDecoderStream\",\n \"TextEncoder\",\n \"TextEncoderStream\",\n \"TransformStream\",\n \"TransformStreamDefaultController\",\n \"TypeError\",\n \"URIError\",\n \"URL\",\n \"URLPattern\",\n \"URLSearchParams\",\n \"Uint16Array\",\n \"Uint32Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"WeakMap\",\n \"WeakRef\",\n \"WeakSet\",\n \"WebAssembly\",\n \"WebSocket\",\n \"WritableStream\",\n \"WritableStreamDefaultController\",\n \"WritableStreamDefaultWriter\",\n \"atob\",\n \"btoa\",\n \"clearImmediate\",\n \"clearInterval\",\n \"clearTimeout\",\n \"console\",\n \"crypto\",\n \"decodeURI\",\n \"decodeURIComponent\",\n \"encodeURI\",\n \"encodeURIComponent\",\n \"escape\",\n \"eval\",\n \"fetch\",\n \"global\",\n \"globalThis\",\n \"isFinite\",\n \"isNaN\",\n \"navigator\",\n \"parseFloat\",\n \"parseInt\",\n \"performance\",\n \"process\",\n \"queueMicrotask\",\n \"setImmediate\",\n \"setInterval\",\n \"setTimeout\",\n \"structuredClone\",\n \"undefined\",\n \"unescape\"\n ]);\n});\n\n// src/edge/shim.js\nfunction nodeVersionJs(v) {\n if (typeof v !== \"string\" || !NODE_VERSION.test(v))\n return \"\";\n return `\n;(() => {\n const version = ${JSON.stringify(v)};\n const hide = (o, k, value) => Object.defineProperty(o, k, { value, writable: false, enumerable: true, configurable: true });\n hide(process, 'version', version);\n if (process.versions) hide(process.versions, 'node', version.slice(1));\n})();\n`;\n}\nfunction withoutSymlinkOverride(links) {\n const a = links.indexOf(SYMLINK_FROM);\n const b = links.indexOf(SYMLINK_TO);\n if (a < 0 || b < a || links.split(PROMISE_SYMLINK).length !== 2)\n throw new Error(\"shim.js: the symlink block of BROWSER_LINKS moved; withoutSymlinkOverride needs a change\");\n const middle = links.slice(a, b);\n const at = middle.indexOf(\" if (fs.promises) {\");\n return links.slice(0, a) + middle.slice(at).replace(PROMISE_SYMLINK, \"\") + links.slice(b);\n}\nfunction shimSource(src, settings, { symlinks = true } = {}) {\n 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]]) {\n const n = src.split(text).length - 1;\n if (n !== 1)\n throw new Error(`linux.cjs: the ${name} is there ${n} times, not once; the browser shim needs a change`);\n }\n return src.replace(SETTINGS_MARKER, () => JSON.stringify(settings)).replace(TAKE, () => TAKE_HERE).replace(SIG_TABLE_FROM, () => SIG_TABLE_TO).replace(SIG_EMIT_FROM, () => SIG_EMIT_TO).replace(LINKS_MARKER, () => (symlinks ? BROWSER_LINKS : withoutSymlinkOverride(BROWSER_LINKS)) + LINKS_MARKER) + nodeVersionJs(settings && settings.nodeVersion);\n}\nvar SETTINGS_MARKER = \"/*__WMD_EDGE_CONFIG__*/{}\", TAKE = `const hostCtl = globalThis.__wmdCtl;\n delete globalThis.__wmdCtl;`, TAKE_HERE = `const realGlobal = Function('return this')();\n const hostCtl = globalThis.__wmdCtl || realGlobal.__wmdCtl;\n delete globalThis.__wmdCtl;\n delete realGlobal.__wmdCtl;`, LINKS_MARKER = \" function ctlError(r, syscall, p) {\", BROWSER_LINKS = ` {\n const pathOf = p => (typeof p === 'string' ? p : Buffer.isBuffer(p) ? p.toString() : null);\n const viaCtl = (op, p, key) => {\n const s = pathOf(p);\n if (s === null) return null;\n try { const r = ctl({ op, path: require('path').resolve(s) }); return r.err ? null : r[key]; } catch (_) { return null; }\n };\n const origRealpathSync = fs.realpathSync;\n const realpathSync = function realpathSync(p, o) {\n const r = viaCtl('realpath', p, 'path');\n if (r === null) return origRealpathSync.apply(fs, arguments);\n return o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r;\n };\n realpathSync.native = realpathSync;\n fs.realpathSync = realpathSync;\n const realpath = function realpath(p, o, cb) {\n if (typeof o === 'function') { cb = o; o = undefined; }\n let r;\n try { r = realpathSync(p, o); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null, r);\n };\n realpath.native = realpath;\n fs.realpath = realpath;\n const origReadlinkSync = fs.readlinkSync;\n const readlinkSync = function readlinkSync(p, o) {\n const r = viaCtl('readlink', p, 'target');\n return r === null ? origReadlinkSync.apply(fs, arguments) : (o && (o === 'buffer' || o.encoding === 'buffer') ? Buffer.from(r) : r);\n };\n fs.readlinkSync = readlinkSync;\n const origReadlink = fs.readlink;\n fs.readlink = function readlink(p, o, cb) {\n if (typeof o === 'function') { cb = o; o = undefined; }\n if (viaCtl('readlink', p, 'target') === null) return origReadlink.apply(fs, arguments);\n let r;\n try { r = readlinkSync(p, o); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null, r);\n };\n // The mount has no symlink call either; a link is made by the control request (npm's node_modules/.bin links).\n const symlinkSync = function symlinkSync(target, path) {\n const s = pathOf(path);\n if (s === null) return origSymlinkSync.apply(fs, arguments);\n const full = require('path').resolve(s);\n const r = ctl({ op: 'symlink', path: full, target: String(pathOf(target) === null ? target : pathOf(target)) });\n if (r.err) throw ctlError(r, 'symlink', s);\n };\n const origSymlinkSync = fs.symlinkSync;\n fs.symlinkSync = symlinkSync;\n fs.symlink = function symlink(target, path, type, cb) {\n if (typeof type === 'function') cb = type;\n try { symlinkSync(target, path); } catch (e) { return process.nextTick(cb, e); }\n process.nextTick(cb, null);\n };\n if (fs.promises) {\n fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };\n fs.promises.realpath = async function realpath(p, o) { return realpathSync(p, o); };\n const origP = fs.promises.readlink;\n fs.promises.readlink = async function readlink(p, o) { return viaCtl('readlink', p, 'target') === null ? origP.apply(fs.promises, arguments) : readlinkSync(p, o); };\n }\n // 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\n // character device to node, so process.stdout.isTTY is true and npm would draw progress. The guest's node says undefined.\n for (const name of ['stdin', 'stdout', 'stderr']) {\n const d = Object.getOwnPropertyDescriptor(process, name);\n if (!d || !d.get) continue;\n Object.defineProperty(process, name, {\n configurable: true,\n enumerable: d.enumerable,\n get() {\n const st = d.get.call(process);\n if (st && st.isTTY) { try { delete st.isTTY; } catch (_) {} if (st.isTTY) { try { Object.defineProperty(st, 'isTTY', { value: undefined, configurable: true }); } catch (_) {} } }\n return st;\n },\n });\n }\n }\n`, NODE_VERSION, SYMLINK_FROM = \" // The mount has no symlink call either; a link is made by the control request\", SYMLINK_TO = \" // The page's run has pipes for stdio\", PROMISE_SYMLINK = ` fs.promises.symlink = async function symlink(target, path) { return symlinkSync(target, path); };\n`, SIG_TABLE_FROM = \" const SIG_NAMES = { 1: 'SIGHUP', 2: 'SIGINT', 3: 'SIGQUIT', 15: 'SIGTERM' };\", SIG_NAMES_LINUX, SIG_IGNORED_LINUX, SIG_TABLE_TO, SIG_EMIT_FROM = ` if (process.listenerCount(name) > 0) {\n process.emit(name, name);\n } else {`, SIG_EMIT_TO = ` if (process.listenerCount(name) > 0) {\n // tell the page that a handler takes it: the program is not stuck and is not cut off after the grace period (fix7)\n try { ctl({ op: 'signal_taken', n: sig, handled: true }); } catch (_) {}\n process.emit(name, name, sig);\n } else if (SIG_IGNORED.has(sig)) {\n // the default action of this signal leaves the program running\n } else {\n // the default action ends the program: the page learns it, so that the stub dies of the signal as node in the guest does (R4)\n try { ctl({ op: 'signal_taken', n: sig, handled: false }); } catch (_) {}`;\nvar init_shim = __esm(() => {\n NODE_VERSION = /^v\\d+\\.\\d+\\.\\d+$/;\n SIG_NAMES_LINUX = {\n 1: \"SIGHUP\",\n 2: \"SIGINT\",\n 3: \"SIGQUIT\",\n 4: \"SIGILL\",\n 5: \"SIGTRAP\",\n 6: \"SIGABRT\",\n 7: \"SIGBUS\",\n 8: \"SIGFPE\",\n 10: \"SIGUSR1\",\n 11: \"SIGSEGV\",\n 12: \"SIGUSR2\",\n 13: \"SIGPIPE\",\n 14: \"SIGALRM\",\n 15: \"SIGTERM\",\n 16: \"SIGSTKFLT\",\n 17: \"SIGCHLD\",\n 18: \"SIGCONT\",\n 19: \"SIGSTOP\",\n 20: \"SIGTSTP\",\n 21: \"SIGTTIN\",\n 22: \"SIGTTOU\",\n 23: \"SIGURG\",\n 24: \"SIGXCPU\",\n 25: \"SIGXFSZ\",\n 26: \"SIGVTALRM\",\n 27: \"SIGPROF\",\n 28: \"SIGWINCH\",\n 29: \"SIGIO\",\n 30: \"SIGPWR\",\n 31: \"SIGSYS\"\n };\n SIG_IGNORED_LINUX = [10, 13, 17, 18, 19, 20, 21, 22, 23, 28];\n SIG_TABLE_TO = ` const SIG_NAMES = ${JSON.stringify(SIG_NAMES_LINUX)};\n const SIG_IGNORED = new Set(${JSON.stringify(SIG_IGNORED_LINUX)});`;\n});\n\n// src/edge/tz.js\nfunction utcClock(g) {\n const RealDate = g.Date;\n const proto = RealDate.prototype;\n const realOffset = proto.getTimezoneOffset;\n const DAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n const p2 = (n) => String(n).padStart(2, \"0\");\n const pairs = [[\"FullYear\"], [\"Month\"], [\"Date\"], [\"Day\"], [\"Hours\"], [\"Minutes\"], [\"Seconds\"], [\"Milliseconds\"]];\n const def = (name, fn) => Object.defineProperty(proto, name, { value: fn, writable: true, configurable: true, enumerable: false });\n for (const [n] of pairs) {\n def(\"get\" + n, function() {\n return this[\"getUTC\" + n]();\n });\n if (n !== \"Day\")\n def(\"set\" + n, function(...a) {\n return this[\"setUTC\" + n](...a);\n });\n }\n def(\"getYear\", function() {\n return this.getUTCFullYear() - 1900;\n });\n def(\"setYear\", function(y) {\n return this.setUTCFullYear(y >= 0 && y <= 99 ? 1900 + y : y);\n });\n def(\"getTimezoneOffset\", function() {\n return Number.isNaN(this.getTime()) ? NaN : 0;\n });\n const year = (y) => y >= 0 ? String(y).padStart(4, \"0\") : \"-\" + String(-y).padStart(4, \"0\");\n const dateText = (d) => `${DAYS[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${p2(d.getUTCDate())} ${year(d.getUTCFullYear())}`;\n const timeText = (d) => `${p2(d.getUTCHours())}:${p2(d.getUTCMinutes())}:${p2(d.getUTCSeconds())} GMT+0000 (Coordinated Universal Time)`;\n const valid = (d, f) => Number.isNaN(d.getTime()) ? \"Invalid Date\" : f(d);\n def(\"toString\", function() {\n return valid(this, (d) => dateText(d) + \" \" + timeText(d));\n });\n def(\"toDateString\", function() {\n return valid(this, dateText);\n });\n def(\"toTimeString\", function() {\n return valid(this, timeText);\n });\n for (const name of [\"toLocaleString\", \"toLocaleDateString\", \"toLocaleTimeString\"]) {\n const orig = proto[name];\n def(name, function(loc, opt) {\n return orig.call(this, loc, { timeZone: \"UTC\", ...opt });\n });\n }\n const isoDate = /^(?:\\+\\d{6}|-(?!000000)\\d{6}|\\d{4})(?:-\\d\\d(?:-\\d\\d)?)?$/;\n const isoLocalTime = /^(?:[+-]\\d{6}|\\d{4})-\\d\\d-\\d\\dT\\d\\d:\\d\\d(?::\\d\\d(?:\\.\\d+)?)?$/i;\n 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;\n const zonedInside = /\\b(?:GMT|UTC|UT)\\b|\\b[ECMP][SD]T\\b|\\dZ\\b|\\s[+-]\\d{2}:?\\d{2}\\b/i;\n const dayBefore = (t) => realOffset.call(new RealDate(t - 86400000));\n const parse = (v) => {\n const s = String(v);\n const t = RealDate.parse(s);\n if (isoDate.test(s) || hasZone.test(s))\n return t;\n const off = Number.isNaN(t) || zonedInside.test(s) ? 0 : realOffset.call(new RealDate(t));\n const iso = isoLocalTime.test(s);\n for (const tail of iso ? [\"Z\"] : [\" GMT\", \"Z\"]) {\n const u = RealDate.parse(s + tail);\n if (!Number.isNaN(u) && (iso || u !== t || off === 0 || dayBefore(t) === 0))\n return u;\n }\n if (Number.isNaN(t))\n return NaN;\n if (!zonedInside.test(s) && !s.includes(\":\") && t % 86400000 === 0 && realOffset.call(new RealDate(t)) !== 0)\n return t;\n const offT = realOffset.call(new RealDate(t));\n let c = t - offT * 60000;\n const offB = dayBefore(t);\n if (offB !== offT) {\n const d = new RealDate(c);\n if (!new RegExp(\"(^|\\\\D)0?\" + d.getUTCHours() + \":\" + p2(d.getUTCMinutes()) + \"(\\\\D|$)\").test(s))\n c = t - offB * 60000;\n }\n return new RealDate(c).getTime();\n };\n const D = new Proxy(RealDate, {\n construct(t, a, nt) {\n if (a.length >= 2)\n return Reflect.construct(t, [RealDate.UTC(...a)], nt);\n if (a.length === 1 && typeof a[0] === \"string\")\n return Reflect.construct(t, [parse(a[0])], nt);\n return Reflect.construct(t, a, nt);\n },\n apply: () => new D().toString(),\n get: (t, k, r) => k === \"parse\" ? parse : Reflect.get(t, k, t)\n });\n Object.defineProperty(proto, \"constructor\", { value: D, writable: true, configurable: true, enumerable: false });\n g.Date = D;\n const DTF = g.Intl.DateTimeFormat;\n g.Intl.DateTimeFormat = new Proxy(DTF, {\n construct: (t, [loc, opt], nt) => Reflect.construct(t, [loc, { timeZone: \"UTC\", ...opt }], nt),\n apply: (t, th, [loc, opt]) => t(loc, { timeZone: \"UTC\", ...opt })\n });\n}\nfunction withUtcClock(src) {\n const head = \"'use strict';\";\n if (src.split(head).length !== 2 || !src.startsWith(head))\n throw new Error(\"linux.cjs: 'use strict' is not the first statement, once; the browser's clock needs a change\");\n return head + `\n(${utcClock})(globalThis);` + src.slice(head.length);\n}\nvar UTC_NAME_LIST, UTC_NAMES;\nvar init_tz = __esm(() => {\n UTC_NAME_LIST = [\"\", \"UTC\", \"UTC0\", \"Etc/UTC\", \"GMT\", \"GMT0\", \"Etc/GMT\", \"Etc/GMT0\", \"Etc/Universal\", \"Etc/Zulu\", \"Universal\", \"Zulu\", \"Z\", \":UTC\"];\n UTC_NAMES = new Set(UTC_NAME_LIST);\n});\n\n// src/edge/own/shim-post.js\nfunction ownShimPost(process, realGlobal, g, utcClock2, utcNames = [], req = null, sigNames = null, sigIgnored = null) {\n process.memoryUsage.rss = function rss() {\n return process.memoryUsage().rss;\n };\n {\n const engineMemory = process.memoryUsage;\n const memoryUsage = function memoryUsage() {\n const m = engineMemory.apply(process, arguments);\n const js = realGlobal && realGlobal.performance && realGlobal.performance.memory;\n if (m && js && js.usedJSHeapSize > 0) {\n m.heapUsed = js.usedJSHeapSize;\n m.heapTotal = js.totalJSHeapSize || js.usedJSHeapSize;\n m.rss = (m.rss || 0) + m.heapTotal;\n }\n return m;\n };\n memoryUsage.rss = function rss() {\n return process.memoryUsage().rss;\n };\n process.memoryUsage = memoryUsage;\n }\n try {\n const st = realGlobal && realGlobal[Symbol.for(\"wasmer.napi.serdes.state\")];\n const B = g && g.Buffer;\n if (st && typeof B === \"function\")\n st.bufferOf = (u8) => B.from(u8.buffer, u8.byteOffset, u8.byteLength);\n } catch {}\n if (sigNames && typeof process.kill === \"function\") {\n const nativeKill = process.kill;\n const byName = {};\n for (const n of Object.keys(sigNames))\n byName[sigNames[n]] = Number(n);\n byName.SIGKILL = 9;\n const ignored = new Set(sigIgnored || []);\n const later = (f) => typeof g.setImmediate === \"function\" ? g.setImmediate(f) : setTimeout(f, 0);\n process.kill = function kill(pid, sig) {\n const mine = pid === process.pid || pid === 0 || pid === \"0\" || String(pid) === String(process.pid) || String(pid) === \"-\" + process.pid;\n if (!mine)\n return nativeKill.apply(process, arguments);\n if (sig === 0 || sig === \"0\")\n return true;\n const num = sig === undefined ? 15 : typeof sig === \"number\" ? sig : byName[sig];\n const name = num === 9 ? \"SIGKILL\" : sigNames[num];\n if (!name)\n return nativeKill.apply(process, arguments);\n if (num !== 9 && process.listenerCount(name) > 0) {\n later(() => process.emit(name, name, num));\n return true;\n }\n if (num !== 9 && (ignored.has(num) || num === 10))\n return true;\n process.reallyExit(128 + num);\n return true;\n };\n }\n {\n let state = 0;\n const mainThread = () => {\n try {\n const wt = typeof req === \"function\" ? req(\"worker_threads\") : null;\n return !wt || wt.isMainThread !== false;\n } catch {\n return true;\n }\n };\n for (const name of [\"exit\", \"reallyExit\"]) {\n const native = process[name];\n if (typeof native !== \"function\")\n continue;\n process[name] = function() {\n if (state === 2)\n return;\n const outer = state === 0;\n state = 1;\n let ret;\n try {\n ret = native.apply(process, arguments);\n } finally {\n if (outer)\n state = 2;\n }\n const now = realGlobal && realGlobal.__wmdExitNow;\n if (typeof now === \"function\" && mainThread())\n now(name === \"reallyExit\" ? arguments[0] : process.exitCode, process.pid);\n return ret;\n };\n }\n }\n if (realGlobal && typeof realGlobal.addEventListener === \"function\") {\n realGlobal.addEventListener(\"unhandledrejection\", (ev) => {\n ev.preventDefault();\n const reason = ev.reason;\n if (process.emit(\"unhandledRejection\", reason, ev.promise))\n return;\n if (process.listenerCount(\"uncaughtException\") > 0) {\n process.emit(\"uncaughtException\", reason, \"unhandledRejection\");\n return;\n }\n 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' }`;\n process.stderr.write(text + `\n`);\n process.exit(1);\n });\n }\n const fs = typeof req === \"function\" ? req(\"fs\") : null;\n if (fs && typeof fs.renameSync === \"function\") {\n const isDir = (p) => {\n try {\n return fs.lstatSync(p).isDirectory();\n } catch {\n return false;\n }\n };\n const fixed = (e, from, to) => {\n if (!e || e.code !== \"EINVAL\" || !isDir(to) || isDir(from))\n return e;\n const x = new Error(`EISDIR: illegal operation on a directory, rename '${from}' -> '${to}'`);\n return Object.assign(x, { errno: -21, code: \"EISDIR\", syscall: \"rename\", path: String(from), dest: String(to) });\n };\n const moveLink = (from, to) => {\n let text;\n try {\n if (!fs.lstatSync(from).isSymbolicLink())\n return false;\n text = fs.readlinkSync(from);\n let there = null;\n try {\n there = fs.lstatSync(to);\n } catch {}\n if (there && there.isDirectory())\n return false;\n if (there)\n fs.unlinkSync(to);\n fs.symlinkSync(text, to);\n fs.unlinkSync(from);\n return true;\n } catch {\n return false;\n }\n };\n const isLink = (p) => {\n try {\n return fs.lstatSync(p).isSymbolicLink();\n } catch {\n return false;\n }\n };\n const renameSync = fs.renameSync;\n fs.renameSync = function(from, to) {\n if (isLink(from) && moveLink(from, to))\n return;\n try {\n return renameSync.call(fs, from, to);\n } catch (e) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return;\n throw fixed(e, from, to);\n }\n };\n const rename = fs.rename;\n fs.rename = function(from, to, cb) {\n if (typeof cb !== \"function\")\n return rename.call(fs, from, to, cb);\n if (isLink(from) && moveLink(from, to))\n return void queueMicrotask(() => cb(null));\n return rename.call(fs, from, to, function(e, ...a) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return cb(null);\n cb(e ? fixed(e, from, to) : e, ...a);\n });\n };\n if (fs.promises && typeof fs.promises.rename === \"function\") {\n const prename = fs.promises.rename;\n fs.promises.rename = async function(from, to) {\n if (isLink(from) && moveLink(from, to))\n return;\n try {\n return await prename.call(fs.promises, from, to);\n } catch (e) {\n if (e && e.code === \"ENOENT\" && moveLink(from, to))\n return;\n throw fixed(e, from, to);\n }\n };\n }\n }\n const tz = process.env && process.env.TZ;\n if (typeof utcClock2 === \"function\" && utcNames.includes(String(tz == null ? \"\" : tz).trim()))\n utcClock2(g);\n}\nvar SHIM_POST;\nvar init_shim_post = __esm(() => {\n init_tz();\n init_shim();\n 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`;\n});\n\n// src/edge/own/adapter.js\nvar exports_adapter = {};\n__export(exports_adapter, {\n exit: () => exit,\n fsCacheOf: () => fsCacheOf,\n fscacheRunOption: () => fscacheRunOption,\n keep: () => keep,\n load: () => load,\n name: () => name,\n prepare: () => prepare,\n release: () => release,\n setDeps: () => setDeps,\n signal: () => signal,\n start: () => start,\n stats: () => stats,\n teardown: () => teardown\n});\nfunction fsCacheOf(env) {\n const v = env && env.WMD_FSCACHE;\n return typeof v === \"string\" && /^[0-7]$/.test(v) ? Number(v) : undefined;\n}\nfunction fscacheRunOption(own, env) {\n if (own && own.fscache === false)\n return 0;\n return fsCacheOf(env);\n}\nfunction runtimeFile(text) {\n const e = new Error(text);\n e.runtimeFiles = true;\n return e;\n}\nasync function fetchOk(url) {\n let r;\n try {\n r = await deps.fetch(url);\n } catch (e) {\n throw runtimeFile(`${absUrl(url)} could not be fetched: ${whyOf(e)}`);\n }\n if (r.ok === false) {\n const e = new Error(`${r.url || url} answered ${r.status}${r.statusText ? \" \" + r.statusText : \"\"}`);\n e.runtimeFiles = true;\n throw e;\n }\n return r;\n}\nasync function readFile(url, as) {\n const r = await fetchOk(url);\n try {\n return as === \"text\" ? await r.text() : new Uint8Array(await r.arrayBuffer());\n } catch (e) {\n throw runtimeFile(`${r.url || absUrl(url)} could not be read: ${whyOf(e)}`);\n }\n}\nfunction setDeps(d) {\n deps = { ...deps, ...d };\n}\n\nclass Pipe {\n #chunks = [];\n #waiters = [];\n #done = false;\n bytes = 0;\n late = 0;\n taken = 0;\n push(b) {\n if (!b.length)\n return;\n this.bytes += b.length;\n if (this.#done)\n this.late += b.length;\n if (this.#waiters.length)\n this.#waiters.shift()(b);\n else\n this.#chunks.push(b);\n }\n end() {\n this.#done = true;\n for (const w of this.#waiters.splice(0))\n w(null);\n }\n async read(n) {\n if (this.#chunks.length)\n return this.#take(n);\n if (this.#done)\n return null;\n const b = await new Promise((r) => this.#waiters.push(r));\n if (b === null)\n return null;\n this.#chunks.unshift(b);\n return this.#take(n);\n }\n #take(n) {\n const c = this.#chunks[0];\n if (c.length <= n) {\n this.taken += c.length;\n return this.#chunks.shift();\n }\n this.#chunks[0] = c.subarray(n);\n this.taken += n;\n return c.subarray(0, n);\n }\n}\nfunction portRoute(p) {\n let next = 1;\n const pending = new Map;\n p.onmessage = (e) => {\n const m = e.data;\n const w = m && pending.get(m.id);\n if (!w)\n return;\n pending.delete(m.id);\n w(m.reply);\n };\n const route = {\n queueSignal: (id, n) => {\n route.handle(\"sigq\", [id, n], new Uint8Array(0));\n },\n handle: (method, args, data) => new Promise((resolve) => {\n const id = next++;\n pending.set(id, resolve);\n p.postMessage(globalThis.__wmdFsTime ? { own: \"fs\", id, method, args, data, t0: performance.timeOrigin + performance.now() } : { own: \"fs\", id, method, args, data });\n }),\n close: () => {\n try {\n p.postMessage({ own: \"bye\" });\n } catch {}\n for (const w of pending.values())\n w({ error: { code: \"EIO\", message: \"the file route closed\" } });\n pending.clear();\n }\n };\n return route;\n}\nasync function checkFiles(own, files) {\n const base = own.wasmUrl.replace(/[^/?#]*([?#].*)?$/, \"\");\n let text = null;\n try {\n const r = await deps.fetch(own.hashesUrl || base + \"HASHES.txt\");\n if (r.ok !== false)\n text = await r.text();\n } catch {}\n if (text === null) {\n files.missing++;\n return {};\n }\n const want = new Map;\n for (const line of String(text).split(`\n`)) {\n const [hash, size, name2] = line.trim().split(/\\s+/);\n if (name2 && /^[0-9a-f]{64}$/.test(hash))\n want.set(name2, { hash, size: Number(size) });\n }\n const out = {};\n for (const [key, name2] of [[\"wasmUrl\", \"wmd_browser_bg.wasm\"], [\"glueUrl\", \"wmd_browser.js\"]]) {\n const w = want.get(name2);\n if (!w) {\n files.unlisted++;\n continue;\n }\n const bytes = await readFile(own[key], \"bytes\");\n files.checked++;\n if (bytes.length !== w.size || await sha256(bytes) !== w.hash) {\n files.mismatch++;\n throw runtimeFile(`the runtime's files do not match HASHES.txt: ${name2} at ${absUrl(own[key])} (size ${bytes.length}, listed ${w.size}); not run`);\n }\n files.ok++;\n if (key === \"wasmUrl\") {\n mark(\"rtc0\");\n try {\n out.module = await deps.compile(bytes);\n } catch (e) {\n throw runtimeFile(`${absUrl(own[key])} did not compile as WebAssembly: ${whyOf(e)}`);\n }\n mark(\"rtc1\");\n }\n }\n return out;\n}\nfunction keep() {\n const k = state && state.keep;\n return k && (k.rtModule || k.prog) ? { ...k, texts: { ...k.texts } } : null;\n}\nasync function runtimeModule(own) {\n const k = state.kept;\n if (k && k.rtModule) {\n state.module = k.rtModule;\n state.files.kept = 1;\n state.keep.rtModule = k.rtModule;\n mark(\"checked\");\n return;\n }\n const tc = performance.now();\n const ok = await checkFiles(own, state.files);\n state.stages.check = performance.now() - tc;\n mark(\"checked\");\n state.module = ok.module;\n if (state.keep && ok.module)\n state.keep.rtModule = ok.module;\n}\nasync function programOf(module, memoryMaxMiB) {\n const s = state;\n let ready = s.kept && s.kept.prog && s.kept.prog.url === module ? s.kept.prog : null;\n let program = null;\n if (ready) {\n s.stages.keptProgram = 1;\n } else {\n program = await readFile(module, \"bytes\");\n if (s.keep && deps.OwnRuntime.prepare) {\n try {\n ready = { ...await deps.OwnRuntime.prepare(program, memoryMaxMiB ? { memoryMaxMiB } : undefined), url: module };\n } catch (e) {\n throw runtimeFile(`${absUrl(module)} is not a node program the runtime can compile: ${whyOf(e)}`);\n }\n program = null;\n }\n }\n if (s.keep && ready)\n s.keep.prog = ready;\n return { program, ready };\n}\nasync function linuxText(src) {\n const s = state;\n let raw = s.keep && s.keep.texts[src];\n if (typeof raw !== \"string\") {\n raw = await readFile(src, \"text\");\n try {\n shimSource(raw, {}, { symlinks: false });\n } catch (e) {\n throw runtimeFile(`${absUrl(src)} is not the settings file: ${whyOf(e)}`);\n }\n }\n if (s.keep)\n s.keep.texts[src] = raw;\n return raw;\n}\nfunction newState(own, kept, more) {\n const k = keptFor(own, kept);\n state = { own, out: new Pipe, err: new Pipe, t0: performance.now(), signals: [], files: { checked: 0, ok: 0, mismatch: 0, missing: 0, unlisted: 0 }, module: undefined, stages: {}, marks: own.marks ? { ...globalThis.__wmdFwMarks || {} } : null, ...more };\n state.kept = k;\n state.keep = own.keepMods !== false ? { wasmUrl: own.wasmUrl, glueUrl: own.glueUrl, rtModule: null, prog: null, texts: { ...k ? k.texts : {} } } : null;\n mark(\"load0\");\n}\nasync function load({ cfg, ports, log, onWorkerError, kept = null }) {\n const own = cfg.own || {};\n if (!own.wasmUrl || !own.glueUrl || !own.workerUrl)\n throw new Error(\"rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl\");\n if (own.fsTime)\n globalThis.__wmdFsTime = true;\n port = ports[0];\n route = portRoute(port);\n newState(own, kept, { log, onWorkerError });\n await runtimeModule(own);\n return {};\n}\nasync function prepare({ cfg, kept = null }) {\n const own = cfg.own || {};\n if (!own.wasmUrl || !own.glueUrl || !own.workerUrl)\n throw new Error(\"rt=own: cfg.own needs wasmUrl, glueUrl and workerUrl\");\n if (own.keepMods === false)\n return { kept: false };\n newState(own, kept, {});\n await runtimeModule(own);\n await programOf(cfg.edgeWasm || \"/wasm/edgejs.wasm\", cfg.memoryMaxMiB);\n if (cfg.linux)\n await linuxText(cfg.linuxSrc || \"/wasm/linux.cjs\");\n return { kept: true, stages: { ...state.stages }, files: { ...state.files } };\n}\nasync function pythonShimText(src, linux) {\n const s = state;\n let raw = s.keep && s.keep.texts[src];\n if (typeof raw !== \"string\")\n raw = await readFile(src, \"text\");\n if (s.keep)\n s.keep.texts[src] = raw;\n const marker = '_cfg = {\"execPath\": \"\", \"arch\": \"\", \"hostname\": \"\", \"cpus\": 0, \"uid\": 0, \"gid\": 0} #__WMD_EDGE_CONFIG__#';\n if (!raw.includes(marker))\n throw runtimeFile(`${absUrl(src)} is not the python settings file`);\n const cfg = { execPath: linux.execPath, arch: linux.arch || \"arm64\", hostname: linux.hostname || \"wmd-web\", cpus: linux.cpus || 1, uid: linux.uid | 0, gid: linux.gid | 0 };\n return raw.replace(marker, () => `_cfg = (lambda true, false, null: ${JSON.stringify(cfg)})(True, False, None)`);\n}\nasync function start({ module, argv, env, cwd, files = {}, linux, linuxSrc, stdin = \"closed\", python }) {\n const s = state;\n let tm = performance.now();\n const lap = (name2) => {\n const now = performance.now();\n s.stages[name2] = now - tm;\n tm = now;\n };\n mark(\"start0\");\n const { program, ready } = await programOf(module, python && python.maxMiB);\n lap(\"program\");\n mark(\"program\");\n let args = argv;\n const shim = { ...files };\n if (python) {\n shim[\"startup.py\"] = await pythonShimText(linuxSrc || \"/wasm/linux.py\", linux || {});\n } else if (linux) {\n const text = shimSource(await linuxText(linuxSrc || \"/wasm/linux.cjs\"), linux, { symlinks: false }) + SHIM_POST;\n shim[\"linux.cjs\"] = text;\n args = [\"--require\", SHIM_PATH, ...argv];\n }\n await route.handle(\"shim\", [shim], new Uint8Array(0));\n lap(\"shim\");\n mark(\"shim\");\n if (globalThis.__wmdFsTime)\n await route.handle(\"timing\", [\"on\"], new Uint8Array(0));\n rt = await deps.OwnRuntime.start({\n wasmUrl: s.own.wasmUrl,\n ...s.module ? { module: s.module } : {},\n glueUrl: s.own.glueUrl,\n workerUrl: s.own.workerUrl,\n fsRoute: route,\n ...python && python.maxMiB ? { memoryMaxMiB: python.maxMiB } : {},\n marks: s.own.marks === 2 ? 2 : !!s.marks,\n onOut: (fd, b) => {\n if (s.stages.firstOut === undefined && b.length && s.runT0)\n s.stages.firstOut = performance.now() - s.runT0, mark(\"firstOut\");\n (fd === 2 ? s.err : s.out).push(b);\n },\n onLog: (d) => s.log?.(typeof d === \"string\" ? d : JSON.stringify(d)),\n stack: s.own.stack,\n ...s.own.trace ? { trace: s.own.trace | 0 } : {},\n nodeGlobals: NODE_GLOBALS\n });\n lap(\"boot\");\n mark(\"booted\");\n s.runT0 = performance.now();\n mark(\"runPost\");\n const envList = Object.entries({ HOME: \"/root\", ...env || {} }).map(([k, v]) => `${k}=${v}`);\n runP = rt.run({ program, ...ready ? { ready } : {}, args, env: envList, node: !python, cwd, stdin: stdin === \"pipe\" ? \"pipe\" : \"null\", tty: {}, children: s.own.children !== false, net: s.own.net !== false, exec: linux && linux.execPath, shim: !!linux && !python, ...python ? { argv0: python.argv0 } : {}, ...fscacheRunOption(s.own, env) !== undefined ? { fscache: fscacheRunOption(s.own, env) } : {} }).then((r) => (r.code & ~127) === 16384 ? { exitCode: 128 + (r.code & 127), reason: \"exit\", signal: r.code & 127 } : { exitCode: r.code, reason: \"exit\" }, (e) => ({ exitCode: 1, reason: \"error: \" + String(e && e.message || e) })).then((r) => (mark(\"exitRecv\"), s.stages.run = performance.now() - s.runT0, s.out.end(), s.err.end(), r));\n return {\n readStdout: (n) => s.out.read(n),\n readStderr: (n) => s.err.read(n),\n writeStdin: async (bytes) => rt.writeStdin(bytes),\n closeStdin: async () => rt.closeStdin()\n };\n}\nasync function signal(proc, n) {\n if (n === 9)\n return rt?.terminate();\n return rt?.signal ? rt.signal(n) : undefined;\n}\nasync function exit() {\n const r = await runP;\n if (globalThis.__wmdFsTime && rt) {\n try {\n const t = (await route.handle(\"timing\", [\"read\"], new Uint8Array(0))).value;\n for (const [side, v] of [[\"hub\", rt.fsTiming], [\"route\", t]]) {\n const j = JSON.stringify(v);\n for (let i = 0;i < j.length; i += 140)\n await route.handle(\"note\", [`FSTAT ${side} ${i / 140} ` + j.slice(i, i + 140)], new Uint8Array(0));\n }\n } catch {}\n }\n return r;\n}\nasync function teardown() {\n rt?.terminate();\n}\nfunction release() {\n rt?.terminate();\n route?.close?.();\n return rt ? 1 : 0;\n}\nasync function stats() {\n let wasm = null;\n try {\n const mine = globalThis.__wmdWasmCounters ? globalThis.__wmdWasmCounters.snapshot() : null;\n let theirs = [];\n if (rt && state && state.own.counts) {\n const tc = performance.now();\n theirs = await rt.collectCounts(400);\n state.stages.counts = performance.now() - tc;\n }\n let sum = mine;\n for (const t of theirs)\n sum = addCounts(sum, t.c);\n if (sum)\n wasm = { ...sum, workers: theirs.length };\n if (wasm)\n wasm.kinds = [...globalThis.__wmdWasmCounters?.kinds?.() || [], ...theirs.flatMap((t) => t.c && t.c.kinds || [])];\n } catch {}\n let marks = null;\n if (state && state.marks) {\n const rm = rt && rt.marks || { first: {}, n: {} };\n const all = { ...rm.first, ...state.marks };\n for (const [k, v] of Object.entries(stagesOf(all)))\n state.stages[\"m.\" + k] = v;\n const base = state.marks.frame ?? state.marks.load0;\n marks = { t: Object.fromEntries(Object.entries(all).map(([k, v]) => [k, Math.round((v - base) * 10) / 10])), n: { ...rm.n }, ...rm.fs ? { fs: rm.fs } : {}, ...rm.series && Object.keys(rm.series).length ? { series: Object.fromEntries(Object.entries(rm.series).map(([k, v]) => [k, v.map((x) => Math.round((x - base) * 10) / 10)])) } : {}, ...rm.memMiB ? { memMiB: rm.memMiB } : {}, ...rm.calls ? { calls: rm.calls } : {} };\n }\n return {\n ...marks ? { marks } : {},\n service: null,\n frameRtt: null,\n ...wasm ? { wasm } : {},\n ...rt?.capiStats ? { capi: rt.capiStats } : {},\n ...rt && rt.forged ? { forged: rt.forged } : {},\n ...state ? { files: { ...state.files }, stages: { ...state.stages }, pipes: { out: state.out.bytes, err: state.err.bytes, lateOut: state.out.late, lateErr: state.err.late, unreadOut: state.out.bytes - state.out.taken, unreadErr: state.err.bytes - state.err.taken } } : {}\n };\n}\nvar name = \"own\", absUrl = (url) => {\n try {\n return new URL(url, globalThis.location && globalThis.location.href).href;\n } catch {\n return url;\n }\n}, whyOf = (e) => String(e && e.message || e).split(`\n`)[0], SHIM_PATH = \"/.wmd-edge/linux.cjs\", deps, rt = null, port = null, route = null, runP = null, state = null, mark = (name2) => {\n if (state && state.marks && state.marks[name2] === undefined)\n state.marks[name2] = at();\n}, sha256 = async (u8) => Array.from(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", u8)), (b) => b.toString(16).padStart(2, \"0\")).join(\"\"), keptFor = (own, kept) => own.keepMods !== false && kept && kept.wasmUrl === own.wasmUrl && kept.glueUrl === own.glueUrl ? kept : null;\nvar init_adapter = __esm(() => {\n init_marks();\n init_hub();\n init_node_globals();\n init_shim();\n init_shim_post();\n deps = { OwnRuntime, fetch: (...a) => fetch(...a), compile: (b) => WebAssembly.compile(b) };\n});\n\n// src/edge/hist.js\nclass Hist {\n constructor() {\n this.n = 0;\n this.sumUs = 0;\n this.maxUs = 0;\n this.neg = 0;\n this.b = new Array(LOG2_BUCKETS).fill(0);\n }\n add(us) {\n if (us < 0) {\n this.neg++;\n us = 0;\n }\n this.n++;\n this.sumUs += us;\n if (us > this.maxUs)\n this.maxUs = us;\n const b = us < 1 ? 0 : Math.min(LOG2_BUCKETS - 1, Math.floor(Math.log2(us)) + 1);\n this.b[b]++;\n }\n quantileUs(q) {\n if (!this.n)\n return 0;\n const want = Math.ceil(this.n * q);\n let c = 0;\n for (let i = 0;i < this.b.length; i++) {\n c += this.b[i];\n if (c >= want)\n return i === 0 ? 1 : 2 ** i;\n }\n return this.maxUs;\n }\n summary() {\n return {\n n: this.n,\n meanUs: this.n ? +(this.sumUs / this.n).toFixed(1) : 0,\n maxUs: +this.maxUs.toFixed(1),\n neg: this.neg,\n p50Us: this.quantileUs(0.5),\n p90Us: this.quantileUs(0.9),\n p99Us: this.quantileUs(0.99),\n buckets: this.b.slice()\n };\n }\n}\nvar LOG2_BUCKETS = 24;\n\n// src/edge/sdk/forward.js\nclass Forwarder {\n constructor(port, respond) {\n this.port = port;\n this.respond = respond;\n this.pending = new Map;\n this.next = 1;\n this.rtt = {};\n this.stat = new Map;\n port.onmessage = ({ data: m }) => this.#reply(m);\n }\n send(m) {\n const id = this.next++;\n const t0 = performance.now();\n this.pending.set(id, { request: m, t0, method: m.method });\n this.port.postMessage({ id, mount: m.mount, method: m.method, args: m.args, t0: performance.timeOrigin + t0 });\n }\n #reply(m) {\n if (m.stats !== undefined || m.reset || m.plan) {\n const r = this.stat.get(m.id);\n this.stat.delete(m.id);\n if (r)\n r(m);\n return;\n }\n const p = this.pending.get(m.id);\n if (!p)\n return;\n this.pending.delete(m.id);\n (this.rtt[p.method] ||= new Hist).add((performance.now() - p.t0) * 1000);\n this.respond(p.request, m.res);\n }\n stats() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, (m) => res(m.stats));\n this.port.postMessage({ id, op: \"stats\" });\n });\n }\n plan() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, (m) => res(m.plan));\n this.port.postMessage({ id, op: \"plan\" });\n });\n }\n reset() {\n return new Promise((res) => {\n const id = this.next++;\n this.stat.set(id, () => res());\n this.port.postMessage({ id, op: \"reset\" });\n this.rtt = {};\n });\n }\n rttSummary() {\n return Object.fromEntries(Object.entries(this.rtt).map(([k, h]) => [k, h.summary()]));\n }\n}\nvar init_forward = () => {};\n\n// src/edge/workers.js\nfunction workerRegistry() {\n const made = new Set;\n return {\n track(w) {\n made.add(w);\n return w;\n },\n release() {\n const n = made.size;\n for (const w of [...made]) {\n made.delete(w);\n try {\n w.terminate();\n } catch {}\n }\n return n;\n },\n size: () => made.size\n };\n}\n\n// src/edge/spawn-guard.js\nfunction newSpawnMark() {\n const b = crypto.getRandomValues(new Uint8Array(6));\n return `${SPAWN_MARK.slice(0, -2)} [${Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\")}]: `;\n}\nfunction markScanner(mark) {\n let carry = \"\";\n let line = null;\n let done = false;\n return {\n push(text) {\n if (done)\n return;\n if (line === null) {\n const all = carry + text;\n const at = all.indexOf(mark);\n if (at < 0) {\n carry = all.slice(Math.max(0, all.length - (mark.length - 1)));\n return;\n }\n line = all.slice(at + mark.length);\n carry = \"\";\n } else\n line += text;\n const nl = line.indexOf(`\n`);\n if (nl < 0)\n return;\n done = true;\n return line.slice(0, nl);\n },\n finish: () => !done && line !== null ? (done = true, line) : undefined\n };\n}\nfunction spawnGuard(req, proc, mark, code) {\n const cp = req(\"child_process\");\n const fs = req(\"fs\");\n let refused = false;\n const refuse = (name, cmd) => {\n if (refused)\n throw new Error(\"spawn refused\");\n refused = true;\n const c = String(cmd == null ? \"\" : cmd).replace(/\\s+/g, \" \").slice(0, 200);\n 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`;\n try {\n fs.writeSync(2, text);\n } catch {}\n proc.exit(code);\n throw new Error(\"spawn refused: \" + c);\n };\n for (const name of [\"spawn\", \"spawnSync\", \"exec\", \"execSync\", \"execFile\", \"execFileSync\", \"fork\"]) {\n if (typeof cp[name] === \"function\")\n cp[name] = function(cmd) {\n return refuse(name, cmd);\n };\n }\n}\nfunction withSpawnGuard(src, mark = SPAWN_MARK) {\n return src + `\n;(${spawnGuard})(require, process, ${JSON.stringify(mark)}, ${SPAWN_EXIT});\n`;\n}\nvar SPAWN_MARK = \"wmd: spawn refused: \", SPAWN_EXIT = 126;\n\n// src/edge/sdk/adapter.js\nvar exports_adapter2 = {};\n__export(exports_adapter2, {\n exit: () => exit2,\n liveWorkers: () => liveWorkers,\n load: () => load2,\n name: () => name2,\n release: () => release2,\n signal: () => signal2,\n start: () => start2,\n stats: () => stats2,\n teardown: () => teardown2\n});\nfunction wrapWorkers(onWorkerError) {\n if (RealWorker)\n return;\n RealWorker = globalThis.Worker;\n globalThis.Worker = class extends RealWorker {\n constructor(...a) {\n super(...a);\n workers.track(this);\n this.addEventListener(\"message\", (e) => {\n const m = e.data;\n if (m && m.type === HOST_FS_MESSAGE && m.response && fwd) {\n e.stopImmediatePropagation();\n fwd.send(m);\n }\n });\n this.addEventListener(\"error\", (e) => onWorkerError?.(String(e && e.message || \"a Worker failed to load or crashed\")));\n }\n };\n}\nasync function load2({ cfg, ports, log, onWorkerError }) {\n baseUrl = cfg.rtBase || \"/sdk/\";\n wrapWorkers(onWorkerError);\n const t0 = performance.now();\n const hf = await import(baseUrl + \"dist/host-filesystem.js\");\n fwd = new Forwarder(ports[0], hf.respondToHostFileSystem);\n relay = workers.track(new RealWorker(\"/edge/sdk/relay.js\", { type: \"module\" }));\n relay.addEventListener(\"error\", (e) => onWorkerError?.(\"the relay Worker failed: \" + String(e && e.message || \"\")));\n await new Promise((r) => {\n relay.onmessage = () => r();\n relay.postMessage({ port: ports[1] }, [ports[1]]);\n });\n hf.installHostFileSystemWorkerBridge((msg) => (relay.postMessage(msg), true));\n const plan = await fwd.plan();\n if (plan.oversize.length)\n return { fallback: { reason: \"listing-too-large\", oversize: plan.oversize.slice(0, 20) } };\n const { Wasmer } = await import(baseUrl + \"dist/index.js\");\n wasmer = new Wasmer({ cache: \"memory\", parallelism: cfg.parallelism || 2 });\n core = await wasmer.getCore();\n log(\"sdk loaded after \" + (performance.now() - t0).toFixed(0) + \" ms\");\n return {};\n}\nasync function start2({ module, argv, env, cwd, mounts, files = {}, linux, linuxSrc, stdin = \"closed\", timeoutMs, parallelism, spawnMark }) {\n const edge = new Uint8Array(await (await fetch(module)).arrayBuffer());\n const fileBytes = Object.fromEntries(Object.entries(files).map(([p, t]) => [p, enc3.encode(t)]));\n let args = argv;\n if (linux) {\n const shim = \"/.wmd-edge/linux.cjs\";\n const src = await (await fetch(linuxSrc || \"/wasm/linux.cjs\")).text();\n const text = shimSource(src, linux);\n fileBytes[shim] = enc3.encode(withSpawnGuard(linux.utc ? withUtcClock(text) : text, spawnMark));\n args = [\"--require\", shim, ...args];\n }\n pkg = await core.createPackage({ modules: { node: edge }, commands: { node: { module: \"node\" } }, files: fileBytes });\n const b = core.sandbox();\n b.package(pkg);\n b.env(\"HOME\", \"/root\");\n for (const [k, v] of Object.entries(env || {}))\n b.env(k, v);\n b.network(\"disabled\");\n for (const [path, id, ro] of mounts)\n b.mountHost(path, id, ro);\n sb = await b.start();\n await fwd.reset();\n const cmd = sb.commandPackage(pkg);\n cmd.args(args);\n if (cwd)\n cmd.currentDir(cwd);\n cmd.timeoutMs(timeoutMs || 2147483647);\n cmd.stdinMode(stdin);\n cmd.stdoutMode(\"pipe\");\n cmd.stderrMode(\"pipe\");\n const pr = await cmd.spawn();\n return {\n pr,\n readStdout: (n) => pr.readStdout(n),\n readStderr: (n) => pr.readStderr(n),\n writeStdin: (bytes) => pr.writeStdin(bytes),\n closeStdin: () => pr.closeStdin()\n };\n}\nasync function signal2(proc, n) {\n if (n === 9)\n return proc.pr.kill();\n return proc.pr.terminate(2000);\n}\nasync function exit2(proc) {\n const w = await proc.pr.wait();\n return { exitCode: w.exitCode, reason: w.reason };\n}\nasync function teardown2() {\n try {\n await sb?.close();\n } finally {\n await wasmer?.close();\n }\n}\nfunction release2() {\n return workers.release();\n}\nasync function stats2() {\n return { service: fwd ? await fwd.stats() : null, frameRtt: fwd ? fwd.rttSummary() : null };\n}\nvar name2 = \"sdk\", HOST_FS_MESSAGE = \"wasmer-filesystem-rpc\", enc3, fwd = null, relay = null, wasmer = null, sb = null, pkg = null, core = null, baseUrl = \"/sdk/\", RealWorker = null, workers, liveWorkers = () => workers.size();\nvar init_adapter2 = __esm(() => {\n init_forward();\n init_shim();\n init_tz();\n enc3 = new TextEncoder;\n workers = workerRegistry();\n});\n\n// src/edge/sbx/worker-entry.js\ninit_hub();\ninit_adapter();\n\n// src/edge/runtime.js\nvar LOADERS = {\n own: () => Promise.resolve().then(() => (init_adapter(), exports_adapter)),\n sdk: null\n};\nvar RT_DEFAULT = \"own\";\nvar RT_NAMES = () => Object.keys(LOADERS);\nfunction handSdk(base) {\n if (typeof base !== \"string\" || !base.startsWith(\"/\") || !base.endsWith(\"/\"))\n throw new Error(\"sdkBase must be a path that starts and ends with '/'\");\n LOADERS.sdk = () => Promise.resolve().then(() => (init_adapter2(), exports_adapter2));\n return { rtBase: base };\n}\nfunction unavailable(rt) {\n if (!Object.hasOwn(LOADERS, rt))\n return `rt=${rt}: no such runtime (rt=${RT_NAMES().join(\"|\")})`;\n if (!LOADERS[rt])\n return rt === \"sdk\" ? \"rt=sdk: no SDK was handed in (the page option sdkBase), it is not in this build, node runs in the guest\" : `rt=${rt}: the runtime is not in this build, node runs in the guest`;\n return \"\";\n}\nasync function loadAdapter(rt, cfg = null) {\n if (rt === \"sdk\" && !LOADERS.sdk && cfg && typeof cfg.rtBase === \"string\") {\n try {\n handSdk(cfg.rtBase);\n } catch {}\n }\n const why = unavailable(rt);\n if (why)\n throw new Error(why);\n return LOADERS[rt]();\n}\n\n// src/edge/error-kind.js\nvar errorKindOf = (e, loading) => loading || e && e.runtimeFiles === true ? \"runtime\" : undefined;\nvar ERROR_KINDS = new Set([\"runtime\"]);\n\n// src/edge/worker.js\ninstallWasmCounters(globalThis);\nvar log = (text) => postMessage({ type: \"log\", text });\nvar errorText = (e) => {\n const stack = e && e.stack ? String(e.stack) : \"\";\n const msg = e && e.message !== undefined ? `${e.name || \"Error\"}: ${e.message}` : \"\";\n if (!msg)\n return stack || String(e);\n return stack.startsWith(msg) ? stack : stack ? msg + `\n` + stack : msg;\n};\nvar dec2 = new TextDecoder;\nvar enc4 = new TextEncoder;\nvar adapter = null;\nvar finished = false;\nvar done = (d) => {\n if (finished)\n return;\n finished = true;\n postMessage({ type: \"done\", ...d });\n};\nvar proc = null;\nvar early = [];\nasync function input(m) {\n if (!proc)\n return early.push(m);\n if (m.stdin)\n await proc.writeStdin(m.stdin);\n else if (m.stdinEnd)\n await proc.closeStdin();\n else if (m.signal)\n await adapter.signal(proc, m.signal);\n}\nonmessage = async ({ data: { cfg, ports, in: inp, tf, kept, prepare } }) => {\n if (inp)\n return input(inp);\n if (prepare) {\n try {\n const t0 = performance.now();\n adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg);\n const r = adapter.prepare ? await adapter.prepare({ cfg, kept }) : { kept: false };\n const k = adapter.keep ? adapter.keep() : null;\n if (k)\n postMessage({ type: \"keep\", keep: k });\n return done({ prepared: !!k, prepareMs: Math.round(performance.now() - t0), ...r.stages ? { stages: r.stages } : {} });\n } catch (e) {\n const kind = errorKindOf(e, false);\n return done({ error: String(e && e.message || e).slice(0, 300), ...kind ? { errorKind: kind } : {} });\n }\n }\n if (typeof tf === \"number\")\n globalThis.__wmdFwMarks = { frame: tf, fw: performance.timeOrigin + performance.now() };\n const res = {};\n let loading = true;\n try {\n const t0 = performance.now();\n adapter = await loadAdapter(cfg.rt || RT_DEFAULT, cfg);\n const loaded = await adapter.load({\n cfg,\n ports,\n kept,\n log,\n onWorkerError: (why) => done({ error: \"the runtime lost a Worker: \" + why })\n });\n loading = false;\n if (loaded.fallback)\n return done({ fallback: true, ...loaded.fallback });\n const spawnMark = newSpawnMark();\n proc = await adapter.start({\n spawnMark,\n module: cfg.edgeWasm,\n argv: cfg.args,\n env: cfg.env,\n cwd: cfg.cwd,\n mounts: cfg.mounts,\n files: cfg.files,\n linux: cfg.linux,\n linuxSrc: cfg.linuxSrc,\n python: cfg.python,\n stdin: cfg.stdin || \"closed\",\n timeoutMs: cfg.timeoutMs,\n parallelism: cfg.parallelism\n });\n res.setupMs = performance.now() - t0;\n const k = adapter.keep ? adapter.keep() : null;\n if (k)\n postMessage({ type: \"keep\", keep: k });\n log(\"process started after \" + res.setupMs.toFixed(0) + \" ms\");\n const t1 = performance.now();\n postMessage({ type: \"step\", name: \"ready\", ms: res.setupMs });\n for (const m of early.splice(0))\n await input(m);\n const outs = [];\n const errs = [];\n let spawnRefused;\n const scanner = markScanner(spawnMark);\n const sdec = new TextDecoder;\n const sent = res.outBytes = { stdout: 0, stderr: 0 };\n const pump = async (read, into, kind) => {\n for (let n = 0;n < 1e6; n++) {\n const b = await read(65536);\n if (b == null)\n return;\n if (!b.length)\n continue;\n sent[kind] += b.length;\n if (kind === \"stderr\" && spawnRefused === undefined)\n spawnRefused = scanner.push(sdec.decode(b, { stream: true }));\n if (cfg.stream) {\n const c = b.slice();\n postMessage({ type: \"out\", kind, bytes: c }, [c.buffer]);\n } else\n into.push(b);\n }\n };\n if (cfg.stdinBytes)\n await proc.writeStdin(enc4.encode(cfg.stdinBytes));\n if (cfg.stdinBytes && cfg.stdin === \"pipe\")\n await proc.closeStdin();\n await Promise.all([pump(proc.readStdout, outs, \"stdout\"), pump(proc.readStderr, errs, \"stderr\")]);\n const w = await adapter.exit(proc);\n const join = (chunks) => {\n const all = new Uint8Array(chunks.reduce((a, c) => a + c.length, 0));\n let at = 0;\n for (const c of chunks)\n all.set(c, at), at += c.length;\n return all;\n };\n if (spawnRefused === undefined)\n spawnRefused = scanner.finish();\n res.runMs = performance.now() - t1;\n res.exitCode = w.exitCode;\n if (spawnRefused !== undefined && w.exitCode === SPAWN_EXIT)\n res.spawnRefused = spawnRefused;\n res.reason = w.reason;\n res.stdout = dec2.decode(join(outs)).slice(-8000);\n res.stderr = dec2.decode(join(errs)).slice(-8000);\n Object.assign(res, await adapter.stats());\n } catch (e) {\n res.error = errorText(e);\n const kind = errorKindOf(e, loading);\n if (kind)\n res.errorKind = kind;\n }\n done(res);\n};\n\n// src/edge/sbx/common.js\nvar b64 = (text) => {\n const bytes = new TextEncoder().encode(text);\n let s = \"\";\n for (let i = 0;i < bytes.length; i += 32768)\n s += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));\n return btoa(s);\n};\nvar dataUrl = (text) => \"data:text/javascript;base64,\" + b64(text).replace(/\\//g, \"%2F\");\nvar blobUrl = (text) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\nvar bootSrc = (url) => `var q = []; var h = function (e) { q.push(e) }; self.addEventListener(\"message\", h);\n` + \"import(\" + JSON.stringify(url) + `).then(function () { self.removeEventListener(\"message\", h); for (var i = 0; i < q.length; i++) self.dispatchEvent(new MessageEvent(\"message\", { data: q[i].data, ports: q[i].ports })) },\n` + ` function (e) { postMessage({ type: \"done\", error: \"the frame's Worker code did not load: \" + String(e && e.message || e) }) })`;\nvar SCRIPT_LOADER = 'onmessage = e => { const d = e.data; if (d && typeof d.__wmdScript === \"string\") { onmessage = null; (0, eval)(d.__wmdScript + \"\\\\n//# sourceURL=wmd-worker.js\") } }';\nvar SCRIPT_PREFIX = \"wmd-script:\";\nfunction makeFactory(name) {\n if (name === \"data\") {\n const scripts = new Map;\n const loader = \"data:text/javascript,\" + encodeURIComponent(SCRIPT_LOADER);\n return {\n name,\n url: dataUrl,\n script: (t) => {\n const n = SCRIPT_PREFIX + scripts.size;\n scripts.set(n, t);\n return n;\n },\n make: (u, o) => {\n const t = scripts.get(u);\n if (t === undefined)\n return new Worker(u, { name: o && o.name, type: \"module\" });\n const w = new Worker(loader, { name: o && o.name, type: \"module\" });\n w.postMessage({ __wmdScript: '\"use strict\";' + t });\n return w;\n }\n };\n }\n if (name === \"boot\")\n return { name, url: blobUrl, make: (u, o) => new Worker(blobUrl(bootSrc(u)), { name: o && o.name }) };\n return { name: \"module\", url: blobUrl, make: (u, o) => new Worker(u, { name: o && o.name, type: \"module\" }) };\n}\nfunction moduleToScript(src) {\n const names = [];\n let body = src.replace(/^export\\s+((?:async\\s+)?function\\s*\\*?\\s*([\\w$]+)|(?:class|const|let|var)\\s+([\\w$]+))/gm, (m, rest, fn, other) => (names.push(fn || other), rest));\n const lists = [];\n body = body.replace(/^export\\s*\\{([^}]*)\\}\\s*;?[ \\t]*$/gm, (m, l) => (lists.push(...asObject(l)), \"\"));\n if (lists.includes(null) || /^\\s*(import|export)\\b/m.test(body) || /^await\\b/m.test(body) || !names.length && !lists.length)\n return null;\n body = body.replace(/import\\.meta\\.url/g, '\"about:blank\"');\n return `(() => {\n'use strict';\n${body}\nreturn { ${[...names, ...lists].join(\", \")} }\n})()`;\n}\nvar ACORN_RE = /(from\\s*)(['\"])\\.\\.\\/\\.\\.\\/acorn\\/acorn\\.mjs\\2/g;\nvar SNIPPET_RE = /(from\\s*)(['\"])\\.\\/snippets\\/[^'\"]+\\/inline0\\.js\\2/g;\nvar SNIPPET_IMPORT_RE = /import\\s*(?:\\*\\s*as\\s+(\\w+)|\\{([^}]*)\\})\\s*from\\s*(['\"])\\.\\/snippets\\/[^'\"]+\\/inline0\\.js\\3/g;\nvar SNIPPET_NS = \"__wmdSnippet\";\nvar dec3 = new TextDecoder;\nvar text = (v) => typeof v === \"string\" ? v : dec3.decode(v);\nvar ACORN_EXPORT_RE = /^export\\s*\\{([^}]*)\\}\\s*;?\\s*$/m;\nvar ACORN_IMPORT_RE = /^import\\s*\\{([^}]*)\\}\\s*from\\s*(['\"])\\.\\.\\/\\.\\.\\/acorn\\/acorn\\.mjs\\2\\s*;?[ \\t]*$/m;\nvar asObject = (list) => list.split(\",\").map((x) => x.trim()).filter(Boolean).map((x) => {\n const m = /^([\\w$]+)\\s+as\\s+([\\w$]+)$/.exec(x);\n return m ? `${m[2]}: ${m[1]}` : /^[\\w$]+$/.test(x) ? x : null;\n});\nfunction acornExpr(src) {\n const m = ACORN_EXPORT_RE.exec(src);\n const rest = m && src.replace(ACORN_EXPORT_RE, \"\");\n if (!m || /^(import|export)\\b/m.test(rest))\n return null;\n const names = asObject(m[1]);\n return names.includes(null) ? null : `(() => {\n'use strict';\n${rest}\nreturn { ${names.join(\", \")} }\n})()`;\n}\nfunction snippetExpr(src, acornSrc) {\n const im = ACORN_IMPORT_RE.exec(src);\n const ac = im && acornExpr(acornSrc);\n if (!ac)\n return null;\n const pairs = im[1].split(\",\").map((x) => x.trim()).filter(Boolean).map((x) => {\n const k = /^([\\w$]+)\\s+as\\s+([\\w$]+)$/.exec(x);\n return k ? `${k[1]}: ${k[2]}` : /^[\\w$]+$/.test(x) ? x : null;\n });\n if (!pairs.length || pairs.includes(null))\n return null;\n let body = src.replace(ACORN_IMPORT_RE, `const { ${pairs.join(\", \")} } = __wmdAcorn;`);\n const names = [];\n body = body.replace(/^export\\s+((?:async\\s+)?function\\s*\\*?\\s*(\\w+)|(?:const|let|var|class)\\s+([\\w$]+))/gm, (m, rest, fn, other) => (names.push(fn || other), rest));\n if (/^(import|export)\\b/m.test(body) || !names.length)\n return null;\n return `(() => {\n'use strict';\nconst __wmdAcorn = ${ac};\n${body}\nreturn { ${names.join(\", \")} }\n})()`;\n}\nfunction urlsFor(factory, { glue, snippet, acorn, ownWorker }) {\n const expr = snippetExpr(text(snippet), text(acorn));\n let nested = null;\n if (!expr) {\n const acornU = factory.url(text(acorn));\n nested = factory.url(text(snippet).replace(ACORN_RE, (m, a, q) => a + q + acornU + q));\n }\n let first = true;\n const named = text(glue).replace(SNIPPET_IMPORT_RE, (m, star, braces, q) => {\n const head = first ? expr ? `const ${SNIPPET_NS} = ${expr}; ` : `import * as ${SNIPPET_NS} from ${q}${nested}${q}; ` : \"\";\n first = false;\n return head + (star ? `const ${star} = ${SNIPPET_NS}` : `const {${braces.replace(/\\s+as\\s+/g, \": \")}} = ${SNIPPET_NS}`);\n });\n const script = factory.script && expr ? moduleToScript(named) : null;\n if (script)\n return { glue: SCRIPT_PREFIX + \"glue\", glueScript: script, worker: factory.script(text(ownWorker)) };\n return { glue: factory.url(expr ? named : named.replace(SNIPPET_RE, (m, a, q) => a + q + nested + q)), worker: factory.url(text(ownWorker)) };\n}\n\n// src/edge/sbx/sha256.js\nvar K = new Int32Array([\n 1116352408,\n 1899447441,\n 3049323471,\n 3921009573,\n 961987163,\n 1508970993,\n 2453635748,\n 2870763221,\n 3624381080,\n 310598401,\n 607225278,\n 1426881987,\n 1925078388,\n 2162078206,\n 2614888103,\n 3248222580,\n 3835390401,\n 4022224774,\n 264347078,\n 604807628,\n 770255983,\n 1249150122,\n 1555081692,\n 1996064986,\n 2554220882,\n 2821834349,\n 2952996808,\n 3210313671,\n 3336571891,\n 3584528711,\n 113926993,\n 338241895,\n 666307205,\n 773529912,\n 1294757372,\n 1396182291,\n 1695183700,\n 1986661051,\n 2177026350,\n 2456956037,\n 2730485921,\n 2820302411,\n 3259730800,\n 3345764771,\n 3516065817,\n 3600352804,\n 4094571909,\n 275423344,\n 430227734,\n 506948616,\n 659060556,\n 883997877,\n 958139571,\n 1322822218,\n 1537002063,\n 1747873779,\n 1955562222,\n 2024104815,\n 2227730452,\n 2361852424,\n 2428436474,\n 2756734187,\n 3204031479,\n 3329325298\n]);\nfunction sha2562(data) {\n const n = data.length;\n const total = n + 9 + 63 >> 6 << 6;\n const tail = new Uint8Array(total - (n - n % 64));\n tail.set(data.subarray(n - n % 64));\n tail[n % 64] = 128;\n const dv = new DataView(tail.buffer);\n dv.setUint32(tail.length - 8, Math.floor(n / 536870912), false);\n dv.setUint32(tail.length - 4, n << 3 >>> 0, false);\n const h = new Int32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);\n const w = new Int32Array(64);\n const block = (b, o) => {\n for (let i = 0;i < 16; i++)\n w[i] = b[o + 4 * i] << 24 | b[o + 4 * i + 1] << 16 | b[o + 4 * i + 2] << 8 | b[o + 4 * i + 3];\n for (let i = 16;i < 64; i++) {\n const a = w[i - 15];\n const c = w[i - 2];\n const s0 = (a >>> 7 | a << 25) ^ (a >>> 18 | a << 14) ^ a >>> 3;\n const s1 = (c >>> 17 | c << 15) ^ (c >>> 19 | c << 13) ^ c >>> 10;\n w[i] = w[i - 16] + s0 + w[i - 7] + s1 | 0;\n }\n let a = h[0], b1 = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];\n for (let i = 0;i < 64; i++) {\n const t1 = hh + ((e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7)) + (e & f ^ ~e & g) + K[i] + w[i] | 0;\n const t2 = ((a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10)) + (a & b1 ^ a & c ^ b1 & c) | 0;\n hh = g;\n g = f;\n f = e;\n e = d + t1 | 0;\n d = c;\n c = b1;\n b1 = a;\n a = t1 + t2 | 0;\n }\n h[0] = h[0] + a | 0;\n h[1] = h[1] + b1 | 0;\n h[2] = h[2] + c | 0;\n h[3] = h[3] + d | 0;\n h[4] = h[4] + e | 0;\n h[5] = h[5] + f | 0;\n h[6] = h[6] + g | 0;\n h[7] = h[7] + hh | 0;\n };\n const whole = n - n % 64;\n for (let o = 0;o < whole; o += 64)\n block(data, o);\n for (let o = 0;o < tail.length; o += 64)\n block(tail, o);\n const out = new Uint8Array(32);\n const ov = new DataView(out.buffer);\n for (let i = 0;i < 8; i++)\n ov.setInt32(4 * i, h[i], false);\n return out;\n}\nfunction installDigestFallback(g = globalThis) {\n if (g.crypto && g.crypto.subtle)\n return false;\n const digest = async (alg, data) => {\n if (String(alg && alg.name ? alg.name : alg).toUpperCase() !== \"SHA-256\")\n throw new Error(\"only SHA-256 is available here\");\n const u = data instanceof ArrayBuffer || typeof SharedArrayBuffer === \"function\" && data instanceof SharedArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return sha2562(u).buffer;\n };\n const subtle = { digest };\n try {\n Object.defineProperty(g.crypto, \"subtle\", { value: subtle, configurable: true });\n } catch {\n return false;\n }\n return true;\n}\n\n// src/edge/sbx/worker-entry.js\ninstallDigestFallback(globalThis);\nvar real = globalThis.onmessage;\nvar dec4 = new TextDecoder;\nglobalThis.onmessage = (e) => {\n const d = e && e.data;\n if (d && d.x5sbx)\n setup(d.x5sbx);\n return real.call(globalThis, e);\n};\nfunction setup({ strategy, ownWorker, files }) {\n const mk = makeFactory(strategy);\n const urls = urlsFor(mk, { glue: files.glue, snippet: files.snippet, acorn: files.acorn, ownWorker });\n const name = (u) => String(u).replace(/^sbx:/, \"\");\n setDeps({\n fetch: async (u) => {\n const b = files[{ \"wmd_browser_bg.wasm\": \"wasm\", \"wmd_browser.js\": \"glue\", \"edgejs.wasm\": \"edgejs\", \"linux.cjs\": \"linux\", \"HASHES.txt\": \"hashes\", \"python-3.12.wasm\": \"python\", \"linux.py\": \"linuxpy\" }[name(u)]];\n if (!b)\n return { ok: false, status: 404, statusText: \"not handed in\", url: String(u) };\n return { ok: true, status: 200, url: String(u), arrayBuffer: async () => b, text: async () => dec4.decode(b) };\n },\n OwnRuntime: {\n start: (o) => OwnRuntime.start({ ...o, glueUrl: urls.glue, workerUrl: urls.worker, ...urls.glueScript ? { glueScript: urls.glueScript } : {}, create: mk.make, ...strategy === \"data\" && o.poolIdleMs === undefined ? { poolIdleMs: 1500 } : {} }),\n prepare: (...a) => OwnRuntime.prepare(...a)\n }\n });\n}\n"
|
|
5
|
+
const OWNWORKER = "// src/edge/own/loader.js\nfunction checkInit(m) {\n if (!m || m.type !== \"init\")\n throw new Error(\"not an init message\");\n if (typeof m.glue !== \"string\" || !m.glue)\n throw new Error(\"init: glue URL missing\");\n if (!m.module)\n throw new Error(\"init: compiled module missing\");\n if (m.role !== \"main\" && m.role !== \"thread\")\n throw new Error(`init: role must be main or thread, got ${m.role}`);\n if (m.role === \"thread\" && !m.memory)\n throw new Error(\"init: a thread Worker needs the shared memory\");\n return m;\n}\nvar hasJspi = () => typeof WebAssembly.promising === \"function\" && typeof WebAssembly.Suspending === \"function\";\nfunction makeTurn(now = () => performance.now(), channel = () => new MessageChannel, timer = setTimeout) {\n let last = 0;\n let idle = 0;\n let ch = null;\n return () => {\n const t = now();\n idle = t - last > 50 ? 0 : idle + 1;\n last = t;\n if (idle < 100) {\n ch ||= channel();\n return new Promise((r) => {\n ch.port1.onmessage = () => r();\n ch.port2.postMessage(0);\n });\n }\n return new Promise((r) => timer(r, 2));\n };\n}\nfunction suspendingImports(turn, run) {\n const wrap = (imports) => {\n for (const ns of Object.values(imports || {})) {\n for (const k of Object.keys(ns || {})) {\n if (k.includes(\"wmdTurn\"))\n ns[k] = new WebAssembly.Suspending(turn);\n }\n }\n return imports;\n };\n const inst = WebAssembly.instantiate;\n const Inst = WebAssembly.Instance;\n WebAssembly.instantiate = (src, imports, ...rest) => inst.call(WebAssembly, src, wrap(imports), ...rest);\n WebAssembly.Instance = new Proxy(Inst, { construct: (T, [mod, imports], nt) => Reflect.construct(T, [mod, wrap(imports)], nt) });\n return run().finally(() => {\n WebAssembly.instantiate = inst;\n WebAssembly.Instance = Inst;\n });\n}\nasync function loadRuntime({ glue, glueScript, module, memory, stack, debug = false, importer = (u) => import(u), jspi = hasJspi(), role = \"main\" }) {\n const g = glueScript ? (0, eval)(glueScript + `\n//# sourceURL=wmd-glue.js`) : await importer(glue);\n const init = () => g.default({ module_or_path: module, memory, thread_stack_size: stack });\n const turning = jspi && role === \"thread\";\n const wasm = turning ? await suspendingImports(makeTurn(), init) : await init();\n g.wmd_init();\n g.wmd_set_debug(!!debug);\n if (turning)\n g.wmd_enable_turn();\n return { glue: g, memory: memory || wasm.memory, exports: wasm, turning };\n}\n\n// src/edge/own/serdes-codec.js\nvar LIMIT = 1024 * 1024;\nvar T = { UNDEF: 0, NULL: 1, FALSE: 2, TRUE: 3, NUM: 4, BIGINT: 5, STR: 6, DATE: 7, REGEXP: 8, ARRAY: 9, OBJECT: 10, MAP: 11, SET: 12, ABUF: 13, HOLE: 14, VIEW: 15, ERROR: 16, REF: 17 };\nvar VIEWS = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, DataView];\nvar ERRORS = [\"Error\", \"EvalError\", \"RangeError\", \"ReferenceError\", \"SyntaxError\", \"TypeError\", \"URIError\"];\n\nclass Unsupported extends Error {\n}\nfunction encode(value) {\n const out = [];\n let size = 0;\n const refs = new Map;\n const u8 = (n) => {\n out.push(Uint8Array.of(n));\n size += 1;\n };\n const u32 = (n) => {\n const b = new Uint8Array(4);\n new DataView(b.buffer).setUint32(0, n, true);\n out.push(b);\n size += 4;\n };\n const f64 = (n) => {\n const b = new Uint8Array(8);\n new DataView(b.buffer).setFloat64(0, n, true);\n out.push(b);\n size += 8;\n };\n const bytes = (b) => {\n if ((size += b.length) > LIMIT)\n throw new Unsupported;\n out.push(b);\n };\n const str = (s) => {\n u32(s.length);\n const b = new Uint8Array(s.length * 2);\n const dv = new DataView(b.buffer);\n for (let i = 0;i < s.length; i++)\n dv.setUint16(i * 2, s.charCodeAt(i), true);\n bytes(b);\n };\n const walk = (v) => {\n if (size > LIMIT)\n throw new Unsupported;\n switch (typeof v) {\n case \"undefined\":\n return u8(T.UNDEF);\n case \"boolean\":\n return u8(v ? T.TRUE : T.FALSE);\n case \"number\":\n u8(T.NUM);\n return f64(v);\n case \"bigint\":\n u8(T.BIGINT);\n return str(v.toString());\n case \"string\":\n u8(T.STR);\n return str(v);\n case \"object\":\n break;\n default:\n throw new Unsupported;\n }\n if (v === null)\n return u8(T.NULL);\n if (refs.has(v)) {\n u8(T.REF);\n return u32(refs.get(v));\n }\n const proto = Object.getPrototypeOf(v);\n const remember = () => refs.set(v, refs.size);\n if (v instanceof Date && proto === Date.prototype) {\n remember();\n u8(T.DATE);\n return f64(v.getTime());\n }\n if (v instanceof RegExp && proto === RegExp.prototype) {\n remember();\n u8(T.REGEXP);\n str(v.source);\n return str(v.flags);\n }\n if (v instanceof ArrayBuffer && proto === ArrayBuffer.prototype) {\n remember();\n u8(T.ABUF);\n u32(v.byteLength);\n return bytes(new Uint8Array(v).slice());\n }\n if (ArrayBuffer.isView(v)) {\n const kind = VIEWS.findIndex((C) => v instanceof C);\n if (kind < 0)\n throw new Unsupported;\n remember();\n u8(T.VIEW);\n u8(kind);\n u32(v.byteLength);\n return bytes(new Uint8Array(v.buffer, v.byteOffset, v.byteLength).slice());\n }\n if (v instanceof Error) {\n const name = ERRORS.includes(v.name) && proto === globalThis[v.name].prototype ? v.name : null;\n if (!name)\n throw new Unsupported;\n remember();\n u8(T.ERROR);\n str(name);\n str(String(v.message));\n str(typeof v.stack === \"string\" ? v.stack : \"\");\n if (\"cause\" in v) {\n u8(1);\n return walk(v.cause);\n }\n return u8(0);\n }\n if (Array.isArray(v) && proto === Array.prototype) {\n remember();\n u8(T.ARRAY);\n u32(v.length);\n for (let i = 0;i < v.length; i++) {\n if (i in v)\n walk(v[i]);\n else\n u8(T.HOLE);\n }\n return;\n }\n if (v instanceof Map && proto === Map.prototype) {\n remember();\n u8(T.MAP);\n u32(v.size);\n for (const [k, x] of v) {\n walk(k);\n walk(x);\n }\n return;\n }\n if (v instanceof Set && proto === Set.prototype) {\n remember();\n u8(T.SET);\n u32(v.size);\n for (const x of v)\n walk(x);\n return;\n }\n if (proto === Object.prototype || proto === null) {\n remember();\n u8(T.OBJECT);\n const keys = Object.keys(v);\n u32(keys.length);\n for (const k of keys) {\n str(k);\n walk(v[k]);\n }\n return;\n }\n throw new Unsupported;\n };\n try {\n walk(value);\n } catch (e) {\n if (e instanceof Unsupported)\n return null;\n throw e;\n }\n const all = new Uint8Array(size);\n let at = 0;\n for (const b of out) {\n all.set(b, at);\n at += b.length;\n }\n return all;\n}\nfunction decode(buf) {\n const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n let at = 0;\n const need = (n) => {\n if (n < 0 || at + n > buf.length)\n throw new RangeError(\"serdes codec: unexpected end of buffer\");\n };\n const u8 = () => {\n need(1);\n return buf[at++];\n };\n const u32 = () => {\n need(4);\n const n = dv.getUint32(at, true);\n at += 4;\n return n;\n };\n const f64 = () => {\n need(8);\n const n = dv.getFloat64(at, true);\n at += 8;\n return n;\n };\n const str = () => {\n const n = u32();\n need(n * 2);\n let s = \"\";\n for (let i = 0;i < n; i += 4096) {\n const part = [];\n for (let j = i;j < Math.min(n, i + 4096); j++)\n part.push(dv.getUint16(at + j * 2, true));\n s += String.fromCharCode(...part);\n }\n at += n * 2;\n return s;\n };\n const refs = [];\n const read = () => {\n const t = u8();\n switch (t) {\n case T.UNDEF:\n return;\n case T.NULL:\n return null;\n case T.FALSE:\n return false;\n case T.TRUE:\n return true;\n case T.NUM:\n return f64();\n case T.BIGINT:\n return BigInt(str());\n case T.STR:\n return str();\n case T.REF: {\n const i = u32();\n if (i >= refs.length)\n throw new RangeError(\"serdes codec: bad reference\");\n return refs[i];\n }\n case T.DATE: {\n const d = new Date(f64());\n refs.push(d);\n return d;\n }\n case T.REGEXP: {\n const r = new RegExp(str(), str());\n refs.push(r);\n return r;\n }\n case T.ABUF: {\n const n = u32();\n need(n);\n const ab = buf.slice(at, at + n).buffer;\n at += n;\n refs.push(ab);\n return ab;\n }\n case T.VIEW: {\n const C = VIEWS[u8()];\n const n = u32();\n if (!C)\n throw new RangeError(\"serdes codec: bad view\");\n need(n);\n const ab = buf.slice(at, at + n).buffer;\n at += n;\n const view = C === DataView ? new DataView(ab) : new C(ab);\n refs.push(view);\n return view;\n }\n case T.ERROR: {\n const name = str();\n if (!ERRORS.includes(name))\n throw new RangeError(\"serdes codec: bad error\");\n const e = new globalThis[name](str());\n const stack = str();\n refs.push(e);\n Object.defineProperty(e, \"stack\", { value: stack, writable: true, configurable: true, enumerable: false });\n if (u8())\n Object.defineProperty(e, \"cause\", { value: read(), writable: true, configurable: true, enumerable: false });\n return e;\n }\n case T.ARRAY: {\n const n = u32();\n const a = [];\n refs.push(a);\n a.length = n;\n for (let i = 0;i < n; i++) {\n if (buf[at] === T.HOLE) {\n at++;\n continue;\n }\n a[i] = read();\n }\n return a;\n }\n case T.MAP: {\n const n = u32();\n const m = new Map;\n refs.push(m);\n for (let i = 0;i < n; i++) {\n const k = read();\n m.set(k, read());\n }\n return m;\n }\n case T.SET: {\n const n = u32();\n const s = new Set;\n refs.push(s);\n for (let i = 0;i < n; i++)\n s.add(read());\n return s;\n }\n case T.OBJECT: {\n const n = u32();\n const o = {};\n refs.push(o);\n for (let i = 0;i < n; i++) {\n const k = str();\n Object.defineProperty(o, k, { value: read(), writable: true, configurable: true, enumerable: true });\n }\n return o;\n }\n default:\n throw new RangeError(`serdes codec: unknown tag ${t}`);\n }\n };\n return read();\n}\n\n// src/edge/own/v8-serdes.js\nvar T2 = {\n PAD: 0,\n VERIFY: 63,\n UNDEF: 95,\n NULL: 48,\n TRUE: 84,\n FALSE: 70,\n INT32: 73,\n UINT32: 85,\n DOUBLE: 78,\n BIGINT: 90,\n UTF8: 83,\n ONE_BYTE: 34,\n TWO_BYTE: 99,\n REF: 94,\n OBJECT: 111,\n END_OBJECT: 123,\n DENSE: 65,\n END_DENSE: 36,\n SPARSE: 97,\n END_SPARSE: 64,\n DATE: 68,\n TRUE_OBJ: 121,\n FALSE_OBJ: 120,\n NUM_OBJ: 110,\n BIGINT_OBJ: 122,\n STR_OBJ: 115,\n REGEXP: 82,\n MAP: 59,\n END_MAP: 58,\n SET: 39,\n END_SET: 44,\n ABUF: 66,\n RESIZABLE_ABUF: 126,\n TRANSFERRED_ABUF: 116,\n SHARED_ABUF: 117,\n VIEW: 86,\n HOST: 92,\n ERROR: 114,\n HOLE: 45\n};\nvar ERR = { EVAL: 69, RANGE: 82, REFERENCE: 70, SYNTAX: 83, TYPE: 84, URI: 85, MESSAGE: 109, CAUSE: 99, STACK: 115, END: 46 };\nvar ERROR_NAMES = { EvalError: ERR.EVAL, RangeError: ERR.RANGE, ReferenceError: ERR.REFERENCE, SyntaxError: ERR.SYNTAX, TypeError: ERR.TYPE, URIError: ERR.URI };\nvar VIEW_TAGS = [\n [\"Int8Array\", 98],\n [\"Uint8Array\", 66],\n [\"Uint8ClampedArray\", 67],\n [\"Int16Array\", 119],\n [\"Uint16Array\", 87],\n [\"Int32Array\", 100],\n [\"Uint32Array\", 68],\n [\"Float16Array\", 104],\n [\"Float32Array\", 102],\n [\"Float64Array\", 70],\n [\"BigInt64Array\", 113],\n [\"BigUint64Array\", 81],\n [\"DataView\", 63]\n];\nvar VERSION = 15;\nvar FLAG_BITS = [[\"g\", 1], [\"i\", 2], [\"m\", 4], [\"y\", 8], [\"u\", 16], [\"s\", 32], [\"l\", 64], [\"d\", 128], [\"v\", 256]];\nvar MAX_INDEX = 4294967294;\nvar VIEW_LENGTH_TRACKING = 1;\nvar VIEW_BACKED_BY_RAB = 2;\nvar VERSION_ERROR = \"Unable to deserialize cloned data due to invalid or unsupported version.\";\nvar MIN_VERSION = 13;\nvar viewByteLength = (v) => {\n try {\n if (typeof v.at === \"function\")\n v.at(0);\n return v.byteLength;\n } catch {\n return -1;\n }\n};\nvar tracksLength = (v, ab) => {\n const before = viewByteLength(v);\n if (before < 0)\n return false;\n const size = ab.byteLength;\n const per = v.BYTES_PER_ELEMENT || 1;\n try {\n if (size + per <= ab.maxByteLength) {\n ab.resize(size + per);\n const grew = viewByteLength(v) !== before;\n ab.resize(size);\n return grew;\n }\n if (size - per >= v.byteOffset) {\n const kept = new Uint8Array(ab).slice(size - per);\n ab.resize(size - per);\n const after = viewByteLength(v);\n ab.resize(size);\n new Uint8Array(ab).set(kept, size - per);\n return before >= per && after === before - per;\n }\n } catch {}\n return false;\n};\nvar own = (o, k) => Object.getOwnPropertyDescriptor(o, k);\nvar tagOf = (o) => Object.prototype.toString.call(o);\nvar brand = (f) => (o) => {\n try {\n f(o);\n return true;\n } catch {\n return false;\n }\n};\nvar isDate = brand((o) => Date.prototype.getTime.call(o));\nvar isMap = brand((o) => own(Map.prototype, \"size\").get.call(o));\nvar isSet = brand((o) => own(Set.prototype, \"size\").get.call(o));\nvar isArrayBuffer = brand((o) => own(ArrayBuffer.prototype, \"byteLength\").get.call(o));\nvar isSharedArrayBuffer = typeof SharedArrayBuffer === \"function\" ? brand((o) => own(SharedArrayBuffer.prototype, \"byteLength\").get.call(o)) : () => false;\nvar isRegExp = brand((o) => {\n if (o === RegExp.prototype)\n throw 0;\n own(RegExp.prototype, \"source\").get.call(o);\n});\nvar isBoolObj = brand((o) => Boolean.prototype.valueOf.call(o));\nvar isNumObj = brand((o) => Number.prototype.valueOf.call(o));\nvar isStrObj = brand((o) => String.prototype.valueOf.call(o));\nvar isBigObj = brand((o) => BigInt.prototype.valueOf.call(o));\nvar NOT_CLONABLE = new Set([\"[object Promise]\", \"[object WeakMap]\", \"[object WeakSet]\", \"[object WeakRef]\", \"[object FinalizationRegistry]\", \"[object Generator]\", \"[object AsyncGenerator]\", \"[object Iterator]\"]);\nvar isIndexKey = (k) => {\n if (k.length === 0 || k.length > 10)\n return false;\n const c = k.charCodeAt(0);\n if (c < 48 || c > 57 || c === 48 && k.length > 1)\n return false;\n for (let i = 1;i < k.length; i++) {\n const d = k.charCodeAt(i);\n if (d < 48 || d > 57)\n return false;\n }\n return Number(k) <= MAX_INDEX;\n};\nvar isInt32 = (n) => n === (n | 0) && !(n === 0 && 1 / n < 0);\n\nclass Writer {\n constructor() {\n this.buf = new Uint8Array(256);\n this.len = 0;\n this.dv = new DataView(this.buf.buffer);\n }\n need(n) {\n if (this.len + n <= this.buf.length)\n return;\n let cap = this.buf.length * 2;\n while (cap < this.len + n)\n cap *= 2;\n const b = new Uint8Array(cap);\n b.set(this.buf.subarray(0, this.len));\n this.buf = b;\n this.dv = new DataView(b.buffer);\n }\n byte(x) {\n this.need(1);\n this.buf[this.len++] = x;\n }\n varint(n) {\n this.need(10);\n if (n <= 4294967295) {\n n >>>= 0;\n do {\n let b = n & 127;\n n >>>= 7;\n if (n)\n b |= 128;\n this.buf[this.len++] = b;\n } while (n);\n return;\n }\n let big = BigInt(n);\n do {\n let b = Number(big & 0x7fn);\n big >>= 7n;\n if (big)\n b |= 128;\n this.buf[this.len++] = b;\n } while (big);\n }\n varintBig(big) {\n this.need(10);\n do {\n let b = Number(big & 0x7fn);\n big >>= 7n;\n if (big)\n b |= 128;\n this.buf[this.len++] = b;\n } while (big);\n }\n f64(n) {\n this.need(8);\n this.dv.setFloat64(this.len, n, true);\n this.len += 8;\n }\n bytes(u8) {\n this.need(u8.length);\n this.buf.set(u8, this.len);\n this.len += u8.length;\n }\n out() {\n return this.buf.slice(0, this.len);\n }\n}\nvar varintSize = (n) => {\n let c = 1;\n while (n >= 128) {\n n = Math.floor(n / 128);\n c++;\n }\n return c;\n};\nfunction makeSerdesBinding({ bufferOf = null } = {}) {\n\n class Serializer {\n constructor() {\n this._w = new Writer;\n this._ids = new Map;\n this._next = 0;\n this._hostViews = false;\n this._transfer = new Map;\n }\n writeHeader() {\n this._w.byte(255);\n this._w.varint(VERSION);\n }\n writeValue(value) {\n this._write(value);\n return true;\n }\n releaseBuffer() {\n const out = this._w.out();\n this._w = new Writer;\n return bufferOf ? bufferOf(out) : out;\n }\n transferArrayBuffer(id, ab) {\n this._transfer.set(ab, Number(id) >>> 0);\n }\n writeUint32(n) {\n this._w.varint(Number(n) >>> 0);\n }\n writeUint64(hi, lo) {\n this._w.varintBig(BigInt(Number(hi) >>> 0) << 32n | BigInt(Number(lo) >>> 0));\n }\n writeDouble(n) {\n this._w.f64(Number(n));\n }\n writeRawBytes(src) {\n this._w.bytes(rawBytes(src));\n }\n _setTreatArrayBufferViewsAsHostObjects(on) {\n this._hostViews = Boolean(on);\n }\n _fail(text) {\n const E = this._getDataCloneError || Error;\n throw new E(text);\n }\n _describe(v) {\n try {\n if (typeof v === \"function\" || typeof v === \"symbol\")\n return String(v);\n const c = v && v.constructor && v.constructor.name;\n return `#<${c || \"Object\"}>`;\n } catch {\n return \"#<Object>\";\n }\n }\n _string(s) {\n const w = this._w;\n const n = s.length;\n let one = true;\n for (let i = 0;i < n; i++) {\n if (s.charCodeAt(i) > 255) {\n one = false;\n break;\n }\n }\n if (one) {\n w.byte(T2.ONE_BYTE);\n w.varint(n);\n w.need(n);\n for (let i = 0;i < n; i++)\n w.buf[w.len++] = s.charCodeAt(i);\n return;\n }\n const bytes = n * 2;\n if (w.len + 1 + varintSize(bytes) & 1)\n w.byte(T2.PAD);\n w.byte(T2.TWO_BYTE);\n w.varint(bytes);\n w.need(bytes);\n for (let i = 0;i < n; i++) {\n const c = s.charCodeAt(i);\n w.buf[w.len++] = c & 255;\n w.buf[w.len++] = c >> 8;\n }\n }\n _bigintBody(v) {\n const w = this._w;\n const neg = v < 0n;\n let mag = neg ? -v : v;\n const digits = [];\n while (mag > 0n) {\n digits.push(mag & 0xffffffffffffffffn);\n mag >>= 64n;\n }\n w.varint(digits.length * 8 * 2 + (neg ? 1 : 0));\n for (const d of digits) {\n w.need(8);\n w.dv.setBigUint64(w.len, d, true);\n w.len += 8;\n }\n }\n _number(n) {\n const w = this._w;\n if (isInt32(n)) {\n w.byte(T2.INT32);\n w.varint((n << 1 ^ n >> 31) >>> 0);\n } else {\n w.byte(T2.DOUBLE);\n w.f64(n);\n }\n }\n _key(k) {\n if (isIndexKey(k))\n this._number(Number(k));\n else\n this._string(k);\n }\n _props(o, keys) {\n let n = 0;\n for (const k of keys) {\n if (!Object.prototype.propertyIsEnumerable.call(o, k))\n continue;\n this._key(k);\n this._write(o[k]);\n n++;\n }\n return n;\n }\n _write(v) {\n const w = this._w;\n switch (typeof v) {\n case \"undefined\":\n return w.byte(T2.UNDEF);\n case \"boolean\":\n return w.byte(v ? T2.TRUE : T2.FALSE);\n case \"number\":\n return this._number(v);\n case \"bigint\":\n w.byte(T2.BIGINT);\n return this._bigintBody(v);\n case \"string\":\n return this._string(v);\n case \"object\":\n if (v === null)\n return w.byte(T2.NULL);\n return this._receiver(v);\n default:\n return this._fail(`${this._describe(v)} could not be cloned.`);\n }\n }\n _receiver(o) {\n const w = this._w;\n const seen = this._ids.get(o);\n if (seen !== undefined) {\n w.byte(T2.REF);\n return w.varint(seen);\n }\n if (!this._hostViews && !Array.isArray(o) && ArrayBuffer.isView(o))\n return this._view(o);\n this._ids.set(o, this._next++);\n if (Array.isArray(o))\n return this._array(o);\n if (isDate(o)) {\n w.byte(T2.DATE);\n return w.f64(Date.prototype.getTime.call(o));\n }\n if (isBoolObj(o))\n return w.byte(Boolean.prototype.valueOf.call(o) ? T2.TRUE_OBJ : T2.FALSE_OBJ);\n if (isNumObj(o)) {\n w.byte(T2.NUM_OBJ);\n return w.f64(Number.prototype.valueOf.call(o));\n }\n if (isStrObj(o)) {\n w.byte(T2.STR_OBJ);\n return this._string(String.prototype.valueOf.call(o));\n }\n if (isBigObj(o)) {\n w.byte(T2.BIGINT_OBJ);\n return this._bigintBody(BigInt.prototype.valueOf.call(o));\n }\n if (isRegExp(o)) {\n w.byte(T2.REGEXP);\n this._string(own(RegExp.prototype, \"source\").get.call(o));\n const flags = own(RegExp.prototype, \"flags\").get.call(o);\n let bits = 0;\n for (const [c, b] of FLAG_BITS)\n if (flags.includes(c))\n bits |= b;\n return w.varint(bits);\n }\n if (isMap(o)) {\n w.byte(T2.MAP);\n const entries = Array.from(Map.prototype.entries.call(o));\n for (const [k, x] of entries) {\n this._write(k);\n this._write(x);\n }\n w.byte(T2.END_MAP);\n return w.varint(entries.length * 2);\n }\n if (isSet(o)) {\n w.byte(T2.SET);\n const items = Array.from(Set.prototype.values.call(o));\n for (const x of items)\n this._write(x);\n w.byte(T2.END_SET);\n return w.varint(items.length);\n }\n if (isArrayBuffer(o))\n return this._arrayBuffer(o);\n if (isSharedArrayBuffer(o)) {\n if (typeof this._getSharedArrayBufferId !== \"function\")\n return this._fail(`${this._describe(o)} could not be cloned.`);\n w.byte(T2.SHARED_ABUF);\n return w.varint(Number(this._getSharedArrayBufferId(o)) >>> 0);\n }\n if (ArrayBuffer.isView(o))\n return this._view(o);\n if (typeof o === \"function\")\n return this._fail(`${String(o)} could not be cloned.`);\n const tag = tagOf(o);\n if (tag === \"[object Error]\")\n return this._error(o);\n if (NOT_CLONABLE.has(tag))\n return this._fail(`${this._describe(o)} could not be cloned.`);\n w.byte(T2.OBJECT);\n const n = this._props(o, Object.keys(o));\n w.byte(T2.END_OBJECT);\n return w.varint(n);\n }\n _array(a) {\n const w = this._w;\n const len = a.length;\n let packed = true;\n for (let i = 0;i < len; i++) {\n if (!(i in a)) {\n packed = false;\n break;\n }\n }\n if (!packed) {\n w.byte(T2.SPARSE);\n w.varint(len);\n const n = this._props(a, Object.keys(a));\n w.byte(T2.END_SPARSE);\n w.varint(n);\n return w.varint(len);\n }\n w.byte(T2.DENSE);\n w.varint(len);\n let doubles = len > 0;\n let fractional = false;\n for (let i = 0;i < len && doubles; i++) {\n const x = a[i];\n if (typeof x !== \"number\")\n doubles = false;\n else if (!isInt32(x))\n fractional = true;\n }\n doubles = doubles && fractional;\n for (let i = 0;i < len; i++) {\n if (doubles) {\n w.byte(T2.DOUBLE);\n w.f64(a[i]);\n } else\n this._write(a[i]);\n }\n const keys = Object.keys(a);\n const named = keys.length > len ? keys.slice(len) : [];\n const n = this._props(a, named);\n w.byte(T2.END_DENSE);\n w.varint(n);\n return w.varint(len);\n }\n _arrayBuffer(ab) {\n const w = this._w;\n const moved = this._transfer.get(ab);\n if (moved !== undefined) {\n w.byte(T2.TRANSFERRED_ABUF);\n return w.varint(moved);\n }\n const bytes = new Uint8Array(ab);\n if (ab.resizable) {\n w.byte(T2.RESIZABLE_ABUF);\n w.varint(ab.byteLength);\n w.varint(ab.maxByteLength);\n } else {\n w.byte(T2.ABUF);\n w.varint(ab.byteLength);\n }\n return w.bytes(bytes);\n }\n _view(v) {\n const w = this._w;\n if (this._hostViews) {\n if (typeof this._writeHostObject !== \"function\")\n return this._fail(`${this._describe(v)} could not be cloned.`);\n w.byte(T2.HOST);\n return this._writeHostObject(v);\n }\n const kind = VIEW_TAGS.findIndex(([name]) => typeof globalThis[name] === \"function\" && v instanceof globalThis[name]);\n const k = kind >= 0 ? kind : VIEW_TAGS.findIndex(([name]) => name !== \"DataView\" && tagOf(v) === `[object ${name}]`);\n const idx = k >= 0 ? k : tagOf(v) === \"[object DataView]\" ? VIEW_TAGS.length - 1 : -1;\n if (idx < 0)\n return this._fail(`${this._describe(v)} could not be cloned.`);\n let flags = 0;\n let length = v.byteLength;\n if (v.buffer.resizable === true) {\n flags = VIEW_BACKED_BY_RAB;\n if (tracksLength(v, v.buffer)) {\n flags |= VIEW_LENGTH_TRACKING;\n length = 0;\n }\n }\n if (!this._ids.has(v.buffer)) {\n this._ids.set(v.buffer, this._next++);\n this._arrayBuffer(v.buffer);\n } else {\n w.byte(T2.REF);\n w.varint(this._ids.get(v.buffer));\n }\n this._ids.set(v, this._next++);\n w.byte(T2.VIEW);\n w.byte(VIEW_TAGS[idx][1]);\n w.varint(v.byteOffset);\n w.varint(length);\n return w.varint(flags);\n }\n _error(e) {\n const w = this._w;\n w.byte(T2.ERROR);\n let name = \"\";\n try {\n name = String(e.name);\n } catch {\n name = \"\";\n }\n if (Object.hasOwn(ERROR_NAMES, name))\n w.byte(ERROR_NAMES[name]);\n const m = own(e, \"message\");\n if (m && \"value\" in m) {\n w.byte(ERR.MESSAGE);\n this._string(String(m.value));\n }\n let stack;\n try {\n stack = e.stack;\n } catch {\n stack = undefined;\n }\n if (typeof stack === \"string\") {\n w.byte(ERR.STACK);\n this._string(stack);\n }\n const c = own(e, \"cause\");\n if (c && \"value\" in c) {\n w.byte(ERR.CAUSE);\n this._write(c.value);\n }\n return w.byte(ERR.END);\n }\n }\n\n class Deserializer {\n constructor(value) {\n this.buffer = value;\n this.bytes = rawBytes(value);\n this.offset = 0;\n this._version = 0;\n this._objects = [];\n this._transfer = new Map;\n this._dv = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);\n }\n readHeader() {\n let version = 0;\n if (this.bytes[this.offset] === 255) {\n this.offset++;\n try {\n version = this._varint32();\n } catch (e) {\n throw e && e.__serdes ? new Error(VERSION_ERROR) : e;\n }\n this._version = version;\n if (version > VERSION)\n throw new Error(VERSION_ERROR);\n }\n if (version < MIN_VERSION)\n throw new Error(VERSION_ERROR);\n return true;\n }\n readValue() {\n try {\n return this._read();\n } catch (e) {\n if (e && e.__serdes)\n throw new Error(\"Unable to deserialize cloned data.\");\n throw e;\n }\n }\n getWireFormatVersion() {\n return this._version;\n }\n transferArrayBuffer(id, ab) {\n this._transfer.set(Number(id) >>> 0, ab);\n }\n _called(text, f) {\n try {\n return f();\n } catch (e) {\n throw e && e.__serdes ? new Error(text) : e;\n }\n }\n readUint32() {\n return this._called(\"ReadUint32() failed\", () => this._varint32());\n }\n readUint64() {\n return this._called(\"ReadUint64() failed\", () => {\n const big = this._varintBig();\n return [Number(big >> 32n) >>> 0, Number(big & 0xffffffffn)];\n });\n }\n readDouble() {\n return this._called(\"ReadDouble() failed\", () => {\n this._need(8);\n const n = this._dv.getFloat64(this.offset, true);\n this.offset += 8;\n return n;\n });\n }\n _readRawBytes(length) {\n const n = Number(length) >>> 0;\n return this._called(\"ReadRawBytes() failed\", () => {\n this._need(n);\n const at = this.offset;\n this.offset += n;\n return at;\n });\n }\n _bad() {\n const e = new Error(\"bad\");\n e.__serdes = true;\n return e;\n }\n _need(n) {\n if (n < 0 || this.offset + n > this.bytes.length)\n throw this._bad();\n }\n _byte() {\n this._need(1);\n return this.bytes[this.offset++];\n }\n _varint32() {\n let n = 0;\n for (let i = 0;; i++) {\n this._need(1);\n const b = this.bytes[this.offset];\n if (i === 5)\n return n >>> 0;\n this.offset++;\n n |= (b & 127) << 7 * i;\n if (!(b & 128))\n return n >>> 0;\n }\n }\n _varint() {\n let n = 0;\n let scale = 1;\n for (let i = 0;; i++) {\n const b = this._byte();\n n += (b & 127) * scale;\n if (!(b & 128))\n return n;\n scale *= 128;\n if (i > 8)\n throw this._bad();\n }\n }\n _varintBig() {\n let n = 0n;\n let shift = 0n;\n for (;; ) {\n const b = this._byte();\n n |= BigInt(b & 127) << shift;\n if (!(b & 128))\n return n;\n shift += 7n;\n if (shift > 70n)\n throw this._bad();\n }\n }\n _peek() {\n return this.offset < this.bytes.length ? this.bytes[this.offset] : -1;\n }\n _skipPadding() {\n while (this._peek() === T2.PAD)\n this.offset++;\n }\n _stringBody(tag) {\n if (tag === T2.ONE_BYTE) {\n const n = this._varint();\n this._need(n);\n let s = \"\";\n for (let i = 0;i < n; i += 8192)\n s += String.fromCharCode.apply(null, this.bytes.subarray(this.offset + i, this.offset + Math.min(n, i + 8192)));\n this.offset += n;\n return s;\n }\n if (tag === T2.TWO_BYTE) {\n const n = this._varint();\n if (n & 1)\n throw this._bad();\n this._need(n);\n let s = \"\";\n const units = n / 2;\n for (let i = 0;i < units; i += 4096) {\n const part = [];\n for (let j = i;j < Math.min(units, i + 4096); j++)\n part.push(this.bytes[this.offset + j * 2] | this.bytes[this.offset + j * 2 + 1] << 8);\n s += String.fromCharCode.apply(null, part);\n }\n this.offset += n;\n return s;\n }\n if (tag === T2.UTF8) {\n const n = this._varint();\n this._need(n);\n const s = new TextDecoder().decode(this.bytes.subarray(this.offset, this.offset + n));\n this.offset += n;\n return s;\n }\n throw this._bad();\n }\n _readString() {\n this._skipPadding();\n return this._stringBody(this._byte());\n }\n _bigintBody() {\n const bits = this._varint();\n const neg = bits & 1;\n const n = Math.floor(bits / 2);\n if (neg && n === 0)\n throw this._bad();\n this._need(n);\n const tail = n % 8;\n let v = 0n;\n for (let i = n - 1;i >= n - tail; i--)\n v = v << 8n | BigInt(this.bytes[this.offset + i]);\n for (let i = (n - tail) / 8 - 1;i >= 0; i--)\n v = v << 64n | this._dv.getBigUint64(this.offset + i * 8, true);\n this.offset += n;\n return neg ? -v : v;\n }\n _add(o) {\n this._objects.push(o);\n return o;\n }\n _setKey(o, k, v) {\n if (Object.hasOwn(o, k))\n throw this._bad();\n if (k === \"__proto__\")\n Object.defineProperty(o, k, { value: v, writable: true, enumerable: true, configurable: true });\n else\n o[k] = v;\n }\n _props(o, endTag) {\n let n = 0;\n for (;; ) {\n this._skipPadding();\n if (this._peek() === endTag) {\n this.offset++;\n return n;\n }\n const k = this._read();\n if (typeof k !== \"string\" && typeof k !== \"number\")\n throw this._bad();\n this._setKey(o, k, this._read());\n n++;\n }\n }\n _read() {\n this._skipPadding();\n const t = this._byte();\n switch (t) {\n case T2.VERIFY:\n this._varint32();\n return this._read();\n case T2.UNDEF:\n return;\n case T2.NULL:\n return null;\n case T2.TRUE:\n return true;\n case T2.FALSE:\n return false;\n case T2.INT32: {\n const z = this._varint();\n return z >>> 1 ^ -(z & 1);\n }\n case T2.UINT32:\n return this._varint();\n case T2.DOUBLE: {\n this._need(8);\n const n = this._dv.getFloat64(this.offset, true);\n this.offset += 8;\n return n;\n }\n case T2.BIGINT:\n return this._bigintBody();\n case T2.ONE_BYTE:\n case T2.TWO_BYTE:\n case T2.UTF8:\n return this._stringBody(t);\n case T2.REF: {\n const id = this._varint();\n if (id >= this._objects.length)\n throw this._bad();\n const o = this._objects[id];\n return o instanceof ArrayBuffer ? this._maybeView(o) : o;\n }\n case T2.OBJECT: {\n const o = this._add({});\n const n = this._props(o, T2.END_OBJECT);\n if (this._varint() !== n)\n throw this._bad();\n return o;\n }\n case T2.DENSE: {\n const len = this._varint();\n if (len > this.bytes.length - this.offset)\n throw this._bad();\n const a = this._add(new Array(len));\n for (let i = 0;i < len; i++) {\n if (this._peek() === T2.HOLE) {\n this.offset++;\n continue;\n }\n a[i] = this._read();\n }\n const n = this._props(a, T2.END_DENSE);\n if (this._varint() !== n)\n throw this._bad();\n if (this._varint() !== len)\n throw this._bad();\n return a;\n }\n case T2.SPARSE: {\n const len = this._varint();\n const a = this._add([]);\n a.length = len;\n const n = this._props(a, T2.END_SPARSE);\n if (this._varint() !== n)\n throw this._bad();\n if (this._varint() !== len)\n throw this._bad();\n return a;\n }\n case T2.DATE: {\n this._need(8);\n const d = this._add(new Date(this._dv.getFloat64(this.offset, true)));\n this.offset += 8;\n return d;\n }\n case T2.TRUE_OBJ:\n return this._add(Object(true));\n case T2.FALSE_OBJ:\n return this._add(Object(false));\n case T2.NUM_OBJ: {\n this._need(8);\n const n = this._add(Object(this._dv.getFloat64(this.offset, true)));\n this.offset += 8;\n return n;\n }\n case T2.BIGINT_OBJ:\n return this._add(Object(this._bigintBody()));\n case T2.STR_OBJ:\n return this._add(Object(this._readString()));\n case T2.REGEXP: {\n const source = this._readString();\n const bits = this._varint32();\n if (bits & ~447 || bits & 16 && bits & 256)\n throw this._bad();\n let flags = \"\";\n for (const [c, b] of FLAG_BITS)\n if (bits & b)\n flags += c;\n return this._add(new RegExp(source, flags));\n }\n case T2.MAP: {\n const m = this._add(new Map);\n let n = 0;\n for (;; ) {\n this._skipPadding();\n if (this._peek() === T2.END_MAP) {\n this.offset++;\n break;\n }\n const k = this._read();\n m.set(k, this._read());\n n += 2;\n }\n if (this._varint() !== n)\n throw this._bad();\n return m;\n }\n case T2.SET: {\n const s = this._add(new Set);\n let n = 0;\n for (;; ) {\n this._skipPadding();\n if (this._peek() === T2.END_SET) {\n this.offset++;\n break;\n }\n s.add(this._read());\n n++;\n }\n if (this._varint() !== n)\n throw this._bad();\n return s;\n }\n case T2.ABUF:\n case T2.RESIZABLE_ABUF: {\n const len = this._varint();\n const max = t === T2.RESIZABLE_ABUF ? this._varint() : len;\n this._need(len);\n const ab = t === T2.RESIZABLE_ABUF ? new ArrayBuffer(len, { maxByteLength: max }) : new ArrayBuffer(len);\n new Uint8Array(ab).set(this.bytes.subarray(this.offset, this.offset + len));\n this.offset += len;\n this._add(ab);\n return this._maybeView(ab);\n }\n case T2.TRANSFERRED_ABUF: {\n const ab = this._transfer.get(this._varint());\n if (!ab)\n throw this._bad();\n this._add(ab);\n return this._maybeView(ab);\n }\n case T2.HOST: {\n if (typeof this._readHostObject !== \"function\")\n throw this._bad();\n const at = this._objects.length;\n this._objects.push(undefined);\n const o = this._readHostObject();\n this._objects[at] = o;\n return o;\n }\n case T2.ERROR:\n return this._readError();\n default:\n throw this._bad();\n }\n }\n _maybeView(ab) {\n if (this._peek() !== T2.VIEW)\n return ab;\n this.offset++;\n const sub = this._byte();\n const k = VIEW_TAGS.findIndex((x) => x[1] === sub);\n if (k < 0)\n throw this._bad();\n const offset = this._varint();\n const length = this._varint();\n const flags = this._version >= 14 ? this._varint() >>> 0 : 0;\n const tracking = (flags & VIEW_LENGTH_TRACKING) !== 0;\n const rab = (flags & VIEW_BACKED_BY_RAB) !== 0;\n if ((tracking || rab) && ab.resizable !== true)\n throw this._bad();\n if (ab.resizable === true && !rab)\n throw this._bad();\n const C = globalThis[VIEW_TAGS[k][0]];\n if (typeof C !== \"function\")\n throw this._bad();\n const per = C === DataView ? 1 : C.BYTES_PER_ELEMENT || 1;\n if (offset % per || length % per)\n throw this._bad();\n let v;\n try {\n if (C === DataView)\n v = tracking ? new DataView(ab, offset) : new DataView(ab, offset, length);\n else\n v = tracking ? new C(ab, offset) : new C(ab, offset, length / (C.BYTES_PER_ELEMENT || 1));\n } catch {\n throw this._bad();\n }\n return this._add(v);\n }\n _readError() {\n const at = this._objects.length;\n this._objects.push(undefined);\n let Ctor = Error;\n let message;\n let stack;\n let hasCause = false;\n let cause;\n for (;; ) {\n const t = this._byte();\n if (t === ERR.END)\n break;\n if (t === ERR.EVAL)\n Ctor = EvalError;\n else if (t === ERR.RANGE)\n Ctor = RangeError;\n else if (t === ERR.REFERENCE)\n Ctor = ReferenceError;\n else if (t === ERR.SYNTAX)\n Ctor = SyntaxError;\n else if (t === ERR.TYPE)\n Ctor = TypeError;\n else if (t === ERR.URI)\n Ctor = URIError;\n else if (t === ERR.MESSAGE)\n message = this._readString();\n else if (t === ERR.STACK)\n stack = this._readString();\n else if (t === ERR.CAUSE) {\n hasCause = true;\n cause = this._read();\n } else\n throw this._bad();\n }\n const e = message === undefined ? new Ctor : new Ctor(message);\n this._objects[at] = e;\n if (hasCause)\n Object.defineProperty(e, \"cause\", { value: cause, writable: true, enumerable: false, configurable: true });\n if (stack !== undefined)\n Object.defineProperty(e, \"stack\", { value: stack, writable: true, enumerable: false, configurable: true });\n return e;\n }\n }\n return { Serializer, Deserializer };\n}\nfunction rawBytes(value) {\n if (value instanceof ArrayBuffer || typeof SharedArrayBuffer === \"function\" && value instanceof SharedArrayBuffer)\n return new Uint8Array(value);\n if (ArrayBuffer.isView(value))\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n throw new TypeError(\"buffer must be an ArrayBuffer or an ArrayBuffer view\");\n}\n\n// src/edge/own/payload-size.js\nvar BIG_SHARE = 1 << 20;\nfunction payloadBytes(v, depth = 0, seen = new Set) {\n if (!v || typeof v !== \"object\" || depth > 6 || seen.has(v))\n return 0;\n if (ArrayBuffer.isView(v))\n return v.byteLength;\n if (v instanceof ArrayBuffer || typeof SharedArrayBuffer !== \"undefined\" && v instanceof SharedArrayBuffer)\n return v.byteLength;\n seen.add(v);\n let n = 0;\n for (const k of Object.keys(v))\n n += payloadBytes(v[k], depth + 1, seen);\n return n;\n}\n\n// src/edge/own/capi.js\nvar GONE_LIMIT = 4096;\nvar key = (registry, handle) => `${registry}:${handle}`;\nfunction installCapi(g, { channel, scope, BroadcastChannel: BC = g.BroadcastChannel, relay = null, log = null }) {\n if (!Number.isInteger(scope) || scope < 0 || scope > 4095)\n throw new Error(`capi: scope ${scope} is not below 4096`);\n const table = new Map;\n const waiting = new Map;\n const gone = new Map;\n const markGone = (k, who) => {\n gone.delete(k);\n gone.set(k, who);\n if (gone.size > GONE_LIMIT)\n for (const old of gone.keys()) {\n gone.delete(old);\n if (gone.size <= GONE_LIMIT)\n break;\n }\n };\n const mine = new Map;\n const bc = !relay && channel && BC ? new BC(channel) : null;\n const open = !!(bc || relay);\n const send = (msg) => relay ? relay({ ...msg, from: scope }) : bc.postMessage(msg);\n const put = (k, envelope) => {\n table.set(k, envelope);\n const ws = waiting.get(k);\n if (ws) {\n waiting.delete(k);\n for (const w of ws)\n w.resolve(undefined);\n }\n };\n const receive = (d) => {\n if (!d || d.from === scope)\n return;\n if (log)\n log(`got ${d.t} ${d.handle}`);\n if (d.t === \"share\") {\n if (!gone.has(key(d.registry, d.handle)))\n put(key(d.registry, d.handle), d.envelope);\n else if (log)\n log(`late copy of ${d.handle} dropped (deleted ${gone.get(key(d.registry, d.handle))})`);\n } else if (d.t === \"delete\") {\n table.delete(key(d.registry, d.handle));\n mine.delete(key(d.registry, d.handle));\n markGone(key(d.registry, d.handle), \"from \" + d.from);\n } else if (d.t === \"hello\") {\n if (log)\n log(`hello: sending again ${[...mine.values()].map((m) => m.handle).join(\",\") || \"nothing\"}`);\n for (const [, m] of mine)\n if (payloadBytes(m.envelope) < BIG_SHARE)\n send({ t: \"share\", registry: m.registry, handle: m.handle, envelope: m.envelope });\n }\n };\n if (bc) {\n bc.onmessage = (e) => receive(e.data);\n bc.onmessageerror = () => {\n if (log)\n log(\"a message from another Worker could not be read here (messageerror)\");\n };\n }\n if (open)\n send({ t: \"hello\" });\n g.__wasmerCapiShare = (registry, handle, envelope) => {\n if (log)\n log(`share ${handle} ${typeof envelope?.value} ${String(Object.prototype.toString.call(envelope?.value))}`);\n try {\n if (open)\n send({ t: \"share\", registry, handle, envelope });\n } catch (e) {\n if (log) {\n let what = \"\";\n try {\n const v = envelope && envelope.value;\n what = v && typeof v === \"object\" ? Object.keys(v).map((k) => `${k}:${typeof v[k]}`).join(\",\") : typeof v;\n } catch (e2) {\n what = \"unreadable \" + String(e2);\n }\n log(`share ${handle} could not be copied: ${String(e && e.name || \"\")} ${String(e && e.message || e).slice(0, 200)} (${what})`);\n }\n throw e;\n }\n mine.set(key(registry, handle), { registry, handle, envelope });\n put(key(registry, handle), envelope);\n };\n g.__wasmerCapiObtain = (registry, handle) => {\n if (log)\n log(`obtain ${handle} ${table.has(key(registry, handle))}`);\n return table.get(key(registry, handle));\n };\n g.__wasmerCapiWait = (registry, handle) => {\n const k = key(registry, handle);\n if (log)\n log(`wait ${registry}:${handle} ${table.has(k)}`);\n if (table.has(k))\n return Promise.resolve(undefined);\n if (open)\n send({ t: \"want\", registry, handle });\n return new Promise((resolve, reject) => {\n const list = waiting.get(k) || [];\n list.push({ resolve, reject });\n waiting.set(k, list);\n });\n };\n g.__wasmerCapiDelete = (registry, handle) => {\n if (log)\n log(`delete ${handle}`);\n table.delete(key(registry, handle));\n mine.delete(key(registry, handle));\n markGone(key(registry, handle), \"here\");\n if (open)\n send({ t: \"delete\", registry, handle });\n };\n g.__wasmerCapiInfo = (registry, handle) => ({ inTable: table.has(key(registry, handle)), mine: mine.has(key(registry, handle)), gone: gone.get(key(registry, handle)) || null, tableSize: table.size });\n g.__wasmerCapiMessageScope = () => scope;\n return {\n receive,\n close() {\n if (bc)\n bc.close();\n for (const ws of waiting.values())\n for (const w of ws)\n w.reject(new Error(\"capi: closed\"));\n waiting.clear();\n },\n table,\n goneLimit: GONE_LIMIT,\n goneSize: () => gone.size\n };\n}\nfunction installSerdesState(g, { scope, note = null }) {\n let next = scope * 2 ** 20 + 1;\n const say = (ev, id, extra = \"\") => note && note(`SERDES ${Math.round(performance.timeOrigin + performance.now()) % 1e7} s${scope} ${ev} ${id} w${Math.floor(id / 2 ** 20)}${extra}`);\n const seen = new Set;\n const state = {\n get next() {\n return next;\n },\n set next(v) {\n next = v;\n },\n codec: {\n encode: (value) => {\n const bytes = encode(value);\n if (note)\n say(bytes ? \"inline\" : \"byid\", 0, ` ${bytes ? bytes.length : 0}`);\n return bytes;\n },\n decode\n },\n values: {\n set: (id, value) => {\n say(\"share\", id);\n return g.__wasmerCapiShare(1397051972, id, { value });\n },\n has: (id) => {\n const hit = g.__wasmerCapiObtain(1397051972, id) !== undefined;\n if (note) {\n if (hit)\n say(\"has\", id, seen.has(id) ? \" AGAIN\" : \"\");\n else {\n const i = g.__wasmerCapiInfo ? g.__wasmerCapiInfo(1397051972, id) : {};\n say(\"MISS\", id, ` ${seen.has(id) ? \"read-before-here\" : i.gone ? \"deleted-\" + i.gone.replace(\" \", \"-\") : i.mine ? \"mine-not-in-table\" : \"never-arrived\"} table=${i.tableSize}`);\n }\n seen.add(id);\n }\n return hit;\n },\n get: (id) => g.__wasmerCapiObtain(1397051972, id)?.value,\n delete: (id) => {\n say(\"delete\", id);\n return g.__wasmerCapiDelete(1397051972, id);\n }\n },\n binding: () => makeSerdesBinding({ bufferOf: (u8) => state.bufferOf ? state.bufferOf(u8) : u8 }),\n bufferOf: null\n };\n g[Symbol.for(\"wasmer.napi.serdes.state\")] = state;\n}\n\n// src/edge/own/wasm-counters.js\nvar kind = (url) => {\n const u = String(url || \"\");\n if (/edgejs\\.wasm/.test(u))\n return \"program\";\n if (/wmd_browser_bg\\.wasm/.test(u))\n return \"runtime\";\n if (/wmd_browser\\.js/.test(u))\n return \"glue\";\n if (/HASHES\\.txt/.test(u))\n return \"hashes\";\n if (/linux\\.cjs/.test(u))\n return \"shim\";\n return \"other\";\n};\nvar sizeOf = (src) => {\n try {\n if (src && typeof src.byteLength === \"number\")\n return src.byteLength;\n if (src && src.buffer && typeof src.buffer.byteLength === \"number\")\n return src.buffer.byteLength;\n } catch {}\n return 0;\n};\nfunction installWasmCounters(g) {\n if (g.__wmdWasmCounters)\n return g.__wmdWasmCounters;\n const W = g.WebAssembly;\n const c = {\n compile: { calls: 0, bytes: 0, ms: 0 },\n stream: { calls: 0, bytes: 0, ms: 0 },\n instantiate: { calls: 0, bytes: 0, ms: 0 },\n module: { calls: 0, bytes: 0, ms: 0, maxMs: 0 },\n memory: { made: 0, shared: 0, madeBytes: 0 },\n fetched: {}\n };\n const refs = [];\n const kinds = [];\n const wrapAsync = (name, slot, bytesOf) => {\n const orig = W[name];\n if (typeof orig !== \"function\")\n return;\n W[name] = function(...a) {\n c[slot].calls++;\n c[slot].bytes += bytesOf ? bytesOf(a[0]) : 0;\n const t0 = performance.now();\n const p = orig.apply(this, a);\n return p && typeof p.then === \"function\" ? p.finally(() => c[slot].ms += performance.now() - t0) : p;\n };\n };\n wrapAsync(\"compile\", \"compile\", sizeOf);\n wrapAsync(\"instantiate\", \"instantiate\", sizeOf);\n const streamBytes = (r) => {\n try {\n return Number(r && r.headers && r.headers.get && r.headers.get(\"content-length\")) || 0;\n } catch {\n return 0;\n }\n };\n wrapAsync(\"compileStreaming\", \"stream\", null);\n wrapAsync(\"instantiateStreaming\", \"stream\", null);\n if (W.Module) {\n W.Module = new Proxy(W.Module, {\n construct(target, args) {\n const t0 = performance.now();\n const m = Reflect.construct(target, args);\n const ms = performance.now() - t0;\n c.module.calls++;\n c.module.bytes += sizeOf(args[0]);\n c.module.ms += ms;\n c.module.maxMs = Math.max(c.module.maxMs, ms);\n return m;\n }\n });\n }\n if (W.Memory) {\n W.Memory = new Proxy(W.Memory, {\n construct(target, args) {\n const d = args[0] || {};\n const m = Reflect.construct(target, args);\n c.memory.made++;\n if (d.shared)\n c.memory.shared++;\n refs.push(new WeakRef(m));\n kinds.push({ ref: new WeakRef(m), initial: d.initial | 0, maximum: d.maximum, shared: !!d.shared });\n return m;\n }\n });\n }\n const R = g.Response && g.Response.prototype;\n if (R && R.arrayBuffer) {\n const orig = R.arrayBuffer;\n R.arrayBuffer = async function() {\n const b = await orig.call(this);\n const k = kind(this.url);\n const f = c.fetched[k] ||= { calls: 0, bytes: 0 };\n f.calls++;\n f.bytes += b.byteLength;\n return b;\n };\n }\n const api = {\n kinds() {\n return kinds.map((k) => {\n const m = k.ref.deref();\n return { initial: k.initial, maximum: k.maximum, shared: k.shared, pages: m ? m.buffer.byteLength / 65536 : null };\n });\n },\n snapshot() {\n let live = 0;\n let liveBytes = 0;\n for (let i = refs.length - 1;i >= 0; i--) {\n const m = refs[i].deref();\n if (!m)\n continue;\n live++;\n try {\n liveBytes += m.buffer.byteLength;\n } catch {}\n }\n return JSON.parse(JSON.stringify({ ...c, memory: { ...c.memory, live, liveBytes }, kinds: api.kinds() }));\n }\n };\n g.__wmdWasmCounters = api;\n return api;\n}\n\n// src/edge/own/stack-fix.js\nvar NAMES = [\"Error\", \"TypeError\", \"RangeError\", \"SyntaxError\", \"ReferenceError\", \"EvalError\", \"URIError\"];\nfunction withHeader(e) {\n try {\n const s = e.stack;\n if (typeof s !== \"string\")\n return e;\n const name = String(e.name);\n if (s.startsWith(name))\n return e;\n const head = e.message ? `${name}: ${e.message}` : name;\n Object.defineProperty(e, \"stack\", { value: `${head}\n${s}`, writable: true, configurable: true, enumerable: false });\n } catch {}\n return e;\n}\nfunction installStackHeader(g) {\n const probe = new g.Error(\"wmd-probe\").stack;\n if (typeof probe === \"string\" && probe.startsWith(\"Error: wmd-probe\"))\n return false;\n for (const n of NAMES) {\n const C = g[n];\n if (typeof C !== \"function\")\n continue;\n g[n] = new Proxy(C, {\n construct: (target, args, newTarget) => withHeader(Reflect.construct(target, args, newTarget === g[n] ? target : newTarget)),\n apply: (target, thisArg, args) => withHeader(Reflect.apply(target, thisArg, args))\n });\n }\n return true;\n}\n\n// src/edge/own/marks.js\nvar PROGRAM_BYTES = 8 << 20;\nvar at = () => performance.timeOrigin + performance.now();\nvar sizeOf2 = (b) => b && typeof b.byteLength === \"number\" ? b.byteLength : 0;\nvar isProgram = (imports) => !!(imports && (imports.wasix_32v1 || imports.wasix_64v1 || imports.wasi_snapshot_preview1 || imports.wasi_unstable));\nvar CALL_RING = 400;\nvar PUSH_EVERY = 64;\nvar WASIX = [\"wasix_32v1\", \"wasix_64v1\", \"wasi_snapshot_preview1\", \"wasi_unstable\"];\n\nclass CallLog {\n ring = [];\n totals = {};\n n = 0;\n t0 = performance.now();\n post = null;\n wrap(name, f) {\n const log = this;\n return function(...a) {\n const t = performance.now();\n try {\n return f.apply(this, a);\n } finally {\n const us = (performance.now() - t) * 1000;\n const e = log.totals[name] ||= [0, 0];\n e[0]++;\n e[1] += us;\n if (log.ring.length < CALL_RING)\n log.ring.push([name, Math.round((t - log.t0) * 1000) / 1000, Math.round(us)]);\n if (log.post && (++log.n % PUSH_EVERY === 0 || log.ring.length === CALL_RING))\n log.post(log.snapshot());\n }\n };\n }\n wrapImports(imports) {\n const out = { ...imports };\n this.wrapped = {};\n for (const ns of WASIX) {\n if (!imports[ns])\n continue;\n this.wrapped[ns] = Object.keys(imports[ns]).length;\n out[ns] = Object.fromEntries(Object.entries(imports[ns]).map(([k, v]) => [k, typeof v === \"function\" ? this.wrap(k, v) : v]));\n }\n return out;\n }\n reset() {\n this.ring = [];\n this.totals = {};\n this.n = 0;\n this.taken = false;\n }\n snapshot() {\n return { inst: (this.g && this.g.__wmdInst ? this.g.__wmdInst : []).map((p) => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`), seen: this.seen || 0, taken: !!this.taken, wrapped: this.wrapped || null, ring: this.ring.map((r) => r.join(\" \")), totals: Object.fromEntries(Object.entries(this.totals).map(([k, v]) => [k, `${v[0]} ${Math.round(v[1])}`])) };\n }\n}\nfunction installMarks(g, post, opts = {}) {\n const W = g.WebAssembly;\n if (!W || W.__wmdMarks)\n return W && W.__wmdMarks;\n const calls = opts.calls ? new CallLog : null;\n if (calls && opts.postCalls)\n calls.post = opts.postCalls;\n if (calls)\n g.__wmdInst = [], calls.g = g;\n const Mod = W.Module;\n const Inst = W.Instance;\n W.Module = new Proxy(Mod, {\n construct(T, a, nt) {\n const big = sizeOf2(a[0]) >= PROGRAM_BYTES;\n const t0 = at();\n const m = Reflect.construct(T, a, nt);\n if (big)\n post(\"compile0\", t0), post(\"compile1\", at());\n return m;\n }\n });\n W.Instance = new Proxy(Inst, {\n construct(T, a, nt) {\n const prog = isProgram(a[1]);\n const t0 = at();\n if (prog && calls)\n calls.seen = (calls.seen || 0) + 1;\n let args = a;\n if (prog && calls && !calls.taken)\n calls.taken = true, args = [a[0], calls.wrapImports(a[1]), ...a.slice(2)];\n const i = Reflect.construct(T, args, nt);\n if (prog && calls && args !== a)\n calls.t0 = performance.now();\n if (prog)\n post(\"inst0\", t0), post(\"inst1\", at());\n return i;\n }\n });\n const compile = W.compile;\n W.compile = function(b, ...rest) {\n const big = sizeOf2(b) >= PROGRAM_BYTES;\n const t0 = at();\n const p = compile.call(this, b, ...rest);\n if (big)\n post(\"acompile0\", t0), p.then(() => post(\"acompile1\", at()), () => {});\n return p;\n };\n W.__wmdMarks = calls || true;\n return calls;\n}\n\n// src/edge/own/exit-now.js\nfunction makeExitNow({ runId, post, outs, cleanup = () => {}, endProcess = () => false, park }) {\n let posted = false;\n const status = (code) => {\n const n = Number(code);\n return Number.isFinite(n) ? Math.trunc(n) & 255 : 0;\n };\n return function exitNow(code, pid = 1) {\n if (pid !== 1) {\n let ended = false;\n try {\n ended = endProcess(pid, status(code)) === true;\n } catch {}\n if (ended)\n park();\n return;\n }\n if (!posted) {\n posted = true;\n try {\n cleanup();\n } catch {}\n post({ type: \"exit\", id: runId(), code: status(code), outs: outs() });\n }\n park();\n };\n}\nfunction parkForever() {\n const cell = new Int32Array(new SharedArrayBuffer(4));\n for (;; )\n Atomics.wait(cell, 0, 0);\n}\n\n// src/edge/own/worker.js\ninstallStackHeader(globalThis);\nvar glue = null;\nvar exports = null;\nvar turning = false;\nvar debug = false;\nvar role = \"\";\nvar capi = null;\nvar counters = null;\nvar marks = false;\nvar calls = null;\nvar runId = 0;\nvar text = (err) => String(err && err.stack || err);\nself.addEventListener(\"message\", async (e) => {\n const m = e.data;\n try {\n if (m.type === \"init\") {\n checkInit(m);\n debug = !!m.debug;\n if (debug)\n console.log(`[w] performance.memory ${typeof performance.memory} used ${performance.memory && performance.memory.usedJSHeapSize}`);\n role = m.role;\n counters = installWasmCounters(globalThis);\n if (m.marks)\n 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;\n if (calls && typeof calls.snapshot !== \"function\")\n calls = null;\n if (marks)\n self.postMessage({ type: \"mark\", name: m.role === \"main\" ? \"mInit0\" : \"tInit0\", t: at() });\n if (m.fsTime) {\n const post = self.postMessage.bind(self);\n self.postMessage = (msg, t) => post(msg && msg.type === \"fs\" ? { ...msg, t0: performance.timeOrigin + performance.now() } : msg, t);\n }\n if (Array.isArray(m.nodeGlobals))\n globalThis.__wmdNodeGlobals = m.nodeGlobals;\n if (m.capi)\n 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 });\n if (capi)\n installSerdesState(globalThis, { scope: m.scope % 4096, note: m.fsTime ? (text) => self.postMessage({ type: \"note\", text }) : null });\n const r = await loadRuntime({ ...m, role: m.role });\n glue = r.glue;\n exports = r.exports;\n turning = r.turning;\n if (marks)\n self.postMessage({ type: \"mark\", name: m.role === \"main\" ? \"mReady\" : \"tReady\", t: at() });\n glue.wmd_set_trace(m.trace | 0);\n 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 });\n if (m.calltrace)\n glue.wmd_set_calltrace(true);\n if (m.napifixOff)\n glue.wmd_set_napifix_off(true);\n globalThis.__wmdCtl = (_pid, json) => glue.wmd_ctl(json);\n self.postMessage({\n type: \"ready\",\n memory: r.memory,\n stdin: { addr: glue.wmd_stdin_addr(), cap: glue.wmd_stdin_cap(), off: glue.wmd_stdin_offset() },\n tty: glue.wmd_tty_addr()\n });\n } else if (m.type === \"counts\") {\n self.postMessage({ type: \"counts\", seq: m.seq, role, c: counters ? counters.snapshot() : null });\n } else if (m.type === \"capi\") {\n if (capi)\n capi.receive(m.msg);\n } else if (m.type === \"task\") {\n try {\n if (debug)\n console.log(\"[w thread] task start\");\n if (marks)\n self.postMessage({ type: \"mark\", name: \"task0\", t: at() });\n if (calls)\n calls.reset();\n if (turning) {\n const ptr = glue.wmd_thread_prepare(m.msg);\n await WebAssembly.promising(exports.wmd_job_main)(ptr);\n } else {\n glue.wmd_thread_entry(m.msg);\n }\n } catch (err) {\n self.postMessage({ type: \"crash\", error: text(err) });\n return;\n }\n if (calls && calls.taken)\n self.postMessage({ type: \"calls\", ...calls.snapshot() });\n if (debug)\n console.log(\"[w thread] task done\");\n self.postMessage({ type: \"done\" });\n } else if (m.type === \"run\") {\n runId = m.id;\n try {\n if (debug)\n console.log(\"[w main] run start\");\n if (marks)\n self.postMessage({ type: \"mark\", name: \"runRecv\", t: at() });\n if (calls)\n calls.reset();\n const run = m.node ? glue.wmd_run_node : glue.wmd_run;\n if (!run)\n throw new Error(\"this build has no N-API support (build edge/browser with --features napi)\");\n let code;\n if (m.module && !m.node && glue.wmd_run_ready) {\n code = glue.wmd_run_ready(m.module, m.hash, m.program, m.args || [], m.env || [], m.opts || \"\");\n } else if (m.module && m.node && glue.wmd_run_node_ready) {\n code = glue.wmd_run_node_ready(m.module, m.hash, m.program, m.args || [], m.env || [], m.opts || \"\");\n } else {\n code = run(new Uint8Array(m.program), m.args || [], m.env || [], m.opts || \"\");\n }\n if (calls)\n self.postMessage({ type: \"calls\", ...calls.snapshot() });\n if (marks)\n self.postMessage({ type: \"mark\", name: \"exitPost\", t: at() });\n self.postMessage({ type: \"exit\", id: m.id, code, outs: glue.wmd_out_count() });\n } catch (err) {\n self.postMessage({ type: \"run-error\", id: m.id, error: text(err), outs: glue.wmd_out_count() });\n }\n }\n } catch (err) {\n self.postMessage({ type: \"fatal\", error: text(err) });\n }\n});\n"
|
|
6
|
+
export const FRAME_CODE = { frame: FRAME, worker: WORKER, ownWorker: OWNWORKER }
|