@johnhenry/browsermesh-apps 0.1.0 → 0.2.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.
package/src/gpu.mjs CHANGED
@@ -12,11 +12,34 @@
12
12
  *
13
13
  * No browser-only imports at module level.
14
14
  *
15
+ * ## GPU compute: real, optional, and safe to omit
16
+ *
17
+ * `GradientAggregator.aggregateGPU(device)` (see below) dispatches a real
18
+ * WGSL compute shader (`./gpu-kernel.mjs`) when given a usable `GPUDevice`.
19
+ * It is entirely optional: pass no device (or a device whose storage-buffer
20
+ * limits are too small for the flattened gradient buffer) and it falls back
21
+ * to the existing synchronous `aggregate()` CPU path, wrapped in a resolved
22
+ * Promise. Nothing in this package requires WebGPU to be present -- the
23
+ * fallback is a first-class, always-tested code path, not a stub.
24
+ *
25
+ * Always-on coverage of the fallback branch lives in `test/gpu.test.mjs`
26
+ * and needs no GPU. Coverage of the real shader against actual WebGPU
27
+ * hardware/drivers is gated behind an optional devDependency and lives in
28
+ * `test/gpu-real-webgpu/kernel.test.mjs` (run via `npm run test:real-gpu`).
29
+ * It deliberately does NOT run in CI (see `.github/workflows/ci.yml`):
30
+ * verified correct on real hardware and on a local headless-Linux
31
+ * approximation, but a real CI run against this repo's actual
32
+ * GitHub-hosted runner hit a native crash inside the `webgpu` binding
33
+ * itself (a pthread mutex assertion failure during `mapAsync()`) that no
34
+ * JS-level handling can turn into a clean skip or failure -- see that test
35
+ * file and this package's README for the full finding.
36
+ *
15
37
  * Run tests:
16
38
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-gpu.test.mjs
17
39
  */
18
40
 
19
41
  import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
42
+ import { runAggregateKernel } from './gpu-kernel.mjs'
20
43
 
21
44
  // ---------------------------------------------------------------------------
22
45
  // Wire Constants — imported from canonical registry
@@ -421,6 +444,46 @@ export class GradientAggregator {
421
444
  return result
422
445
  }
423
446
 
