@threadedstack/wmd-web 0.1.39 → 0.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +236 -1
  2. package/RELEASE.json +84 -49
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +231 -4
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +208 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +125 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +13 -2
  38. package/src/edge/sbx/cap.js +36 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +275 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/setup.js +9 -6
  54. package/src/host/chan-service.js +8 -5
  55. package/src/host/chan-services.js +29 -4
  56. package/src/host/edge-host.js +58 -3
  57. package/wmdpack.wasm +0 -0
@@ -0,0 +1,186 @@
1
+ // The sandboxed frame (no second site): what the page's side, the frame and the frame's Workers share.
2
+ //
3
+ // The frame is made by the library from strings: a sandboxed iframe (`sandbox="allow-scripts"`, no `allow-same-origin`), so its origin is
4
+ // opaque and it can reach none of the page's storage, cookies or state. Everything it runs reaches it as bytes or text from the page over a
5
+ // MessagePort. Which Worker form the browser takes is found by a probe in the frame (probeStrategy), never by the browser's name:
6
+ // module a module Worker from a blob: URL (Firefox)
7
+ // boot a classic blob: Worker that import()s the module from a second blob: URL (Chromium refuses module Workers from an opaque blob:)
8
+ // data a module Worker from a data: URL, every module of it a data: URL (WebKit refuses blob: Workers of an opaque frame under COEP)
9
+ // Modules import each other only by absolute blob: or data: URLs, so the glue's two relative imports are rewritten (urlsFor).
10
+
11
+ /** The "origin" the page's bookkeeping (bridge, kept frames, the site) uses for the frame the library makes itself. */
12
+ export const SANDBOX = 'x5:sandbox'
13
+ export const STRATEGIES = ['module', 'boot', 'data']
14
+
15
+ const b64 = text => {
16
+ const bytes = new TextEncoder().encode(text)
17
+ let s = ''
18
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000))
19
+ return btoa(s)
20
+ }
21
+ // base64 with each slash written %2F (the URL parser percent-decodes the body before it reads the base64, so the module is the same text). WebKit
22
+ // builds a prefix string at every slash of a module's URL each time a Worker resolves an import, and base64 holds a slash about every 64 characters
23
+ // (item 7 of product.md). No quote or space is possible in the body, so the URL sits inside the quotes of the import that names it.
24
+ export const dataUrl = text => 'data:text/javascript;base64,' + b64(text).replace(/\//g, '%2F')
25
+ const blobUrl = text => URL.createObjectURL(new Blob([text], { type: 'text/javascript' }))
26
+
27
+ /** A classic Worker script that loads the module at `url` and replays the messages that came before it loaded. */
28
+ export const bootSrc = url =>
29
+ 'var q = []; var h = function (e) { q.push(e) }; self.addEventListener("message", h);\n' +
30
+ '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' +
31
+ ' function (e) { postMessage({ type: "done", error: "the frame\'s Worker code did not load: " + String(e && e.message || e) }) })'
32
+
33
+ // The data form's Worker is this short module and is sent its code as the first message. A Worker made from the code's own data: URL puts that whole URL
34
+ // (62,963 characters for the runtime's Worker) into every frame of every Error stack it makes; here the code runs by eval under a short name.
35
+ export const 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") } }'
36
+ const SCRIPT_PREFIX = 'wmd-script:'
37
+
38
+ /** {name, url(text) -> the URL a module of this form has, make(url, opts) -> a Worker running that module}; the data form also has script(text) -> a name make() takes. */
39
+ export function makeFactory(name) {
40
+ if (name === 'data') {
41
+ const scripts = new Map()
42
+ const loader = 'data:text/javascript,' + encodeURIComponent(SCRIPT_LOADER)
43
+ return {
44
+ name,
45
+ url: dataUrl,
46
+ script: t => {
47
+ const n = SCRIPT_PREFIX + scripts.size
48
+ scripts.set(n, t)
49
+ return n
50
+ },
51
+ make: (u, o) => {
52
+ const t = scripts.get(u)
53
+ if (t === undefined) return new Worker(u, { name: o && o.name, type: 'module' })
54
+ const w = new Worker(loader, { name: o && o.name, type: 'module' })
55
+ w.postMessage({ __wmdScript: '"use strict";' + t })
56
+ return w
57
+ },
58
+ }
59
+ }
60
+ if (name === 'boot') return { name, url: blobUrl, make: (u, o) => new Worker(blobUrl(bootSrc(u)), { name: o && o.name }) }
61
+ return { name: 'module', url: blobUrl, make: (u, o) => new Worker(u, { name: o && o.name, type: 'module' }) }
62
+ }
63
+
64
+ /**
65
+ * A module as an expression that evaluates to its exports object (so it can run by eval under a short source name). Only the shapes of the pinned glue: `export class|function|
66
+ * async function|const|let|var` lines and `export { a, b as c }` lists, import.meta.url as a fixed string; null when an import is left, a top-level await is found, or nothing is exported.
67
+ */
68
+ export function moduleToScript(src) {
69
+ const names = []
70
+ 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))
71
+ const lists = []
72
+ body = body.replace(/^export\s*\{([^}]*)\}\s*;?[ \t]*$/gm, (m, l) => (lists.push(...asObject(l)), ''))
73
+ if (lists.includes(null) || /^\s*(import|export)\b/m.test(body) || /^await\b/m.test(body) || (!names.length && !lists.length)) return null
74
+ body = body.replace(/import\.meta\.url/g, '"about:blank"')
75
+ return `(() => {\n'use strict';\n${body}\nreturn { ${[...names, ...lists].join(', ')} }\n})()`
76
+ }
77
+
78
+ const ACORN_RE = /(from\s*)(['"])\.\.\/\.\.\/acorn\/acorn\.mjs\2/g
79
+ const SNIPPET_RE = /(from\s*)(['"])\.\/snippets\/[^'"]+\/inline0\.js\2/g
80
+ // The glue imports the napi snippet 21 times: one named import and `import * as importN` for each of 20 imports of its import object, all the same module.
81
+ // Each of them became the snippet's whole nested data: URL (fix round B item 1: the glue's URL was 11.8 MB, and every Worker of the runtime held and
82
+ // resolved it). Now the first one names the URL (one namespace import) and every other is a constant of that namespace: the glue's URL is a tenth of the size
83
+ // (WebKit: its page footprint cost for a node start fell by 1.2 to 1.5 GiB), and what the glue sees is the same module.
84
+ const SNIPPET_IMPORT_RE = /import\s*(?:\*\s*as\s+(\w+)|\{([^}]*)\})\s*from\s*(['"])\.\/snippets\/[^'"]+\/inline0\.js\3/g
85
+ const SNIPPET_NS = '__wmdSnippet'
86
+ const dec = new TextDecoder()
87
+ const text = v => (typeof v === 'string' ? v : dec.decode(v))
88
+
89
+ // One module instead of three (speed-x5-webkit). A data: Worker loads its module graph from URLs, and the glue's URL held the snippet's, which held acorn's (base64
90
+ // inside base64). WebKit kept about 13 MiB for each Worker that loaded the real chain from data: URLs against 4 MiB from a blob: URL (60 Workers: 981 against 385
91
+ // MiB), and the cost followed the length of the nested URL. So acorn and the snippet become expressions inside the glue's own text. Only for the exact shapes of the
92
+ // pinned files (acorn: one `export { ... }` at its end; the snippet: `export function|const` lines and one import of acorn's names); any other shape returns null and
93
+ // the nested URLs are used as before.
94
+ const ACORN_EXPORT_RE = /^export\s*\{([^}]*)\}\s*;?\s*$/m
95
+ const ACORN_IMPORT_RE = /^import\s*\{([^}]*)\}\s*from\s*(['"])\.\.\/\.\.\/acorn\/acorn\.mjs\2\s*;?[ \t]*$/m
96
+ // `export { x as y }` makes the object { y: x }
97
+ const asObject = list => list.split(',').map(x => x.trim()).filter(Boolean).map(x => { const m = /^([\w$]+)\s+as\s+([\w$]+)$/.exec(x); return m ? `${m[2]}: ${m[1]}` : /^[\w$]+$/.test(x) ? x : null })
98
+ function acornExpr(src) {
99
+ const m = ACORN_EXPORT_RE.exec(src)
100
+ const rest = m && src.replace(ACORN_EXPORT_RE, '')
101
+ if (!m || /^(import|export)\b/m.test(rest)) return null
102
+ const names = asObject(m[1])
103
+ return names.includes(null) ? null : `(() => {\n'use strict';\n${rest}\nreturn { ${names.join(', ')} }\n})()`
104
+ }
105
+ function snippetExpr(src, acornSrc) {
106
+ const im = ACORN_IMPORT_RE.exec(src)
107
+ const ac = im && acornExpr(acornSrc)
108
+ if (!ac) return null
109
+ // `import { parse as p }` is `const { parse: p } = acorn`
110
+ const pairs = im[1].split(',').map(x => x.trim()).filter(Boolean).map(x => { const k = /^([\w$]+)\s+as\s+([\w$]+)$/.exec(x); return k ? `${k[1]}: ${k[2]}` : /^[\w$]+$/.test(x) ? x : null })
111
+ if (!pairs.length || pairs.includes(null)) return null
112
+ let body = src.replace(ACORN_IMPORT_RE, `const { ${pairs.join(', ')} } = __wmdAcorn;`)
113
+ const names = []
114
+ 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))
115
+ if (/^(import|export)\b/m.test(body) || !names.length) return null
116
+ return `(() => {\n'use strict';\nconst __wmdAcorn = ${ac};\n${body}\nreturn { ${names.join(', ')} }\n})()`
117
+ }
118
+
119
+ /** The glue imports its snippet and the snippet imports acorn by relative paths; here they become one module (the snippet and acorn inside the glue's text), or, when their shape is not the known one, the URLs of this form (the snippet's once). -> {glue, worker} */
120
+ export function urlsFor(factory, { glue, snippet, acorn, ownWorker }) {
121
+ const expr = snippetExpr(text(snippet), text(acorn))
122
+ let nested = null
123
+ if (!expr) {
124
+ const acornU = factory.url(text(acorn))
125
+ nested = factory.url(text(snippet).replace(ACORN_RE, (m, a, q) => a + q + acornU + q))
126
+ }
127
+ let first = true
128
+ const named = text(glue).replace(SNIPPET_IMPORT_RE, (m, star, braces, q) => {
129
+ const head = first ? (expr ? `const ${SNIPPET_NS} = ${expr}; ` : `import * as ${SNIPPET_NS} from ${q}${nested}${q}; `) : ''
130
+ first = false
131
+ return head + (star ? `const ${star} = ${SNIPPET_NS}` : `const {${braces.replace(/\s+as\s+/g, ': ')}} = ${SNIPPET_NS}`)
132
+ })
133
+ // the data form (it has script()): the glue is text the Workers evaluate and the Worker's code is sent to a short loader
134
+ const script = factory.script && expr ? moduleToScript(named) : null
135
+ if (script) return { glue: SCRIPT_PREFIX + 'glue', glueScript: script, worker: factory.script(text(ownWorker)) }
136
+ return { glue: factory.url(expr ? named : named.replace(SNIPPET_RE, (m, a, q) => a + q + nested + q)), worker: factory.url(text(ownWorker)) }
137
+ }
138
+
139
+ /**
140
+ * Which Worker form this browser takes: each form's probe (a module that imports a second module, as the runtime's do) runs at once, and the first
141
+ * form in the order that starts a Worker and hears from it wins. -> {name, tried: [{name, ok, why?}]}; name is null when none works.
142
+ * `hint` (what an earlier frame of this page found) goes first in the order: the result is kept for the page's lifetime by the page.
143
+ */
144
+ export async function probeStrategy({ hint = '', timeoutMs = 1500, make = makeFactory } = {}) {
145
+ const order = [...(STRATEGIES.includes(hint) ? [hint] : []), ...STRATEGIES.filter(s => s !== hint)]
146
+ // fix round item 4 (F5b): a hint is tried ALONE first. A refused form (WebKit refuses a blob: Worker of an opaque frame under COEP) logs a console error and an
147
+ // uncaught error of its own, so the forms that are not needed are not made: the others are tried only when the hint does not work (the probe still decides).
148
+ const first = STRATEGIES.includes(hint) ? await probeForms([hint], timeoutMs, make) : null
149
+ if (first && first.name) return first
150
+ const rest = await probeForms(first ? order.slice(1) : order, timeoutMs, make)
151
+ return first ? { name: rest.name, tried: [...first.tried, ...rest.tried] } : rest
152
+ }
153
+
154
+ async function probeForms(order, timeoutMs, make) {
155
+ const runs = order.map(name => {
156
+ const f = make(name)
157
+ let w = null
158
+ const p = new Promise(resolve => {
159
+ const timer = setTimeout(() => resolve({ name, ok: false, why: `no answer in ${timeoutMs} ms` }), timeoutMs)
160
+ const end = r => (clearTimeout(timer), resolve({ name, ...r }))
161
+ try {
162
+ const a = f.url('export const v = 7')
163
+ const b = f.url(`import { v } from ${JSON.stringify(a)}; postMessage(v)`)
164
+ w = f.make(b, { name: 'wmd-probe' })
165
+ w.onmessage = e => end(e.data === 7 ? { ok: true } : { ok: false, why: 'a wrong answer' })
166
+ w.onerror = e => {
167
+ e?.preventDefault?.() // a refused form is an answer of the probe, not an uncaught error of the frame
168
+ end({ ok: false, why: String((e && e.message) || 'the Worker did not start') })
169
+ }
170
+ } catch (e) {
171
+ end({ ok: false, why: String((e && e.message) || e).slice(0, 120) })
172
+ }
173
+ })
174
+ return p.then(r => (w && w.terminate(), r))
175
+ })
176
+ const tried = []
177
+ for (const run of runs) {
178
+ const r = await run
179
+ tried.push(r)
180
+ if (r.ok) {
181
+ runs.forEach(x => x.catch(() => {})) // the later probes end by themselves (timer or answer)
182
+ return { name: r.name, tried }
183
+ }
184
+ }
185
+ return { name: null, tried }
186
+ }
@@ -0,0 +1,121 @@
1
+ // The page's side of the sandboxed frame: the frame's document, the handshake and the link (a MessagePort) the run talks over.
2
+ //
3
+ // The document is a srcdoc with a meta policy and ONE inline start script (BOOT_JS, its hash BOOT_HASH is pinned by a test and written in web/README.md, so
4
+ // what an app's Content-Security-Policy must allow does not change with a wmd release). The start script says hello, takes the first message with the port
5
+ // from the parent, and loads the frame's code from text. After `init` everything goes over the port. Why srcdoc and inline: docs/research/browser-speed-2026-11/
6
+ // x5/sandbox/product/product.md item 1.
7
+ import { SANDBOX, dataUrl } from './common.js'
8
+
9
+ /** How long after the frame's document loaded its start script may take to say hello. A page policy that refuses the script makes it never say so. */
10
+ export const HELLO_MS = 3000
11
+ export const silentWhy = ms => `the frame's start script did not run within ${ms} ms of its document loading: the page's Content-Security-Policy refuses it (script-src needs '${BOOT_HASH}', blob: and 'unsafe-eval', and worker-src needs blob: and data: or is absent with data: in script-src; web/README.md) or the machine is too slow; node runs in the guest`
12
+
13
+ /** The document form the library uses: a srcdoc frame (no frame-src of the page's policy applies to it). */
14
+ export const FORM = 'srcdoc'
15
+
16
+ /**
17
+ * The policy inside the frame's document. It is the wall that stops the frame's requests (they would carry the page's cookies): the frame and its
18
+ * Workers can fetch nothing, whatever script runs in them, and script cannot drop a meta policy. Never add a host, 'self', http:, https: or connect-src.
19
+ */
20
+ export const BOOT_HASH = 'sha256-aW6P+6eP4hoF25XvKAQTO1ytOkCZ7TwDyjdVN/WaHTI='
21
+ export const FRAME_CSP = `default-src 'none'; script-src '${BOOT_HASH}' blob: data: 'unsafe-eval' 'wasm-unsafe-eval'; worker-src blob: data:; form-action 'none'; base-uri 'none'`
22
+
23
+ /**
24
+ * The start script of the frame (classic). It says hello to the parent, takes ONE first message, only from the frame's parent, with the port, and loads
25
+ * the frame's code from the text in that message. Tests evaluate this text with fake globals.
26
+ */
27
+ export const BOOT_JS = `(function () {
28
+ var done = false
29
+ addEventListener('message', function (e) {
30
+ if (done || e.source !== parent) return
31
+ var m = e.data
32
+ if (!m || m.x5sbx !== 'init' || typeof m.frame !== 'string' || !e.ports || !e.ports[0]) return
33
+ done = true
34
+ var p = e.ports[0]
35
+ import(URL.createObjectURL(new Blob([m.frame], { type: 'text/javascript' }))).then(
36
+ function (x) { x.default({ port: p, worker: m.worker, ownWorker: m.ownWorker, hint: m.hint }) },
37
+ function (err) { p.postMessage({ x5sbx: 'frame-failed', error: String((err && err.message) || err).slice(0, 300) }) }
38
+ )
39
+ })
40
+ // the page learns that this document (not the empty one a frame starts with) listens: it sends the first message then
41
+ parent.postMessage({ x5sbx: 'hello' }, '*')
42
+ })()`
43
+
44
+ /**
45
+ * The frame's document. The start script is INLINE: a script the frame loads from a blob: or data: URL the page made is refused in an opaque frame
46
+ * (Chromium: "Not allowed to load local resource"), and an inline one needs its hash in the page's policy. BOOT_JS does not change from release to
47
+ * release (a unit test pins its hash; the hash is documented in web/README.md), so what an app must allow does not change either.
48
+ * `scriptUrl` (experiments only): the script from a URL instead.
49
+ */
50
+ export const docHtml = scriptUrl => `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${FRAME_CSP}">${scriptUrl ? `<script src="${scriptUrl}"></script>` : `<script>${BOOT_JS}</script>`}</head><body></body></html>`
51
+
52
+ const links = new WeakMap() // frame -> link
53
+ export const linkOf = f => links.get(f)
54
+
55
+ /**
56
+ * The frame, its port and its link. `code` = {frame, worker, ownWorker} (the generated frame code, src/edge/frame-code.gen.js).
57
+ * link.post(msg, transfer); link.sink(fn | null): the one place the frame's messages go (only messages from this frame's port; a page that
58
+ * listens on its window gets nothing from here); link.violation: the first Content-Security-Policy violation the page's own policy reported
59
+ * while the frame started (its directive and what it blocked); link.close().
60
+ */
61
+ export function createSandboxFrame({ doc = globalThis.document, win = globalThis, code, hint = '', form = FORM, helloMs = HELLO_MS }) {
62
+ const f = doc.createElement('iframe')
63
+ f.setAttribute('sandbox', 'allow-scripts')
64
+ f.setAttribute('allow', 'cross-origin-isolated')
65
+ f.style.cssText = 'position:absolute;width:0;height:0;border:0'
66
+ // form: 'srcdoc' (the document is the iframe's srcdoc) or 'blob' (a blob: document); 'srcdoc-src', 'blob-src' and 'blob-data' load the start script from a URL
67
+ // (experiments: they do not run in an opaque frame, test/edge/page/x5-forms.js)
68
+ const scriptUrl = /-src$/.test(form) ? URL.createObjectURL(new Blob([BOOT_JS], { type: 'text/javascript' })) : form === 'blob-data' ? dataUrl(BOOT_JS) : ''
69
+ const html = docHtml(scriptUrl)
70
+ const bootUrl = scriptUrl
71
+ const docUrl = form.startsWith('blob') ? URL.createObjectURL(new Blob([html], { type: 'text/html' })) : ''
72
+ const ch = new MessageChannel()
73
+ let sink = null
74
+ const link = {
75
+ violation: null,
76
+ port: ch.port1,
77
+ post: (msg, transfer) => ch.port1.postMessage(msg, transfer || []),
78
+ sink: fn => void (sink = fn),
79
+ close: () => {
80
+ ch.port1.onmessage = null
81
+ ch.port1.close()
82
+ doc.removeEventListener('securitypolicyviolation', onViolation)
83
+ win.removeEventListener('message', onHello)
84
+ clearTimeout(helloTimer)
85
+ },
86
+ }
87
+ ch.port1.onmessage = e => sink && sink(e.data)
88
+ // a page whose own policy refuses the frame (frame-src, script-src without blob:) says so here: the browser reports it to the page's document
89
+ function onViolation(e) {
90
+ if (link.violation || !/^(blob|data)/.test(String(e.blockedURI || '')) && !/^(frame|child|script|worker)-src/.test(String(e.effectiveDirective || e.violatedDirective || ''))) return
91
+ link.violation = { directive: String(e.effectiveDirective || e.violatedDirective || ''), blocked: String(e.blockedURI || '').slice(0, 40) }
92
+ link.onViolation && link.onViolation(link.violation)
93
+ }
94
+ doc.addEventListener('securitypolicyviolation', onViolation)
95
+ // the frame's start script says hello from its own document; only the frame's window is heard, and only once: the first message (with the port) goes
96
+ // to it with target '*' (an opaque origin has no other target), then everything goes over the port
97
+ let helloTimer = null
98
+ let heard = false // Firefox runs the start script and posts hello BEFORE the iframe's load event: a hello that came first needs no timer
99
+ const onHello = e => {
100
+ if (!e || e.source !== f.contentWindow || !e.data || e.data.x5sbx !== 'hello') return
101
+ heard = true
102
+ win.removeEventListener('message', onHello)
103
+ clearTimeout(helloTimer)
104
+ if (bootUrl && bootUrl.startsWith('blob:')) URL.revokeObjectURL(bootUrl)
105
+ if (docUrl) URL.revokeObjectURL(docUrl)
106
+ try {
107
+ f.contentWindow.postMessage({ x5sbx: 'init', frame: code.frame, worker: code.worker, ownWorker: code.ownWorker, hint }, '*', [ch.port2])
108
+ } catch {
109
+ // a frame that is gone takes no message
110
+ }
111
+ }
112
+ win.addEventListener('message', onHello)
113
+ // no hello a short time after the frame's document loaded: its start script was refused (the page's policy has no hash for it)
114
+ f.addEventListener('load', () => { if (!heard) helloTimer = setTimeout(() => link.onSilent && link.onSilent(silentWhy(helloMs)), helloMs) }, { once: true })
115
+ if (docUrl) f.src = docUrl
116
+ else f.srcdoc = html
117
+ links.set(f, link)
118
+ return f
119
+ }
120
+
121
+ export { SANDBOX }
@@ -0,0 +1,112 @@
1
+ // Where the sandboxed frame's bytes come from (items 2, 8 and 9): the PAGE fetches them from an ordered list of sources (a registry tarball, a file
2
+ // base, a url; the option edge: { sources }, `base` is the short form of one file base), checks them against the pins (src/edge/pins.gen.js, written by
3
+ // scripts/edge-pins.mjs from a build folder, never by hand) and hands them to the frame as bytes. The fetch, its limits, the sha256 check and the cache
4
+ // are src/host/pinned-fetch.js (X6's, used as it is); this file is the small seam between it and the frame. One page fetches ONCE (fetchEdgeFilesOnce).
5
+ import { PINNED_CACHE_NAME, fetchPinned, pinnedCacheKey } from '../../host/pinned-fetch.js'
6
+ import { EDGE_SOURCES_DEFAULT } from '../base.js'
7
+
8
+ const enc = new TextEncoder()
9
+ /** The names the runtime's own files have in the build's HASHES.txt, and the pin each belongs to. */
10
+ const HASHED = { 'wmd_browser_bg.wasm': 'wasm', 'wmd_browser.js': 'glue' }
11
+
12
+ /**
13
+ * The bytes of one pin from an ordered list of sources, checked: `fetchChecked(pin, sources)` -> {bytes, from} or {error, reasons}. Every fetch of
14
+ * this feature goes through here; `sources` are the plain `<base>/<path>` kind ({kind: 'file', base}) here, and any kind pinned-fetch.js knows.
15
+ */
16
+ export async function fetchChecked(pin, sources, opts = {}) {
17
+ const r = await fetchPinned({ ...opts, files: [{ path: pin.path, sha256: pin.sha256, size: pin.size }], sources })
18
+ if (r.error) return { error: r.error, reasons: r.reasons }
19
+ return { bytes: r.files[pin.path], from: r.from[pin.path], reasons: r.reasons }
20
+ }
21
+
22
+ /** F4d: the most sources one list may have: a longer list is an error, not that many requests and a reason of that many lines. */
23
+ export const EDGE_SOURCES_MAX = 8
24
+ /** The list as it is, or an error that names the option, the number and the limit. */
25
+ export function checkCount(list, name) {
26
+ if (list.length > EDGE_SOURCES_MAX) throw new Error(`${name} has ${list.length} entries, at most ${EDGE_SOURCES_MAX} are allowed`)
27
+ return list
28
+ }
29
+
30
+ /** The option `base` as the list of plain sources: one base or a list of bases, tried in order (the first with every pinned sha256 wins). */
31
+ export const sourcesOf = base => (Array.isArray(base) ? base : [base]).filter(b => typeof b === 'string' && b).map(b => ({ kind: 'file', base: b }))
32
+
33
+ /**
34
+ * The sources the option words name: `sources` (a list), else `base` (one base or a list of bases: file sources), else the package's default
35
+ * (src/edge/base.js). null when there is none.
36
+ */
37
+ export function edgeSources({ sources, base } = {}) {
38
+ if (Array.isArray(sources) && sources.length) return checkCount(sources, 'edge.sources')
39
+ const b = sourcesOf(base)
40
+ if (b.length) return checkCount(b, 'edge.base')
41
+ return Array.isArray(EDGE_SOURCES_DEFAULT) && EDGE_SOURCES_DEFAULT.length ? EDGE_SOURCES_DEFAULT : null
42
+ }
43
+
44
+ /**
45
+ * Every pinned file, checked. -> {files: {role: ArrayBuffer}, notices: n, source, from} or {error, reasons}. The roles the frame uses are wasm,
46
+ * glue, snippet, acorn, edgejs and linux; the notice files are in the pinned set (they are fetched and cached with the rest) and go no further.
47
+ * `pins` and `pkg` come from src/edge/pins.js loadEdgePins(); `pkg` fills the {name} {version} {file} of the sources' urls.
48
+ */
49
+ export async function fetchEdgeFiles({ sources, base, pkg = null, pins, dropCopy = false, ...opts }) {
50
+ const list = edgeSources({ sources, base })
51
+ if (!list) return { error: 'no source for the files of node in the frame', reasons: [] }
52
+ if (!Array.isArray(pins) || !pins.length) return { error: 'no pins for the files of node in the frame', reasons: [] }
53
+ const r = await fetchPinned({ ...opts, pkg, files: pins.map(p => ({ path: p.path, sha256: p.sha256, size: p.size })), sources: list })
54
+ // F4d: the text of a failure is bounded (each reason at 300 characters, the whole at 1500)
55
+ if (r.error) return { error: String(r.error).slice(0, 1500), reasons: (r.reasons || []).map(x => ({ ...x, why: String(x.why).slice(0, 300) })) }
56
+ const files = {}
57
+ let notices = 0
58
+ const hashes = []
59
+ for (const p of pins) {
60
+ if (p.role === 'notice') notices++
61
+ else files[p.role] = r.files[p.path]
62
+ const h = Object.keys(HASHED).find(n => HASHED[n] === p.role)
63
+ if (h) hashes.push(`${p.sha256} ${p.size} ${h}`)
64
+ }
65
+ files.hashes = enc.encode(hashes.join('\n') + '\n').buffer // what the build's HASHES.txt says of the runtime's wasm and glue (own/adapter.js checkFiles)
66
+ return { files, notices, source: r.source, from: r.from, reasons: r.reasons, cached: dropCopy ? await cacheHolds(pins, opts) : false }
67
+ }
68
+
69
+ /** True when Cache Storage holds every pinned file now (a match of each key; no body is read). A storage that is missing or throws holds nothing. */
70
+ export async function cacheHolds(pins, { cacheStorage = globalThis.caches, cacheKeyOf = pinnedCacheKey } = {}) {
71
+ try {
72
+ if (!cacheStorage) return false
73
+ const cache = await cacheStorage.open(PINNED_CACHE_NAME)
74
+ for (const p of pins) if (!(await cache.match(cacheKeyOf(p.sha256)))) return false
75
+ return true
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+
81
+ // ---- one fetch for the page's life (item 8) ----
82
+ const shared = new Map() // key -> promise of a result with no error
83
+ const sizes = new Map() // key -> the bytes the page holds for that result
84
+ const bytesOf = r => Object.values((r && r.files) || {}).reduce((n, v) => n + ((v && v.byteLength) || 0), 0)
85
+ /**
86
+ * One promise per key for the life of the page; a result with an error, or a rejection, is not kept (the next asker tries again). The promise holds the
87
+ * bytes: every asker takes a copy (a frame takes its files by transfer, which empties the buffer it was given).
88
+ */
89
+ export function sharedFiles(key, get) {
90
+ const have = shared.get(key)
91
+ if (have) return have
92
+ const p = Promise.resolve().then(get)
93
+ shared.set(key, p)
94
+ const drop = () => shared.get(key) === p && (shared.delete(key), sizes.delete(key))
95
+ // a result with an error is not kept; with the option dropCopy a result the cache holds is not kept either (item 15: the page drops its copy of the
96
+ // 65 MB, a later asker reads the cache and its hash is checked again; off by default, product.md item 15: a second frame starts slower)
97
+ p.then(r => (r && (r.error || r.cached) ? drop() : r && shared.get(key) === p && sizes.set(key, bytesOf(r))), drop)
98
+ return p
99
+ }
100
+
101
+ /** How many results of this page's one fetch the page holds (item 15; tests and the look from outside). */
102
+ export const heldByPage = () => shared.size
103
+ /** The page lets go of every result it holds (tests). */
104
+ export const forgetHeld = () => (shared.clear(), sizes.clear())
105
+ /** The bytes of those results (the measurement of item 15: 0 once the cache holds the files). */
106
+ export const heldBytes = () => [...sizes.values()].reduce((a, b) => a + b, 0)
107
+
108
+ /** What makes two askers "the same": the pins and the sources (and the package the sources' urls are made from). */
109
+ export const filesKey = ({ sources, base, pkg = null, pins }) => JSON.stringify([edgeSources({ sources, base }), pkg, (pins || []).map(p => [p.path, p.sha256, p.size])])
110
+
111
+ /** fetchEdgeFiles once per page for the same pins and sources (the prepare frame and the first run frame ask for the same files). */
112
+ export const fetchEdgeFilesOnce = o => sharedFiles(filesKey(o), () => fetchEdgeFiles(o))
@@ -0,0 +1,126 @@
1
+ // The frame side of the sandboxed frame (the counterpart of ../frame.js for a frame the library makes itself). Bundled into one text
2
+ // (scripts/build-frame-code.mjs, src/edge/frame-code.gen.js) that the page hands to the frame's start script (doc.js BOOT_JS).
3
+ //
4
+ // Everything arrives over `port`: the page's messages ({x5edge: ping|stop|prepare|start|in} as in ../frame.js, and {x5sbx: 'files'}), and every
5
+ // answer goes back over it. The frame makes no request at all (its document's policy refuses them): the files came as bytes from the page.
6
+ import { kindWord } from '../error-kind.js'
7
+ import { makeFactory, probeStrategy } from './common.js'
8
+
9
+ export default function start({ port, worker, ownWorker, hint = '' }) {
10
+ let w = null // the Worker of the run on now; null between runs
11
+ let cur = 0
12
+ const live = new Set()
13
+ globalThis.x5live = live
14
+ let kept = null // what a run's Worker left for the next (own/adapter.js keep())
15
+ globalThis.x5kept = () => kept
16
+ let held = null // the files the page handed in (glue, snippet, acorn, wasm, edgejs, linux, hashes)
17
+ let mk = null
18
+ let workerUrl = ''
19
+ const up = msg => port.postMessage(msg)
20
+
21
+ const endWorker = x => {
22
+ if (!x || !live.delete(x)) return
23
+ x.onmessage = null
24
+ x.onerror = null
25
+ if (x === w) (w = null), (cur = 0)
26
+ try {
27
+ x.terminate()
28
+ } catch {
29
+ // already gone
30
+ }
31
+ }
32
+ const endAll = () => {
33
+ for (const x of [...live]) endWorker(x)
34
+ }
35
+ // what a Worker of this run is given: the files it needs (a kept compiled module or program means its bytes are not sent) and the Worker form
36
+ const payload = () => {
37
+ if (!held) throw new Error('the page handed in no files')
38
+ const files = { glue: held.glue, snippet: held.snippet, acorn: held.acorn, linux: held.linux, hashes: held.hashes, ...(held.linuxpy ? { linuxpy: held.linuxpy } : {}) }
39
+ if (held.python) files.python = held.python // python's module (X25), when the page handed it in
40
+ if (!(kept && kept.rtModule)) files.wasm = held.wasm
41
+ if (!(kept && kept.prog)) files.edgejs = held.edgejs
42
+ return { strategy: mk.name, ownWorker, files }
43
+ }
44
+ const spawn = () => {
45
+ const x = mk.make(workerUrl, { name: 'wmd-edge' })
46
+ live.add(x)
47
+ return x
48
+ }
49
+
50
+ let prepW = null
51
+ let waiting = null
52
+ const prepDone = r => {
53
+ if (!prepW) return
54
+ const p = prepW
55
+ prepW = null
56
+ endWorker(p)
57
+ up({ x5prepared: r })
58
+ if (waiting) {
59
+ const d = waiting
60
+ waiting = null
61
+ begin(d)
62
+ }
63
+ }
64
+ const prepare = cfg => {
65
+ if (prepW || w || waiting || kept) return up({ x5prepared: { ok: !!kept, already: true } })
66
+ const p = (prepW = spawn())
67
+ p.onmessage = ({ data: d }) => {
68
+ if (d && d.type === 'keep') return void (kept = d.keep)
69
+ if (d && d.type === 'done') prepDone({ ok: !!d.prepared && !d.error, ...(d.error ? { error: String(d.error).slice(0, 300) } : {}), ...(kindWord(d.errorKind) ? { errorKind: d.errorKind } : {}), ms: d.prepareMs })
70
+ }
71
+ p.onerror = e => prepDone({ ok: false, error: 'worker error: ' + e.message })
72
+ try {
73
+ p.postMessage({ cfg, ports: [], prepare: true, kept, tf: performance.timeOrigin + performance.now(), x5sbx: payload() })
74
+ } catch (e) {
75
+ prepDone({ ok: false, error: String((e && e.message) || e).slice(0, 200), errorKind: 'runtime' })
76
+ }
77
+ }
78
+ function begin(data) {
79
+ const run = data.run
80
+ cur = run
81
+ const mine = (w = spawn())
82
+ mine.onmessage = ({ data: d }) => {
83
+ if (d && d.type === 'keep') return void (kept = d.keep)
84
+ up({ x5relay: d, x5run: run })
85
+ if (d && d.type === 'done') endWorker(mine)
86
+ }
87
+ mine.onerror = e => {
88
+ up({ x5relay: { type: 'done', error: 'worker error: ' + e.message }, x5run: run })
89
+ endWorker(mine)
90
+ }
91
+ try {
92
+ mine.postMessage({ cfg: data.cfg, ports: data.ports, tf: performance.timeOrigin + performance.now(), kept, x5sbx: payload() }, data.ports)
93
+ } catch (e) {
94
+ up({ x5relay: { type: 'done', error: String((e && e.message) || e).slice(0, 300), errorKind: 'runtime' }, x5run: run })
95
+ endWorker(mine)
96
+ }
97
+ }
98
+
99
+ addEventListener('pagehide', endAll)
100
+ port.onmessage = ({ data }) => {
101
+ if (!data) return
102
+ if (data.x5sbx === 'files') return void (held = data.files)
103
+ if (data.x5edge === 'ping') return up(data.check !== undefined ? { x5pong: data.check } : 'x5-pong')
104
+ if (data.x5edge === 'stop') return (waiting = null), (prepW = null), endAll()
105
+ if (data.x5edge === 'prepare') return prepare(data.cfg)
106
+ if (data.x5edge === 'in') return w && cur !== 0 && data.run === cur ? w.postMessage({ in: data.in }) : undefined
107
+ if (w || waiting || data.x5edge !== 'start') return
108
+ if (prepW) return void (waiting = data)
109
+ begin(data)
110
+ }
111
+
112
+ // the Worker form, then ready. The page also learns what this frame can do (the policy it runs under): a frame that cannot eval or make a
113
+ // Worker cannot run node, and the page says so at once instead of after a watch limit.
114
+ const evalOk = () => {
115
+ try {
116
+ return new Function('return 7')() === 7
117
+ } catch {
118
+ return false
119
+ }
120
+ }
121
+ probeStrategy({ hint }).then(r => {
122
+ mk = r.name ? makeFactory(r.name) : null
123
+ if (mk) workerUrl = mk.url(worker)
124
+ up({ x5sbx: 'ready', caps: { worker: r.name, tried: r.tried, eval: evalOk(), sab: typeof SharedArrayBuffer === 'function', coi: globalThis.crossOriginIsolated === true } })
125
+ })
126
+ }