@johnhenry/browsermesh-pod 0.0.3 → 0.1.0

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.
@@ -0,0 +1,445 @@
1
+ /**
2
+ * browser-host-driver.mjs — the **in-page** `PodHostDriver` for the browser
3
+ * lane (issue #185 item 7, deliverable A).
4
+ *
5
+ * Of the browser lane's three drivers (in-page, here; CDP,
6
+ * `spikes/browser-pod-host`; extension, `spikes/browser-extension-host`),
7
+ * this is the one that needs NOTHING beyond what a page already has: no
8
+ * remote debugging port, no extension privileges, zero dependencies. A tab
9
+ * (or a worker) drives sibling pages/workers it itself spawned, using
10
+ * `iframe`/`window.open`/`Worker` and `BroadcastChannel` — the same
11
+ * primitives `Pod` already uses for peer discovery.
12
+ *
13
+ * That is also exactly its limit. A parent tab has no privilege boundary
14
+ * against a child it spawned the same way any other tab could: same-origin
15
+ * JS can already reach into same-origin children via `contentWindow`/
16
+ * `postMessage`, and a CROSS-origin child cannot be evaluated into safely
17
+ * from here at all (there is no sandbox, no attestation, nothing stopping
18
+ * the child from lying about what it evaluated). So `exec` — which the
19
+ * browser lane defines as "evaluate an expression in the page's JS
20
+ * context" (see `host-protocol.mjs`'s `POD_LANE_VERBS` doc comment) — is a
21
+ * verb this driver deliberately never implements: `ENOTSUP`, not because
22
+ * nobody got around to it, but because an in-page driver's architecture has
23
+ * no safe way to do it, same-origin or not. `snapshot`/`restore` are
24
+ * `ENOTSUP` for the same "not this wave" reason the module doc comment
25
+ * below spells out — a durable soft-snapshot to IndexedDB is a plausible
26
+ * follow-up, just not implemented here.
27
+ *
28
+ * ── How a spawned pod is found ──────────────────────────────────────────
29
+ *
30
+ * `spawn()` creates the child (iframe / window / worker) pointed at
31
+ * `podUrl` with the pod's name encoded two ways — `iframe.name` /
32
+ * `window.open()`'s name argument / `new Worker(url, {name})`, AND a
33
+ * `#name=…` URL-hash fallback — and then waits on the SAME
34
+ * `BroadcastChannel` (`channel`, shared with the child via
35
+ * `browser-host-child.mjs`'s `bootHostedPod()`) for a
36
+ * `browser-host:ready` announcement naming it. See that module's doc
37
+ * comment for why a broadcast rather than a new wire message type.
38
+ *
39
+ * ── Sending ──────────────────────────────────────────────────────────────
40
+ *
41
+ * `send()` goes over `postMessage` directly to the child's own global
42
+ * (`contentWindow` / window ref / worker ref) rather than through
43
+ * `BroadcastChannel` — `BroadcastChannel` fans out to every same-origin
44
+ * context on the channel, including the driver's own listener and any
45
+ * sibling pods; `postMessage` to a specific target is the one-to-one
46
+ * delivery `send(name, {to, payload})` promises.
47
+ */
48
+
49
+ import {
50
+ POD_HOST_VERB,
51
+ POD_HOST_ERROR,
52
+ POD_HOST_EVENT_KIND,
53
+ POD_LANE,
54
+ POD_LIFECYCLE,
55
+ PodHostDriverError,
56
+ canTransition,
57
+ createHostEvent,
58
+ validatePodSpec,
59
+ } from './host-protocol.mjs'
60
+ import { POD_MESSAGE, createMessage } from './messages.mjs'
61
+ import { DEFAULT_DISCOVERY_CHANNEL, BROWSER_HOST_READY } from './browser-host-child.mjs'
62
+
63
+ export { DEFAULT_DISCOVERY_CHANNEL }
64
+
65
+ /** Verbs this driver actually serves — a strict subset of what the browser
66
+ * lane structurally allows (`POD_LANE_VERBS[POD_LANE.BROWSER]`); `exec` is
67
+ * lane-capable but not implemented here, see the module doc comment. */
68
+ const VERBS = Object.freeze([
69
+ POD_HOST_VERB.SPAWN, POD_HOST_VERB.STATUS, POD_HOST_VERB.SEND,
70
+ POD_HOST_VERB.DRAIN, POD_HOST_VERB.LIST,
71
+ ])
72
+
73
+ const SPAWN_KINDS = Object.freeze(['iframe', 'window', 'worker'])
74
+
75
+ /** Default budget for `spawn()`'s wait on the child's `browser-host:ready`. */
76
+ const DEFAULT_SPAWN_TIMEOUT_MS = 5000
77
+
78
+ /**
79
+ * Build the child page URL, encoding `name` as both the primary channel
80
+ * (`g.name` / `window.open` name / `Worker`'s `name` option, set by the
81
+ * caller) AND a `#name=…` hash fallback `browser-host-child.mjs`'s
82
+ * `readPodName()` also understands.
83
+ * @param {string} podUrl
84
+ * @param {string} name
85
+ * @returns {string}
86
+ */
87
+ function buildChildUrl(podUrl, name) {
88
+ const sep = podUrl.includes('#') ? '&' : '#'
89
+ return `${podUrl}${sep}name=${encodeURIComponent(name)}`
90
+ }
91
+
92
+ /**
93
+ * Build a `PodHostDriver` that spawns and controls browser-lane pods from
94
+ * inside a page, using only platform primitives (`iframe`, `window.open`,
95
+ * `Worker`, `BroadcastChannel`, `postMessage`).
96
+ *
97
+ * @param {object} opts
98
+ * @param {object} [opts.globalThis=globalThis] - The hosting page/worker's
99
+ * global. Override for testing with a fake `document`/`open`/`Worker`.
100
+ * @param {string} opts.podUrl - The URL of the page every spawned pod
101
+ * boots (expected to call `bootHostedPod()` from `browser-host-child.mjs`).
102
+ * @param {string} [opts.channel=DEFAULT_DISCOVERY_CHANNEL] - BroadcastChannel
103
+ * name shared with spawned children.
104
+ * @param {'iframe'|'window'|'worker'} [opts.spawnKind='iframe'] - How to
105
+ * create a child: an `<iframe>`, a `window.open()` popup, or a dedicated
106
+ * `Worker`.
107
+ * @param {number} [opts.timeoutMs=5000] - How long `spawn()` waits for the
108
+ * child's readiness announcement before rejecting `ETIMEDOUT`.
109
+ * @param {number} [opts.childHandshakeTimeoutMs] - Forwarded as the booted
110
+ * child's `handshakeTimeout` (only meaningful if the test harness also
111
+ * calls `bootHostedPod()` with it; a real page reads its own default).
112
+ * @param {number} [opts.childDiscoveryTimeoutMs] - Same, for `discoveryTimeout`.
113
+ * @param {Function} [opts.BCConstructor] - `BroadcastChannel` constructor
114
+ * override, for testing with a fake bus. Defaults to `globalThis.BroadcastChannel`.
115
+ * @param {string} [opts.driverId='browser-host-driver'] - The `from` this
116
+ * driver stamps on messages it sends via `send()`.
117
+ * @returns {import('./host-protocol.mjs').PodHostDriver}
118
+ */
119
+ export function createInPageDriver({
120
+ globalThis: g = globalThis,
121
+ podUrl,
122
+ channel = DEFAULT_DISCOVERY_CHANNEL,
123
+ spawnKind = 'iframe',
124
+ timeoutMs = DEFAULT_SPAWN_TIMEOUT_MS,
125
+ childHandshakeTimeoutMs,
126
+ childDiscoveryTimeoutMs,
127
+ BCConstructor,
128
+ driverId = 'browser-host-driver',
129
+ } = {}) {
130
+ if (!podUrl || typeof podUrl !== 'string') {
131
+ throw new Error('createInPageDriver: podUrl is required')
132
+ }
133
+ if (!SPAWN_KINDS.includes(spawnKind)) {
134
+ throw new Error(`createInPageDriver: spawnKind must be one of ${SPAWN_KINDS.join('|')}`)
135
+ }
136
+ const BC = BCConstructor || g.BroadcastChannel
137
+ if (typeof BC !== 'function') {
138
+ throw new Error('createInPageDriver: no BroadcastChannel available — pass opts.BCConstructor for a fake')
139
+ }
140
+
141
+ /** @type {Map<string, object>} name -> pod record */
142
+ const pods = new Map()
143
+ /** @type {Set<(event: object) => void>} */
144
+ const listeners = new Set()
145
+
146
+ /** @param {object} event */
147
+ function emit(event) {
148
+ for (const fn of [...listeners]) {
149
+ try { fn(event) } catch { /* a throwing subscriber never breaks the driver */ }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * @param {object} record
155
+ * @param {string} to
156
+ * @param {string} reason
157
+ */
158
+ function transition(record, to, reason) {
159
+ if (!canTransition(record.state, to)) {
160
+ throw new PodHostDriverError(
161
+ POD_HOST_ERROR.EBUSY,
162
+ `pod '${record.name}' cannot go ${record.state} -> ${to}`,
163
+ { name: record.name, from: record.state, to },
164
+ )
165
+ }
166
+ const from = record.state
167
+ record.state = to
168
+ record.updatedAt = Date.now()
169
+ emit(createHostEvent(POD_HOST_EVENT_KIND.LIFECYCLE, {
170
+ name: record.name, lane: POD_LANE.BROWSER, from, to, reason,
171
+ }))
172
+ }
173
+
174
+ // A single listening channel, opened up front (not lazily on first
175
+ // spawn) so there is no race between "child announces ready" and "driver
176
+ // starts listening" -- the channel is live before any child can exist.
177
+ const listenChannel = new BC(channel)
178
+ listenChannel.onmessage = (event) => handleIncoming(event?.data)
179
+
180
+ /** @param {*} data */
181
+ function handleIncoming(data) {
182
+ if (!data || data.type !== POD_MESSAGE) return
183
+ const payload = data.payload
184
+ if (!payload || payload.kind !== BROWSER_HOST_READY) return
185
+ const record = pods.get(payload.name)
186
+ if (!record || record.state === POD_LIFECYCLE.GONE) return
187
+ record.podId = data.from ?? payload.podId ?? null
188
+ if (record.state === POD_LIFECYCLE.BOOTING) transition(record, POD_LIFECYCLE.REGISTERED, 'child-ready')
189
+ if (record.readyWaiters) {
190
+ for (const resolve of record.readyWaiters) resolve()
191
+ record.readyWaiters.clear()
192
+ }
193
+ }
194
+
195
+ /**
196
+ * @param {object} record
197
+ * @param {number} ms
198
+ * @returns {Promise<void>}
199
+ */
200
+ function waitForReady(record, ms) {
201
+ if (record.state === POD_LIFECYCLE.REGISTERED) return Promise.resolve()
202
+ return new Promise((resolve, reject) => {
203
+ const timer = setTimeout(() => {
204
+ record.readyWaiters.delete(onReady)
205
+ reject(new PodHostDriverError(
206
+ POD_HOST_ERROR.ETIMEDOUT,
207
+ `pod '${record.name}' did not announce '${BROWSER_HOST_READY}' within ${ms}ms`,
208
+ { name: record.name },
209
+ ))
210
+ }, ms)
211
+ function onReady() {
212
+ clearTimeout(timer)
213
+ resolve()
214
+ }
215
+ record.readyWaiters.add(onReady)
216
+ })
217
+ }
218
+
219
+ /**
220
+ * @param {string} verb
221
+ */
222
+ function requireVerb(verb) {
223
+ if (VERBS.includes(verb)) return
224
+ throw new PodHostDriverError(
225
+ POD_HOST_ERROR.ENOTSUP,
226
+ `in-page driver (lane 'browser') does not implement '${verb}'`,
227
+ { verb, lane: POD_LANE.BROWSER },
228
+ )
229
+ }
230
+
231
+ /** @param {string} name @returns {object} */
232
+ function require_(name) {
233
+ const record = pods.get(name)
234
+ if (!record) throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `no pod named '${name}'`, { name })
235
+ return record
236
+ }
237
+
238
+ /** @param {string} name @returns {object} */
239
+ function requireLive(name) {
240
+ const record = require_(name)
241
+ if (record.state === POD_LIFECYCLE.GONE) {
242
+ throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `pod '${name}' is gone`, { name })
243
+ }
244
+ return record
245
+ }
246
+
247
+ /** @param {object} record @returns {import('./host-protocol.mjs').PodHostStatus} */
248
+ function snapshotOf(record) {
249
+ return {
250
+ name: record.name,
251
+ lane: POD_LANE.BROWSER,
252
+ state: record.state,
253
+ spec: record.spec,
254
+ createdAt: record.createdAt,
255
+ updatedAt: record.updatedAt,
256
+ podId: record.podId,
257
+ kind: record.kind,
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Create the child browsing context for `spawnKind`, wired to `url`.
263
+ * @param {string} name
264
+ * @param {string} url
265
+ * @returns {{kind: string, ref: *}}
266
+ */
267
+ function createChild(name, url) {
268
+ if (spawnKind === 'iframe') {
269
+ if (!g.document || typeof g.document.createElement !== 'function') {
270
+ throw new Error('createInPageDriver: globalThis.document.createElement is required for spawnKind "iframe"')
271
+ }
272
+ const iframe = g.document.createElement('iframe')
273
+ iframe.name = name
274
+ // Insert before setting `src`: some engines defer the initial
275
+ // navigation of a detached iframe, so appending first is the more
276
+ // portable order even though the fake harness in tests would accept
277
+ // either.
278
+ const parent = g.document.body || g.document
279
+ parent.appendChild(iframe)
280
+ iframe.src = url
281
+ return { kind: 'iframe', ref: iframe }
282
+ }
283
+ if (spawnKind === 'window') {
284
+ if (typeof g.open !== 'function') {
285
+ throw new Error('createInPageDriver: globalThis.open is required for spawnKind "window"')
286
+ }
287
+ const win = g.open(url, name)
288
+ if (!win) {
289
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, `window.open('${url}', '${name}') returned no window (popup blocked?)`, { name })
290
+ }
291
+ return { kind: 'window', ref: win }
292
+ }
293
+ // worker
294
+ if (typeof g.Worker !== 'function') {
295
+ throw new Error('createInPageDriver: globalThis.Worker is required for spawnKind "worker"')
296
+ }
297
+ const worker = new g.Worker(url, { name, type: 'module' })
298
+ return { kind: 'worker', ref: worker }
299
+ }
300
+
301
+ /** @param {object} handle */
302
+ function destroyChild(handle) {
303
+ if (!handle) return
304
+ if (handle.kind === 'iframe') {
305
+ const el = handle.ref
306
+ if (typeof el.remove === 'function') el.remove()
307
+ else if (el.parentNode && typeof el.parentNode.removeChild === 'function') el.parentNode.removeChild(el)
308
+ } else if (handle.kind === 'window') {
309
+ if (typeof handle.ref.close === 'function') handle.ref.close()
310
+ } else if (handle.kind === 'worker') {
311
+ if (typeof handle.ref.terminate === 'function') handle.ref.terminate()
312
+ }
313
+ }
314
+
315
+ return {
316
+ lane: POD_LANE.BROWSER,
317
+
318
+ capabilities() {
319
+ return { verbs: [...VERBS] }
320
+ },
321
+
322
+ onEvent(fn) {
323
+ if (typeof fn !== 'function') return () => {}
324
+ listeners.add(fn)
325
+ return () => { listeners.delete(fn) }
326
+ },
327
+
328
+ async spawn(spec) {
329
+ requireVerb(POD_HOST_VERB.SPAWN)
330
+ const validated = validatePodSpec(spec)
331
+ if (!validated.ok) {
332
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, validated.errors.join('; '), { errors: validated.errors })
333
+ }
334
+ const value = validated.value
335
+ if (value.lane !== POD_LANE.BROWSER) {
336
+ throw new PodHostDriverError(
337
+ POD_HOST_ERROR.ELANE,
338
+ `this host runs the '${POD_LANE.BROWSER}' lane, not '${value.lane}'`,
339
+ { lane: value.lane },
340
+ )
341
+ }
342
+ const existing = pods.get(value.name)
343
+ if (existing && existing.state !== POD_LIFECYCLE.GONE) {
344
+ throw new PodHostDriverError(POD_HOST_ERROR.EEXIST, `pod '${value.name}' already exists`, { name: value.name })
345
+ }
346
+
347
+ const now = Date.now()
348
+ const record = {
349
+ name: value.name,
350
+ spec: value,
351
+ state: POD_LIFECYCLE.COLD,
352
+ createdAt: now,
353
+ updatedAt: now,
354
+ podId: null,
355
+ kind: spawnKind,
356
+ handle: null,
357
+ readyWaiters: new Set(),
358
+ }
359
+ pods.set(value.name, record)
360
+ transition(record, POD_LIFECYCLE.BOOTING, 'spawn')
361
+
362
+ const url = buildChildUrl(podUrl, value.name)
363
+ try {
364
+ record.handle = createChild(value.name, url)
365
+ } catch (err) {
366
+ record.state = POD_LIFECYCLE.GONE
367
+ if (err instanceof PodHostDriverError) throw err
368
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, `failed to spawn '${value.name}': ${err.message}`, { name: value.name })
369
+ }
370
+
371
+ await waitForReady(record, timeoutMs)
372
+ return snapshotOf(record)
373
+ },
374
+
375
+ async status(name) {
376
+ requireVerb(POD_HOST_VERB.STATUS)
377
+ return snapshotOf(require_(name))
378
+ },
379
+
380
+ async send(name, msg) {
381
+ requireVerb(POD_HOST_VERB.SEND)
382
+ const record = requireLive(name)
383
+ if (!record.handle) {
384
+ throw new PodHostDriverError(POD_HOST_ERROR.EBUSY, `pod '${name}' has no live browsing context`, { name })
385
+ }
386
+ const envelope = createMessage({ from: driverId, to: record.podId ?? '*', payload: msg?.payload ?? null })
387
+ const target = record.handle.kind === 'iframe' ? record.handle.ref.contentWindow : record.handle.ref
388
+ if (!target || typeof target.postMessage !== 'function') {
389
+ throw new PodHostDriverError(POD_HOST_ERROR.EBUSY, `pod '${name}' has no reachable postMessage target`, { name })
390
+ }
391
+ if (record.handle.kind === 'worker') target.postMessage(envelope)
392
+ else target.postMessage(envelope, '*')
393
+ return { delivered: true, to: msg?.to ?? null }
394
+ },
395
+
396
+ // `exec` is lane-capable on 'browser' (it means "evaluate script in the
397
+ // page" -- see host-protocol.mjs's POD_LANE_VERBS doc comment) but this
398
+ // driver never implements it: a parent tab has no safe way to evaluate
399
+ // code in a cross-origin child it spawned. Use the CDP or extension
400
+ // driver, which run with an operator's out-of-band control instead of
401
+ // borrowing the hosted page's own (nonexistent) trust boundary.
402
+ async exec() {
403
+ requireVerb(POD_HOST_VERB.EXEC) // always throws -- EXEC is not in VERBS
404
+ },
405
+
406
+ // A durable soft-snapshot (serialize reachable pod state to IndexedDB,
407
+ // restore by re-spawning and replaying it) is a plausible follow-up,
408
+ // not implemented in this wave.
409
+ async snapshot() {
410
+ requireVerb(POD_HOST_VERB.SNAPSHOT)
411
+ },
412
+
413
+ async restore() {
414
+ requireVerb(POD_HOST_VERB.RESTORE)
415
+ },
416
+
417
+ async drain(name, opts = {}) {
418
+ requireVerb(POD_HOST_VERB.DRAIN)
419
+ const record = require_(name)
420
+ if (record.state !== POD_LIFECYCLE.GONE) {
421
+ if (record.state !== POD_LIFECYCLE.DRAINING) transition(record, POD_LIFECYCLE.DRAINING, 'drain')
422
+ destroyChild(record.handle)
423
+ record.handle = null
424
+ transition(record, POD_LIFECYCLE.GONE, 'drain')
425
+ }
426
+ emit(createHostEvent(POD_HOST_EVENT_KIND.EXIT, {
427
+ name, lane: POD_LANE.BROWSER, code: 0, cascade: opts.cascade === true,
428
+ }))
429
+ return snapshotOf(record)
430
+ },
431
+
432
+ async list() {
433
+ requireVerb(POD_HOST_VERB.LIST)
434
+ return [...pods.values()].map((record) => snapshotOf(record))
435
+ },
436
+
437
+ // Not part of the `PodHostDriver` typedef -- a test/teardown convenience
438
+ // so nothing keeps a (real) BroadcastChannel, and therefore the event
439
+ // loop, alive after a suite is done with this driver.
440
+ close() {
441
+ try { listenChannel.close() } catch { /* already closed */ }
442
+ listeners.clear()
443
+ },
444
+ }
445
+ }
@@ -10,6 +10,15 @@
10
10
  /**
11
11
  * Detect the pod kind for the current execution context.
12
12
  *
13
+ * Returns `'server'` whenever there is no `window`/`document` and no worker
14
+ * global scope on `g` — plain Node.js, and a Firecracker microVM guest
15
+ * running Node. Inside workerd / Cloudflare Workers the global satisfies
16
+ * `instanceof ServiceWorkerGlobalScope`, so an isolate-hosted pod reports
17
+ * `'service-worker'` (measured in `spikes/isolate-pod-host`), not
18
+ * `'server'`. Hosted-pod code must treat both as "not a browser window"
19
+ * rather than branching on `'server'` alone. See `docs/hosted-pods.md` at
20
+ * the monorepo root.
21
+ *
13
22
  * @param {object} [g=globalThis] - The global scope to inspect
14
23
  * @returns {PodKind}
15
24
  */