447
+ /**
448
+ * Aggregate submitted gradients on the GPU when possible, falling back to
449
+ * the synchronous `aggregate()` CPU path otherwise. The fallback covers:
450
+ * - no `device` supplied (falsy),
451
+ * - zero submitted gradients,
452
+ * - a flattened gradient buffer (`shards * vectorLength * 4` bytes)
453
+ * that would exceed `device.limits.maxStorageBufferBindingSize`.
454
+ * In every fallback case this calls the real, unmodified `aggregate()`
455
+ * and wraps its result in a resolved Promise -- the fallback is a real
456
+ * code path (tested in test/gpu.test.mjs), not a placeholder.
457
+ * @param {object} [device] GPUDevice
458
+ * @returns {Promise<number[]>} Aggregated gradient vector
459
+ */
460
+ async aggregateGPU(device) {
461
+ const entries = [...this.#gradients.entries()]
462
+ if (!device || entries.length === 0) {
463
+ return this.aggregate()
464
+ }
465
+
466
+ const vectorLength = entries[0][1].length
467
+ const numShards = entries.length
468
+ const bufferBytes = numShards * vectorLength * 4
469
+ const maxBufferBytes = device.limits?.maxStorageBufferBindingSize
470
+ if (typeof maxBufferBytes === 'number' && bufferBytes > maxBufferBytes) {
471
+ return this.aggregate()
472
+ }
473
+
474
+ const useWeights = this.strategy === 'federated_avg'
475
+ const gradients = new Array(numShards * vectorLength)
476
+ const weights = new Array(numShards)
477
+ entries.forEach(([shardId, grads], shardIndex) => {
478
+ weights[shardIndex] = this.#weights.get(shardId) || 1
479
+ for (let i = 0; i < vectorLength; i++) {
480
+ gradients[shardIndex * vectorLength + i] = grads[i]
481
+ }
482
+ })
483
+
484
+ return runAggregateKernel(device, { gradients, weights, useWeights })
485
+ }
486
+
424
487
  /**
425
488
  * Clear all stored gradients and weights.
426
489
  */
@@ -453,17 +516,25 @@ export class TrainingOrchestrator {
453
516
  /** @type {Map<string, GpuCapability>} podId → capability */
454
517
  #peerCapabilities = new Map()
455
518
 
519
+ /** @type {object|null} GPUDevice, used by handleGradientPush's aggregateGPU() call */
520
+ #gpuDevice
521
+
456
522
  /**
457
523
  * @param {object} opts
458
524
  * @param {Function} opts.sendFn Send function: (targetId, msg) => {}
459
525
  * @param {GpuCapability} [opts.localCapability] Local GPU capability
526
+ * @param {object} [opts.gpuDevice] Optional GPUDevice. When supplied,
527
+ * `handleGradientPush()` aggregates on the GPU via
528
+ * `GradientAggregator.aggregateGPU()`; when omitted, aggregation runs on
529
+ * the CPU (aggregateGPU()'s own no-device fallback).
460
530
  */
461
- constructor({ sendFn, localCapability }) {
531
+ constructor({ sendFn, localCapability, gpuDevice }) {
462
532
  if (typeof sendFn !== 'function') {
463
533
  throw new Error('sendFn is required and must be a function')
464
534
  }
465
535
  this.#sendFn = sendFn
466
536
  this.#localCapability = localCapability || null
537
+ this.#gpuDevice = gpuDevice || null
467
538
  }
468
539
 
469
540
  /**
@@ -523,6 +594,7 @@ export class TrainingOrchestrator {
523
594
  shards: shardMap,
524
595
  aggregator,
525
596
  status: 'running',
597
+ result: null,
526
598
  })
527
599
 
528
600
  // Send shard assignments to peers
@@ -583,12 +655,17 @@ export class TrainingOrchestrator {
583
655
  }
584
656
 
585
657
  /**
586
- * Handle a gradient push from a shard peer.
658
+ * Handle a gradient push from a shard peer. Once the job's aggregator has
659
+ * received a gradient from every shard, actually runs aggregation
660
+ * (GPU-accelerated when a `gpuDevice` was supplied to the constructor,
661
+ * otherwise the CPU path via `aggregateGPU()`'s own fallback) and stores
662
+ * the result on the job record, retrievable via `getJobResult()`.
587
663
  * @param {string} fromId
588
664
  * @param {string} shardId
589
665
  * @param {number[]} gradients
666
+ * @returns {Promise<void>}
590
667
  */
591
- handleGradientPush(fromId, shardId, gradients) {
668
+ async handleGradientPush(fromId, shardId, gradients) {
592
669
  // Find the job that contains this shard
593
670
  for (const [jobId, job] of this.#jobs) {
594
671
  if (job.shards.has(shardId)) {
@@ -597,6 +674,7 @@ export class TrainingOrchestrator {
597
674
  job.aggregator.submit(shardId, gradients)
598
675
 
599
676
  if (job.aggregator.isReady(job.shards.size)) {
677
+ job.result = await job.aggregator.aggregateGPU(this.#gpuDevice)
600
678
  job.status = 'aggregated'
601
679
  }
602
680
  return
@@ -646,7 +724,7 @@ export class TrainingOrchestrator {
646
724
  getJobStatus(jobId) {
647
725
  const job = this.#jobs.get(jobId)
648
726
  if (!job) {
649
- return { jobId, status: 'not_found', shardCount: 0, completedShards: 0, aggregated: false }
727
+ return { jobId, status: 'not_found', shardCount: 0, completedShards: 0, aggregated: false, result: null }
650
728
  }
651
729
 
652
730
  let completedShards = 0
@@ -660,9 +738,21 @@ export class TrainingOrchestrator {
660
738
  shardCount: job.shards.size,
661
739
  completedShards,
662
740
  aggregated: job.status === 'aggregated',
741
+ result: job.result ?? null,
663
742
  }
664
743
  }
665
744
 
745
+ /**
746
+ * Get the aggregated result for a job, or `null` if the job doesn't
747
+ * exist yet or hasn't finished aggregating.
748
+ * @param {string} jobId
749
+ * @returns {number[]|null}
750
+ */
751
+ getJobResult(jobId) {
752
+ const job = this.#jobs.get(jobId)
753
+ return job ? (job.result ?? null) : null
754
+ }
755
+
666
756
  /**
667
757
  * Cancel a training job.
668
758
  * @param {string} jobId
@@ -699,11 +789,15 @@ export class TrainingOrchestrator {
699
789
  }
700
790
 
701
791
  /**
702
- * Main message handler — dispatches based on msg.type.
792
+ * Main message handler — dispatches based on msg.type. Async because the
793
+ * GPU_GRADIENT_PUSH branch awaits `handleGradientPush()` (which itself
794
+ * awaits GPU/CPU aggregation once a job's shards are all in) — callers
795
+ * must `await` this rather than fire-and-forget it.
703
796
  * @param {string} fromId
704
797
  * @param {object} msg
798
+ * @returns {Promise<void>}
705
799
  */
706
- handleMessage(fromId, msg) {
800
+ async handleMessage(fromId, msg) {
707
801
  switch (msg.type) {
708
802
  case GPU_PROBE:
709
803
  // Respond with local capability
@@ -721,7 +815,7 @@ export class TrainingOrchestrator {
721
815
  break
722
816
 
723
817
  case GPU_GRADIENT_PUSH:
724
- this.handleGradientPush(fromId, msg.shardId, msg.gradients)
818
+ await this.handleGradientPush(fromId, msg.shardId, msg.gradients)
725
819
  break
726
820
 
727
821
  case GPU_TRAIN_CONTROL:
package/src/index.mjs CHANGED
@@ -23,6 +23,13 @@ export * from './peer-files.mjs';
23
23
  export * from './peer-health.mjs';
24
24
  export * from './peer-ipfs.mjs';
25
25
  export * from './peer-node.mjs';
26
+ export * from './signaling.mjs';
27
+ export * from './webrtc-negotiator.mjs';
28
+ export * from './mesh-bootstrap.mjs';
29
+ export * from './mesh-sync.mjs';
30
+ export * from './kernel-mesh.mjs';
31
+ export * from './mesh-relay-host.mjs';
32
+ export * from './mesh-relay-backend.mjs';
26
33
  export * from './peer-payments.mjs';
27
34
  export * from './peer-registry.mjs';
28
35
  export * from './peer-routing.mjs';
@@ -0,0 +1,56 @@
1
+ /**
2
+ * kernel-mesh.mjs -- composition glue: build a Kernel with a real mesh
3
+ * capability backed by a connected PeerNode (Phase 4 of the integration plan).
4
+ *
5
+ * `browsermesh-kernel/src/caps.mjs`'s `buildCaps()` previously set `caps.mesh`
6
+ * to a bare `true` marker -- nothing real backed it. `Kernel` now accepts an
7
+ * optional `mesh` constructor option and, when present, hands a tenant
8
+ * granted `KERNEL_CAP.MESH` a scoped `{ send, onReceive }` view instead of the
9
+ * marker -- every `send`/`onReceive` delivery gated by the mesh provider's
10
+ * `registry.checkAccess(peerId, 'mesh', 'send'|'receive')`, so a tenant can
11
+ * only reach peers the registry has actually authorized, not the raw
12
+ * `PeerNode` API (no `connectToPeer`, `addPeer`, `discover`, etc.).
13
+ *
14
+ * **Architectural call (documented here, not silently picked): the wiring
15
+ * lives in `browsermesh-apps`, not `browsermesh-kernel`.** `Kernel`'s `mesh`
16
+ * option is a duck-typed interface (`{ sendTo, onIncomingData, registry:
17
+ * { checkAccess } }`) -- `browsermesh-kernel` does NOT import this package,
18
+ * or any other `@johnhenry/browsermesh-*` package, to satisfy it (confirmed:
19
+ * `packages/browsermesh-kernel/package.json` still declares zero runtime
20
+ * dependencies). Kernel gaining a real dependency on `browsermesh-apps` would
21
+ * invert the family's layering -- `-kernel` is the innermost primitive
22
+ * package everything else composes on top of; `-apps` already depends on
23
+ * `-core`/`-discovery`/`-transport`/`-sync` as the top-of-stack composition
24
+ * layer (see `mesh-bootstrap.mjs`). So `-apps` gains a new peerDependency on
25
+ * `-kernel` instead, and this module -- not kernel.mjs/caps.mjs -- is where a
26
+ * real `PeerNode` gets handed to a `Kernel` constructor. `PeerNode` already
27
+ * satisfies the duck-typed shape kernel expects (`sendTo(pubKey, data)`,
28
+ * `onIncomingData(cb)`, `.registry.checkAccess(pubKey, resource, action)`)
29
+ * with no adapter code needed -- this module's only real job is making that
30
+ * dependency direction, and the one-import convenience, explicit.
31
+ *
32
+ * No browser-only imports at module level.
33
+ */
34
+
35
+ import { Kernel } from '@johnhenry/browsermesh-kernel'
36
+
37
+ /**
38
+ * Construct a Kernel whose MESH capability is backed by a real, connected
39
+ * `PeerNode`. Any tenant created via the returned kernel with
40
+ * `KERNEL_CAP.MESH` granted gets `caps.mesh` as a `{ send, onReceive }` view
41
+ * scoped by `peerNode.registry.checkAccess()` (see `Kernel#meshFor()` in
42
+ * `browsermesh-kernel/src/kernel.mjs` for the enforcement itself).
43
+ *
44
+ * @param {object} [opts]
45
+ * @param {import('./peer-node.mjs').PeerNode} [opts.peerNode] - A real,
46
+ * booted `PeerNode` (e.g. from `createMeshNode()` in mesh-bootstrap.mjs).
47
+ * Omit to get a kernel with no real mesh backing -- `caps.mesh` then falls
48
+ * back to the pre-Phase-4 bare boolean marker, matching a plain
49
+ * `new Kernel()`.
50
+ * @param {object} [opts.kernelOpts] - Passed through to the Kernel
51
+ * constructor (`clock`, `rng`, `tracerOpts`, `loggerOpts`, `resourceOpts`).
52
+ * @returns {Kernel}
53
+ */
54
+ export function createMeshKernel({ peerNode, kernelOpts = {} } = {}) {
55
+ return new Kernel({ ...kernelOpts, mesh: peerNode || null })
56
+ }
@@ -0,0 +1,362 @@
1
+ /**
2
+ * mesh-bootstrap.mjs -- composition root for a real, connected PeerNode.
3
+ *
4
+ * This is the file the rest of the audit found missing: nothing anywhere in
5
+ * the repo instantiates `PeerNode` with real `IdentityWallet` /
6
+ * `PeerRegistry` / `DiscoveryManager` / `MeshTransportNegotiator`
7
+ * implementations -- only hand-rolled test mocks. `createMeshNode()` does
8
+ * exactly that wiring, using:
9
+ * - `IdentityWallet` + `MeshIdentityManager` from `@johnhenry/browsermesh-core`
10
+ * for a real Ed25519 identity.
11
+ * - `PeerRegistry` (this package) wired to real `MeshPeerManager` /
12
+ * `TrustGraph` / `MeshACL` from `@johnhenry/browsermesh-core`.
13
+ * - `DiscoveryManager` from `@johnhenry/browsermesh-discovery`, with
14
+ * whatever `DiscoveryStrategy` instances the caller supplies (default:
15
+ * `BroadcastChannelStrategy`, browser-only -- see below).
16
+ * - `MeshTransportNegotiator` + `WebRTCMeshManager` from
17
+ * `@johnhenry/browsermesh-transport`, wired through this package's own
18
+ * `signaling.mjs` / `webrtc-negotiator.mjs`.
19
+ *
20
+ * **Discovery is browser-only by default.** `BroadcastChannelStrategy`
21
+ * requires a global `BroadcastChannel`, which Node does not have. Rather
22
+ * than inventing a new Node-only discovery mechanism, callers running
23
+ * outside a browser (tests, this package's own integration suite) pass
24
+ * `discoveryStrategies` explicitly -- `ManualStrategy` from
25
+ * `@johnhenry/browsermesh-discovery` is the existing, real, Node-safe
26
+ * strategy that fits (peers are added explicitly rather than found via a
27
+ * browser API), the same way the existing Pod example
28
+ * (`examples/02-two-pods-discover-and-message.mjs`) injects an
29
+ * `EventEmitterTransport` instead of relying on a browser transport.
30
+ *
31
+ * **Signaling has no default at all** -- `signalingTransport` must always be
32
+ * supplied. There is no in-repo precedent for a "default" signaling bus the
33
+ * way there is for discovery, and guessing one (e.g. silently reaching for
34
+ * `BroadcastChannel`) would hide a real infrastructure decision (which bus
35
+ * carries offer/answer/ICE traffic) behind a default that only works in one
36
+ * environment. `createBroadcastChannelSignalingTransport()` (signaling.mjs)
37
+ * is the ready-made browser option; tests supply a Node-safe bus (see
38
+ * `test/mesh-bootstrap.test.mjs`).
39
+ *
40
+ * **CRDT sync is opt-in via `{ enableSync: true }`** (Phase 3). When set,
41
+ * this function also builds a `MeshSyncEngine` (`@johnhenry/browsermesh-sync`)
42
+ * -- durable `IndexedDBSyncStorage` by default -- and wires it to the
43
+ * returned `PeerNode` via `mesh-sync.mjs`'s `createMeshSync()`, attached as
44
+ * `node.sync` (a `MeshSyncBinding`). This keeps `createMeshNode()` the one
45
+ * obvious place to get a fully-wired mesh node, while leaving direct
46
+ * `createMeshSync({ node })` available for callers who want to construct
47
+ * the binding themselves (e.g. a custom storage adapter per document type).
48
+ *
49
+ * **Mesh relay is opt-in via `{ enableRelayHost: true, relayHostNetwork }`**
50
+ * (Phase 8). When set, this function builds a `MeshRelayHost`
51
+ * (`mesh-relay-host.mjs`) bridging inbound, `PeerRegistry`-authorized relay
52
+ * connections into `relayHostNetwork` (a caller-supplied `VirtualNetwork`,
53
+ * e.g. one with a `GatewayBackend` reaching a real local service), attached
54
+ * as `node.relayHost`. This is the "share my `VirtualNetwork` access with
55
+ * specific peers" side; the client side is `mesh-relay-backend.mjs`'s
56
+ * `MeshRelayBackend`, constructed directly (not via this function) and
57
+ * registered on the *client's own* `VirtualNetwork`.
58
+ *
59
+ * No browser-only imports at module level.
60
+ */
61
+
62
+ import {
63
+ IdentityWallet,
64
+ MeshIdentityManager,
65
+ MeshPeerManager,
66
+ TrustGraph,
67
+ MeshACL,
68
+ CapabilityValidator,
69
+ CapabilityToken,
70
+ } from '@johnhenry/browsermesh-core'
71
+ import {
72
+ DiscoveryManager,
73
+ DiscoveryRecord,
74
+ BroadcastChannelStrategy,
75
+ } from '@johnhenry/browsermesh-discovery'
76
+ import {
77
+ MeshTransportNegotiator,
78
+ WebRTCMeshManager,
79
+ mergeIceServers,
80
+ } from '@johnhenry/browsermesh-transport'
81
+
82
+ import { PeerNode } from './peer-node.mjs'
83
+ import { PeerRegistry } from './peer-registry.mjs'
84
+ import { MeshSignalingChannel } from './signaling.mjs'
85
+ import { createWebRTCTransportFactory } from './webrtc-negotiator.mjs'
86
+ import { createMeshSync } from './mesh-sync.mjs'
87
+ import { MeshRelayHost } from './mesh-relay-host.mjs'
88
+
89
+ /**
90
+ * Build and boot a real, WebRTC-capable `PeerNode`.
91
+ *
92
+ * Order of operations matters here: `DiscoveryManager` and `PeerRegistry`
93
+ * both need the local podId *before* they can be constructed, but
94
+ * `PeerNode.boot()` is what normally auto-creates the default identity. So
95
+ * this function creates the identity itself up front (via
96
+ * `wallet.createIdentity(label)`) and passes `{ skipDiscovery }` through to
97
+ * `boot()` for the rest of the lifecycle -- `boot()` sees an identity
98
+ * already exists and does not create a second one.
99
+ *
100
+ * @param {object} [options]
101
+ * @param {string} [options.label='default'] - Identity label.
102
+ * @param {import('@johnhenry/browsermesh-core').MeshIdentityManager} [options.identityManager]
103
+ * Pre-constructed identity manager (e.g. one backed by
104
+ * `IndexedDBIdentityStorage` for persistence). Defaults to a fresh
105
+ * in-memory `MeshIdentityManager`.
106
+ * @param {import('@johnhenry/browsermesh-core').MeshPeerManager} [options.peerManager]
107
+ * @param {import('@johnhenry/browsermesh-core').TrustGraph} [options.trustGraph]
108
+ * @param {import('@johnhenry/browsermesh-core').MeshACL} [options.acl]
109
+ * @param {import('@johnhenry/browsermesh-core').CapabilityValidator} [options.capabilityValidator]
110
+ * Backs `PeerRegistry.grantCapabilities()`/`.revokeCapabilities()`'s real
111
+ * token issuance/revocation (Phase 5). Defaults to a fresh real
112
+ * `CapabilityValidator` from `@johnhenry/browsermesh-core`.
113
+ * @param {import('@johnhenry/browsermesh-discovery').DiscoveryStrategy[]} [options.discoveryStrategies]
114
+ * Defaults to `[new BroadcastChannelStrategy(...)]`; throws if omitted
115
+ * and `BroadcastChannel` is not available (e.g. plain Node) -- pass e.g.
116
+ * `[new ManualStrategy()]` there instead.
117
+ * @param {string} [options.discoveryChannelName='mesh-discovery']
118
+ * @param {number} [options.announceInterval]
119
+ * @param {string[]} [options.capabilities] - Advertised in the local discovery record.
120
+ * @param {{send: Function, onMessage: Function, open?: Function, close?: Function}} options.signalingTransport
121
+ * Required. Injectable bus for WebRTC offer/answer/ICE relay -- see
122
+ * `signaling.mjs`.
123
+ * @param {RTCIceServer[]} [options.iceServers] - TURN (or additional STUN)
124
+ * servers, merged alongside `DEFAULT_ICE_SERVERS` via
125
+ * `@johnhenry/browsermesh-transport`'s `mergeIceServers()` -- the same
126
+ * extension point `webrtc.mjs` already documents, not reimplemented here.
127
+ * `DEFAULT_ICE_SERVERS` is empty (no ICE servers, for privacy -- see
128
+ * `webrtc.mjs`), so omitting this option preserves today's default
129
+ * behaviour exactly. An explicit `iceServers: []` is honoured as "no ICE
130
+ * servers at all" (used by this package's own real-peer test for a
131
+ * hermetic, loopback-only connection); a non-empty array is merged with
132
+ * the defaults and malformed entries are silently dropped. To combine a
133
+ * TURN server with the family's opt-in public STUN server, spread
134
+ * `PUBLIC_STUN_SERVERS` in yourself:
135
+ * ```js
136
+ * import { PUBLIC_STUN_SERVERS } from '@johnhenry/browsermesh-transport'
137
+ * import { createMeshNode } from '@johnhenry/browsermesh-apps'
138
+ *
139
+ * const node = await createMeshNode({
140
+ * signalingTransport,
141
+ * iceServers: [
142
+ * ...PUBLIC_STUN_SERVERS,
143
+ * { urls: 'turn:turn.example.com:3478', username: 'alice', credential: 's3cr3t' },
144
+ * ],
145
+ * })
146
+ * ```
147
+ * @param {import('./audit.mjs').AuditChain} [options.auditChain]
148
+ * @param {Function} [options.onLog]
149
+ * @param {boolean} [options.skipDiscovery=false] - Passed through to `PeerNode.boot()`.
150
+ * @param {boolean} [options.skipBoot=false] - Construct but don't boot (caller calls `node.boot()` itself).
151
+ * @param {boolean} [options.enableSync=false] - Build a `MeshSyncEngine` and
152
+ * wire it to the returned node as `node.sync` (see `mesh-sync.mjs`).
153
+ * @param {object} [options.syncStorage] - Storage adapter for the sync engine.
154
+ * Defaults to a durable `IndexedDBSyncStorage`; only used when `enableSync`.
155
+ * @param {string} [options.syncDbName] - dbName for the default `IndexedDBSyncStorage`.
156
+ * Defaults to `mesh-sync-${podId}`. Ignored if `syncStorage` is supplied.
157
+ * @param {string} [options.syncEnvelopeType] - Overrides the `envelope.type`
158
+ * the sync binding sends/routes on `PeerNode`'s dispatch bus (default `'mesh-sync'`).
159
+ * @param {boolean} [options.syncAutoLoad=true] - When `enableSync`, await
160
+ * `node.sync.load()` before returning so previously-persisted documents
161
+ * (e.g. from a prior page session, via `IndexedDBSyncStorage`) are already
162
+ * present -- the actual "a workspace survives a reload" behavior.
163
+ * @param {boolean} [options.enableRelayHost=false] - Build a `MeshRelayHost`
164
+ * (Phase 8) and wire it to the returned node as `node.relayHost`, so
165
+ * authorized mesh peers can relay through `options.relayHostNetwork` (e.g.
166
+ * a `VirtualNetwork` with a `GatewayBackend` reaching a real local
167
+ * service) via `PeerRegistry.grantCapabilities()`-gated
168
+ * `mesh-relay:<service>:connect` scopes. See `mesh-relay-host.mjs`.
169
+ * @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [options.relayHostNetwork]
170
+ * Required when `enableRelayHost` -- the `VirtualNetwork` `MeshRelayHost`
171
+ * bridges inbound relay connections into.
172
+ * @param {Object<string,string>} [options.relayHostServices] - Optional
173
+ * `{ name: targetAddress }` map of services to `exposeService()` on the
174
+ * new `MeshRelayHost` immediately (equivalent to calling
175
+ * `node.relayHost.exposeService(name, targetAddress)` for each entry).
176
+ * @param {string} [options.relayHostEnvelopeType] - Overrides the
177
+ * `envelope.type` the relay host routes/sends on `PeerNode`'s dispatch bus
178
+ * (default `'mesh-relay'`).
179
+ * @returns {Promise<PeerNode>} A booted (unless `skipBoot`) PeerNode, with
180
+ * `node.meshManager` (`WebRTCMeshManager`) and `node.signaling`
181
+ * (`MeshSignalingChannel`) attached for callers/tests that need lower-level
182
+ * access beyond what `PeerNode`'s own API exposes, `node.sync`
183
+ * (`MeshSyncBinding`, see `mesh-sync.mjs`) attached when `enableSync`, and
184
+ * `node.relayHost` (`MeshRelayHost`, see `mesh-relay-host.mjs`) attached
185
+ * when `enableRelayHost`.
186
+ */
187
+ export async function createMeshNode(options = {}) {
188
+ const {
189
+ label = 'default',
190
+ identityManager: providedIdentityManager,
191
+ peerManager,
192
+ trustGraph,
193
+ acl,
194
+ capabilityValidator,
195
+ discoveryStrategies,
196
+ discoveryChannelName = 'mesh-discovery',
197
+ announceInterval,
198
+ capabilities = [],
199
+ signalingTransport,
200
+ iceServers,
201
+ auditChain,
202
+ onLog = () => {},
203
+ skipDiscovery = false,
204
+ skipBoot = false,
205
+ enableSync = false,
206
+ syncStorage,
207
+ syncDbName,
208
+ syncEnvelopeType,
209
+ syncAutoLoad = true,
210
+ enableRelayHost = false,
211
+ relayHostNetwork,
212
+ relayHostServices,
213
+ relayHostEnvelopeType,
214
+ } = options
215
+
216
+ if (!signalingTransport) {
217
+ throw new Error(
218
+ 'createMeshNode: options.signalingTransport is required (an injectable ' +
219
+ 'bidirectional bus for WebRTC offer/answer/ICE relay -- see signaling.mjs)',
220
+ )
221
+ }
222
+
223
+ // -- Identity ---------------------------------------------------------
224
+ const identityManager = providedIdentityManager || new MeshIdentityManager({ onLog })
225
+ const wallet = new IdentityWallet({ identityManager, onLog })
226
+ const { podId } = await wallet.createIdentity(label)
227
+
228
+ // -- Registry (peers + trust + ACL + capability tokens) -----------------
229
+ // capabilityValidator/tokenFactory back Phase 5's real granting/revocation
230
+ // path (see peer-registry.mjs's grantCapabilities()/revokeCapabilities()/
231
+ // checkAccess()) with the genuine, tested `-core` classes rather than
232
+ // PeerRegistry's in-package duck-typed defaults.
233
+ const registry = new PeerRegistry({
234
+ localPodId: podId,
235
+ peerManager: peerManager || new MeshPeerManager({ onLog }),
236
+ trustGraph: trustGraph || new TrustGraph(),
237
+ acl: acl || new MeshACL({ owner: podId, onLog }),
238
+ capabilityValidator: capabilityValidator || new CapabilityValidator(),
239
+ tokenFactory: (tokenOpts) => new CapabilityToken(tokenOpts),
240
+ onLog,
241
+ })
242
+
243
+ // -- Discovery ----------------------------------------------------------
244
+ let strategies = discoveryStrategies
245
+ if (!strategies) {
246
+ if (typeof BroadcastChannel === 'undefined') {
247
+ throw new Error(
248
+ 'createMeshNode: no options.discoveryStrategies supplied and BroadcastChannel ' +
249
+ 'is not available in this environment (e.g. Node). Pass a Node-safe strategy, ' +
250
+ 'such as [new ManualStrategy()] from @johnhenry/browsermesh-discovery.',
251
+ )
252
+ }
253
+ strategies = [new BroadcastChannelStrategy({ channelName: discoveryChannelName })]
254
+ }
255
+ const localRecord = new DiscoveryRecord({
256
+ podId,
257
+ label,
258
+ transport: 'webrtc',
259
+ capabilities,
260
+ })
261
+ const discoveryOpts = { strategies, localRecord }
262
+ if (announceInterval !== undefined) discoveryOpts.announceInterval = announceInterval
263
+ const discovery = new DiscoveryManager(discoveryOpts)
264
+
265
+ // -- WebRTC transport negotiator -----------------------------------------
266
+ // mergeIceServers() is webrtc.mjs's own extension point: it honours an
267
+ // explicit `[]` as "no ICE servers" (used by this package's real-peer
268
+ // test for a hermetic, loopback-only connection) and otherwise merges any
269
+ // caller-supplied servers (typically TURN) alongside DEFAULT_ICE_SERVERS
270
+ // (empty by default), filtering out malformed entries rather than handing
271
+ // them straight to WebRTCMeshManager.
272
+ const meshManager = new WebRTCMeshManager({ localPodId: podId, iceServers: mergeIceServers(iceServers), onLog })
273
+ const signaling = new MeshSignalingChannel({ localPodId: podId, transport: signalingTransport, onLog })
274
+ await signaling.open()
275
+
276
+ // The negotiator is constructed (and handed to PeerNode) before its
277
+ // 'webrtc' adapter is registered -- registerAdapter() only needs to run
278
+ // before connectToPeer() is actually called at runtime, not before
279
+ // PeerNode's constructor captures the negotiator reference. This
280
+ // ordering is what lets the webrtc factory's onIncomingConnection hook
281
+ // below close over `node` and call PeerNode.adoptIncomingSession() --
282
+ // resolving the callee-side session gap (see peer-node.mjs / Phase 3).
283
+ const transportNegotiator = new MeshTransportNegotiator()
284
+
285
+ // -- PeerNode -------------------------------------------------------------
286
+ const node = new PeerNode({
287
+ wallet,
288
+ registry,
289
+ discovery,
290
+ transportNegotiator,
291
+ auditChain,
292
+ onLog,
293
+ })
294
+
295
+ const webrtcFactory = createWebRTCTransportFactory({
296
+ localPodId: podId,
297
+ meshManager,
298
+ signaling,
299
+ onLog,
300
+ // Callee side: once an auto-answered inbound offer's DataChannel opens,
301
+ // give it the same PeerNode-level session bookkeeping connectToPeer()
302
+ // gives the caller side, so sendTo()/onIncomingData() work symmetrically
303
+ // regardless of which side dialed.
304
+ onIncomingConnection: (remotePodId, adapter) => {
305
+ node.adoptIncomingSession(remotePodId, adapter, 'webrtc').catch((err) => {
306
+ onLog('mesh-bootstrap:adopt-incoming-session-failed', {
307
+ remotePodId,
308
+ error: err?.message || String(err),
309
+ })
310
+ })
311
+ },
312
+ })
313
+ transportNegotiator.registerAdapter('webrtc', webrtcFactory)
314
+
315
+ if (!skipBoot) {
316
+ await node.boot({ label, skipDiscovery })
317
+ }
318
+
319
+ // Not part of PeerNode's own API surface, but real callers/tests
320
+ // occasionally need direct access below the PeerNode abstraction
321
+ // (e.g. to inspect connection stats, or to close the signaling bus).
322
+ node.meshManager = meshManager
323
+ node.signaling = signaling
324
+
325
+ // -- CRDT sync (opt-in, Phase 3) -------------------------------------------
326
+ if (enableSync) {
327
+ node.sync = createMeshSync({
328
+ node,
329
+ storage: syncStorage,
330
+ dbName: syncDbName,
331
+ envelopeType: syncEnvelopeType,
332
+ onLog,
333
+ })
334
+ if (syncAutoLoad) {
335
+ await node.sync.load()
336
+ }
337
+ }
338
+
339
+ // -- Mesh relay host (opt-in, Phase 8) -------------------------------------
340
+ if (enableRelayHost) {
341
+ if (!relayHostNetwork) {
342
+ throw new Error(
343
+ 'createMeshNode: options.relayHostNetwork is required when enableRelayHost is true ' +
344
+ '(the VirtualNetwork MeshRelayHost bridges inbound relay connections into).',
345
+ )
346
+ }
347
+ node.relayHost = new MeshRelayHost({
348
+ node,
349
+ network: relayHostNetwork,
350
+ registry,
351
+ envelopeType: relayHostEnvelopeType,
352
+ onLog,
353
+ })
354
+ if (relayHostServices) {
355
+ for (const [name, targetAddress] of Object.entries(relayHostServices)) {
356
+ node.relayHost.exposeService(name, targetAddress)
357
+ }
358
+ }
359
+ }
360
+
361
+ return node
362
+ }