@johnhenry/browsermesh-apps 0.9.0 → 0.11.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/README.md CHANGED
@@ -17,7 +17,9 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
17
17
  - [Sharing a `VirtualNetwork` with specific peers: mesh relay](#sharing-a-virtualnetwork-with-specific-peers-mesh-relay)
18
18
  - [CloudStorage bucket authorization and key distribution](#cloudstorage-bucket-authorization-and-key-distribution)
19
19
  - [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
20
+ - [Torrent service: durable stores, authorization and serve limits](#torrent-service-durable-stores-authorization-and-serve-limits)
20
21
  - [Putting it all together: sync + kernel-gated mesh + relay on one connection](#putting-it-all-together-sync--kernel-gated-mesh--relay-on-one-connection)
22
+ - [Sending to peers: wire format, the bulk lane and `broadcast()`](#sending-to-peers-wire-format-the-bulk-lane-and-broadcast)
21
23
  - [`fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`](#fetchwebsocket-shaped-mesh-access-browsermeshfetch-and-browsermeshwebsocket)
22
24
  - [`browserMeshFetch`](#browsermeshfetch)
23
25
  - [`BrowserMeshWebSocket`](#browsermeshwebsocket)
@@ -59,8 +61,9 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
59
61
  | peer-escrow | `EscrowContract`, `EscrowManager` |
60
62
  | peer-files | `FileHost`, `FileClient` |
61
63
  | peer-health | `HealthMonitor`, `AutoMigrator` |
62
- | peer-ipfs | `IPFSStore` |
64
+ | peer-ipfs | `IPFSStore` (also exported as `MeshLocalCidStore`): a mesh-local content-addressed store. CIDs are SHA-256 hex digests, not IPFS CIDs, and nothing talks to the IPFS network |
63
65
  | peer-node | `PeerNode` |
66
+ | peer-node-transport | `createPeerNodeTransport` |
64
67
  | peer-payments | `CreditLedger`, `WebLNProvider` |
65
68
  | peer-registry | `PeerRegistry` |
66
69
  | peer-routing | `MeshRouter`, `ServerSharing` |
@@ -68,6 +71,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
68
71
  | peer-terminal | `TerminalHost`, `TerminalClient` |
69
72
  | peer-timestamp | `TimestampAuthority`, `TimestampProof` |
70
73
  | peer-torrent | `TorrentManager` |
74
+ | mesh-torrent | `createTorrentService` (swarm piece exchange as a `MeshService`; injectable durable stores, `authorize` hook, serve caps) |
71
75
  | peer-verification | `VerificationQuorum`, `Attestation` |
72
76
  | marketplace-ui | `SkillMarketplace` |
73
77
  | mesh-relay-host | `MeshRelayHost` |
@@ -343,6 +347,55 @@ GrantLog pattern, and the key-distribution pattern, each with pointers to
343
347
  the real code, written so the *next* mesh-native service doesn't have to
344
348
  rediscover these same design questions from scratch.
345
349
 
350
+ ## Torrent service: durable stores, authorization and serve limits
351
+
352
+ `createTorrentService()` (`mesh-torrent.mjs`) distributes content in
353
+ SHA-256-addressed pieces: a downloader fetches each piece from whichever peer
354
+ holds it, and a finished downloader becomes a seeder. By default everything is
355
+ in memory and open to any peer that knows the magnet URI. These options change
356
+ that; all are optional.
357
+
358
+ ```js
359
+ import { createTorrentService, attachService } from '@johnhenry/browsermesh-apps'
360
+ import { IndexedDBChunkStore } from '@johnhenry/browsermesh-sync'
361
+
362
+ const torrent = attachService(peerNode, undefined, createTorrentService({
363
+ // Durable pieces and manifests: a seeder that reloads keeps serving.
364
+ chunkStore: new IndexedDBChunkStore({ dbName: 'my-app-pieces' }),
365
+ manifestStore: myManifestStore,
366
+ // Who may fetch what. Return true to allow; false, a throw, or anything else denies.
367
+ authorize: async (fromPubKey, { kind, magnetURI, infoHash, cid, chunkCid }) =>
368
+ registry.checkAccess(fromPubKey, `share:${cid}`, 'read'),
369
+ maxConcurrentServes: 16, // chunk-responses in flight, all peers (0 = unlimited)
370
+ maxConcurrentServesPerPeer: 4, // ... per requesting peer
371
+ maxBytesPerPeerPerSec: 4 * 1024 * 1024, // served-bytes budget per peer (default 0 = unlimited)
372
+ maxAnnouncesPerPeerPerMinute: 30, // inbound announces accepted per peer
373
+ }))
374
+
375
+ await torrent.api.ensureLoaded() // after a reload: also restores listTorrents()
376
+ const info = await torrent.api.seed('some text') // strings are UTF-8 encoded
377
+ ```
378
+
379
+ - **`chunkStore`** is any object with `save(cid, bytes)`, `get(cid)`,
380
+ `has(cid)` and `remove(cid)`, each sync or returning a Promise. The in-memory
381
+ `ChunkStore` and the IndexedDB-backed `IndexedDBChunkStore` from
382
+ `@johnhenry/browsermesh-sync` both fit; the service is tested against both.
383
+ - **`manifestStore`** is `{ get(magnetURI), set(magnetURI, manifest),
384
+ delete(magnetURI), entries() }` (sync or async). Each manifest is a small
385
+ JSON-safe record. It is the index of what the node holds, and a node only
386
+ serves pieces that one of its manifests lists, so persist both stores or
387
+ neither. `TorrentManager` accepts the same two options (plus `chunkSize`).
388
+ - Stores you pass in belong to you: `destroy()` never clears them.
389
+ - **`authorize`** runs before every manifest and piece is served. A refused
390
+ request gets exactly the reply an unknown one gets (`manifest: null` /
391
+ `error: 'not-found'`), so a peer cannot probe what exists. `cid` is the
392
+ SHA-256 hex CID of the whole content; `chunkCid` is set for `kind: 'chunk'`.
393
+ - Over a serve cap a requester is told `busy` (whatever it asked for) and
394
+ downloaders back off and retry. Caps and `authorize` never apply to the
395
+ downloading side.
396
+ - Events: `torrent:chunk-served`, `torrent:chunk-received` (as before), plus
397
+ `torrent:request-denied` and `torrent:serve-busy`.
398
+
346
399
  ## Putting it all together: sync + kernel-gated mesh + relay on one connection
347
400
 
348
401
  Every composition layer above (`enableSync`, a `Kernel` wired via
@@ -369,6 +422,76 @@ it (harmless -- those envelopes are just plain objects with a `.type` field
369
422
  tenant code can filter on itself if it cares, but worth knowing rather than
370
423
  assuming the view is pre-filtered).
371
424
 
425
+ ## Sending to peers: wire format, the bulk lane and `broadcast()`
426
+
427
+ **What goes on the wire.** A real transport (`RTCDataChannel`, `WebSocket`)
428
+ carries only strings and binary. `PeerNode.sendTo(pubKey, envelopeObject)` and
429
+ `ctx.sendTo()` hand the transport an object; the transports in
430
+ `@johnhenry/browsermesh-transport` encode it as JSON text (strings and binary
431
+ go out unchanged -- see `encodeWireData()` there), and a service receives it
432
+ back as the parsed object through `ctx.onIncomingData()`. That parse accepts
433
+ either form, so it works for transports that deliver text and for in-process
434
+ nodes that pass objects. `PeerNode.onIncomingData()` is the raw bus: it hands
435
+ subscribers exactly what the transport delivered, so a direct subscriber that
436
+ wants objects should parse JSON-object text itself. If you write your own
437
+ transport, make `send()` follow the same rule -- forwarding an object to
438
+ `RTCDataChannel.send()` turns it into the text `"[object Object]"` with no
439
+ error.
440
+
441
+ **The bulk lane.** The WebRTC transport opens a second, unordered `mesh-bulk`
442
+ data channel so a large payload does not sit in front of control traffic.
443
+ Select it per send:
444
+
445
+ ```js
446
+ await peerNode.sendTo(pubKey, envelope, { channel: 'bulk' }) // PeerNode
447
+ await ctx.sendTo(pubKey, 'chunk-response', payload, { channel: 'bulk' }) // MeshService ctx
448
+ ```
449
+
450
+ `channel` is `'control'` (the default; the transport is then called exactly as
451
+ before) or `'bulk'`; anything else throws a `TypeError`. It reaches the
452
+ transport as `send(data, { channel })`. A transport with no bulk lane ignores
453
+ the option, and the WebRTC transport falls back to its control channel when the
454
+ bulk channel is not open, so the same code works against an older peer. The
455
+ chunk-carrying services -- chunk replication (`chunk-push`,
456
+ `chunk-fetch-response`) and the torrent service (`chunk-response`) -- already
457
+ send on the bulk lane; requests and acknowledgements stay on control. Use it in
458
+ your own service for any payload that is large or arrives in a burst.
459
+
460
+ **Sending to everyone.** `PeerNode.broadcast(data, { channel, exclude, concurrency })`
461
+ sends to every connected peer -- one send per peer, at most `concurrency` (default
462
+ 8) in flight. A peer whose send fails does not stop the others: errors are
463
+ collected, never thrown.
464
+
465
+ ```js
466
+ const { sent, failed } = await peerNode.broadcast({ type: 'hello' }, { exclude: [somePubKey] })
467
+ // sent: ['pk1', 'pk2'], failed: [{ pubKey: 'pk3', error: 'Data channel not open' }]
468
+ peerNode.on('broadcast', ({ sent, failed }) => { /* fires after each fan-out */ })
469
+ ```
470
+
471
+ `exclude` is an array, a `Set` or a `(pubKey) => boolean` predicate.
472
+
473
+ **Wiring payments, consensus, migration and group keys.** `PaymentRouter`,
474
+ `ConsensusManager`, `MigrationEngine` (`@johnhenry/browsermesh-sync`) and
475
+ `GroupKeyManager` (`@johnhenry/browsermesh-core`) each take a host-supplied
476
+ `wireTransport(broadcastFn, subscribeFn)`. `createPeerNodeTransport(peerNode)`
477
+ builds that pair from a `PeerNode`:
478
+
479
+ ```js
480
+ import { createPeerNodeTransport } from '@johnhenry/browsermesh-apps'
481
+
482
+ const { broadcastFn, subscribeFn } = createPeerNodeTransport(peerNode)
483
+ paymentRouter.wireTransport(broadcastFn, subscribeFn)
484
+ consensus.wireTransport(broadcastFn, subscribeFn)
485
+ ```
486
+
487
+ Messages travel as `{ type: <wire type>, payload, from }`. The `fromPodId` a
488
+ handler receives is the peer the message actually arrived from, not the
489
+ envelope's own `from` field, which a remote peer could set to anything.
490
+ `broadcastFn` never rejects, so it is safe to call fire-and-forget.
491
+
492
+ `test/real-peer/wire-envelope.test.mjs` runs all three over a real
493
+ `RTCPeerConnection` pair (`npm run test:real-peer`).
494
+
372
495
  ## `fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`
373
496
 
374
497
  Two web-standard-API-shaped wrappers over a mesh connection, so existing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -467,7 +467,7 @@ export function createChunkReplicationService({
467
467
  return
468
468
  }
469
469
 
470
- await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-fetch-response', requestId: msg.requestId, cid: msg.cid, data: toBase64(bytes) }).catch((err) => {
470
+ await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-fetch-response', requestId: msg.requestId, cid: msg.cid, data: toBase64(bytes) }, { channel: 'bulk' }).catch((err) => {
471
471
  log('chunk-replication:fetch-response-send-failed', { bucketId, to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
472
472
  })
473
473
  }
@@ -530,7 +530,7 @@ export function createChunkReplicationService({
530
530
  const bytes = chunkBytesByCid.get(cid)
531
531
  if (!bytes) continue // we don't hold this chunk ourselves -- nothing to push
532
532
  sends.push(
533
- ctx.sendTo(target, envelopeType, { bucketId, kind: 'chunk-push', requestId, cid, data: toBase64(bytes) }).catch((err) => {
533
+ ctx.sendTo(target, envelopeType, { bucketId, kind: 'chunk-push', requestId, cid, data: toBase64(bytes) }, { channel: 'bulk' }).catch((err) => {
534
534
  log('chunk-replication:push-send-failed', { bucketId, to: target, cid, error: err?.message || String(err) })
535
535
  }),
536
536
  )
package/src/index.mjs CHANGED
@@ -23,6 +23,7 @@ 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 './peer-node-transport.mjs';
26
27
  export * from './signaling.mjs';
27
28
  export * from './webrtc-negotiator.mjs';
28
29
  export * from './mesh-bootstrap.mjs';
@@ -0,0 +1,141 @@
1
+ // Shared helpers for TorrentManager (peer-torrent.mjs) and
2
+ // createTorrentService (mesh-torrent.mjs): byte-input normalisation, the
3
+ // default in-memory manifest store, and reference-counted chunk release.
4
+ //
5
+ // No browser-only imports at module level.
6
+
7
+ /**
8
+ * Normalise anything `seed()` accepts to a `Uint8Array`.
9
+ *
10
+ * string -> UTF-8 bytes
11
+ * Blob -> its bytes
12
+ * ArrayBuffer -> a view over it
13
+ * TypedArray / DataView -> a Uint8Array over the same bytes (Uint8Array is returned as-is)
14
+ *
15
+ * Anything else throws a `TypeError`. It must not fall through to
16
+ * `new Uint8Array(x)`: for a string or a plain object that yields an EMPTY
17
+ * array, which silently seeded zero bytes (#195).
18
+ *
19
+ * @param {unknown} data
20
+ * @returns {Promise<Uint8Array>}
21
+ */
22
+ export async function toSeedBytes(data) {
23
+ if (data instanceof Uint8Array) return data
24
+ if (typeof data === 'string') return new TextEncoder().encode(data)
25
+ if (data instanceof ArrayBuffer) return new Uint8Array(data)
26
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
27
+ if (typeof Blob !== 'undefined' && data instanceof Blob) return new Uint8Array(await data.arrayBuffer())
28
+ if (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer) return new Uint8Array(data)
29
+ const got = data === null ? 'null' : Array.isArray(data) ? 'Array' : typeof data === 'object' ? (data.constructor?.name || 'object') : typeof data
30
+ throw new TypeError(
31
+ `seed(): data must be a string, Uint8Array, other TypedArray, ArrayBuffer or Blob (got ${got})`,
32
+ )
33
+ }
34
+
35
+ /**
36
+ * Default `manifestStore`: a `Map` behind the async-tolerant contract
37
+ *
38
+ * get(key) -> manifest | undefined | null
39
+ * set(key, manifest) -> void
40
+ * delete(key) -> void
41
+ * entries() -> Iterable<[key, manifest]> | Array<[key, manifest]>
42
+ *
43
+ * (every method may be sync or return a Promise). Keys are magnet URIs;
44
+ * values are JSON-safe `{ infoHash, name, size, chunkSize, chunkCids, cid }`
45
+ * records, so a durable implementation can simply JSON-serialise them.
46
+ */
47
+ export class MemoryManifestStore {
48
+ #m = new Map()
49
+ get(key) { return this.#m.get(key) }
50
+ set(key, manifest) { this.#m.set(key, manifest) }
51
+ delete(key) { this.#m.delete(key) }
52
+ entries() { return [...this.#m.entries()] }
53
+ clear() { this.#m.clear() }
54
+ get size() { return this.#m.size }
55
+ }
56
+
57
+ /**
58
+ * Remove the chunks of `manifest` from `chunkStore`, except any that another
59
+ * manifest in `manifestStore` (other than `exceptKey`) still lists -- chunks
60
+ * are content-addressed and shared between torrents that contain identical
61
+ * pieces.
62
+ *
63
+ * @param {object} chunkStore
64
+ * @param {object} manifestStore
65
+ * @param {{ chunkCids: string[] }} manifest
66
+ * @param {string} exceptKey magnet URI being removed
67
+ * @returns {Promise<number>} chunks removed
68
+ */
69
+ export async function releaseChunks(chunkStore, manifestStore, manifest, exceptKey) {
70
+ const stillUsed = new Set()
71
+ for (const [key, other] of await manifestStore.entries()) {
72
+ if (key === exceptKey || !other || !Array.isArray(other.chunkCids)) continue
73
+ for (const cid of other.chunkCids) stillUsed.add(cid)
74
+ }
75
+ let removed = 0
76
+ for (const cid of new Set(manifest.chunkCids)) {
77
+ if (stillUsed.has(cid)) continue
78
+ if (await chunkStore.remove(cid)) removed++
79
+ }
80
+ return removed
81
+ }
82
+
83
+ /**
84
+ * Split `bytes` into `chunkSize` pieces (zero pieces for empty input).
85
+ * @param {Uint8Array} bytes
86
+ * @param {number} chunkSize
87
+ * @returns {Uint8Array[]}
88
+ */
89
+ export function splitIntoChunks(bytes, chunkSize) {
90
+ const pieces = []
91
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
92
+ pieces.push(bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)))
93
+ }
94
+ return pieces
95
+ }
96
+
97
+ /**
98
+ * @param {object} store a ChunkStore-contract object (sync or async)
99
+ * @param {Uint8Array[]} pieces
100
+ * @param {(piece: Uint8Array) => Promise<string>} computeCid
101
+ * @returns {Promise<string[]>} the pieces' CIDs, in order. Pieces already in the store are not re-written.
102
+ */
103
+ export async function saveChunks(store, pieces, computeCid) {
104
+ const cids = []
105
+ for (const piece of pieces) {
106
+ const cid = await computeCid(piece)
107
+ if (!(await store.has(cid))) await store.save(cid, piece)
108
+ cids.push(cid)
109
+ }
110
+ return cids
111
+ }
112
+
113
+ /**
114
+ * Token bucket: `rate` bytes/second with a one-second burst. `take(n)` waits
115
+ * until `n` bytes of budget exist (a single piece larger than one second's
116
+ * budget waits for a full bucket, never forever). `rate <= 0` or `Infinity`
117
+ * disables the limit.
118
+ *
119
+ * @param {object} opts
120
+ * @param {number} opts.rate
121
+ * @param {() => number} [opts.now]
122
+ * @param {(ms: number) => Promise<void>} [opts.sleep]
123
+ */
124
+ export function createByteBucket({ rate, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
125
+ const unlimited = !(rate > 0) || !Number.isFinite(rate)
126
+ let tokens = rate
127
+ let last = now()
128
+ return {
129
+ async take(bytes) {
130
+ if (unlimited) return
131
+ const need = Math.min(bytes, rate)
132
+ for (;;) {
133
+ const t = now()
134
+ tokens = Math.min(rate, tokens + ((t - last) / 1000) * rate)
135
+ last = t
136
+ if (tokens >= need) { tokens -= need; return }
137
+ await sleep(Math.ceil(((need - tokens) / rate) * 1000))
138
+ }
139
+ },
140
+ }
141
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Inbound half of the mesh wire-envelope contract.
3
+ *
4
+ * A real transport (`RTCDataChannel`, `WebSocket`) can only carry strings and
5
+ * binary, so a MeshService envelope (`{ type, ...payload }`) crosses it as
6
+ * JSON text -- see `@johnhenry/browsermesh-transport`'s `encodeWireData()`
7
+ * for the outbound half. Some transports parse that text back before they
8
+ * hand it up (`WebRTCPeerConnection` does); others hand `PeerNode` the raw
9
+ * string. A consumer that wants envelope objects therefore has to accept
10
+ * both, which is what this does.
11
+ *
12
+ * Only strings that look like a JSON object or array are parsed, so a plain
13
+ * text payload that merely happens to be valid JSON (`"42"`, `"true"`) is
14
+ * left exactly as the sender wrote it. A string that looks like JSON but
15
+ * does not parse is returned unchanged rather than thrown on -- one corrupt
16
+ * frame must never take down the shared dispatch loop.
17
+ *
18
+ * Browser-safe: no imports.
19
+ *
20
+ * @param {*} data - Whatever `PeerNode.onIncomingData()` delivered.
21
+ * @returns {*} The parsed object/array when `data` was a JSON object/array
22
+ * string; `data` itself otherwise.
23
+ */
24
+ export function decodeWireData(data) {
25
+ if (typeof data !== 'string') return data
26
+ const first = data.trimStart()[0]
27
+ if (first !== '{' && first !== '[') return data
28
+ try {
29
+ return JSON.parse(data)
30
+ } catch {
31
+ return data
32
+ }
33
+ }
@@ -576,7 +576,9 @@ import { registerOrchestratorTools } from './mesh-orchestrator-tools.mjs'
576
576
  * `node.services.get('torrent')`).
577
577
  * @param {object} [options.torrentOptions] - Only used when `enableTorrent`.
578
578
  * Passed straight through to `createTorrentService()`
579
- * (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs`).
579
+ * (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs`,
580
+ * plus the hooks `chunkStore`/`manifestStore`/`authorize`/`maxConcurrentServes`/
581
+ * `maxConcurrentServesPerPeer`/`maxBytesPerPeerPerSec`/`maxAnnouncesPerPeerPerMinute`).
580
582
  * @param {boolean} [options.enableEscrow=false] - Attach `peer-escrow.mjs`'s
581
583
  * `createEscrowService()` (issue #117): real escrow-contract create/
582
584
  * release/refund/dispute against `escrowOptions.creditLedger`, with
@@ -1220,6 +1222,13 @@ export async function createMeshNode(options = {}) {
1220
1222
  envelopeType: torrentOptions?.envelopeType,
1221
1223
  manifestTimeoutMs: torrentOptions?.manifestTimeoutMs,
1222
1224
  chunkTimeoutMs: torrentOptions?.chunkTimeoutMs,
1225
+ chunkStore: torrentOptions?.chunkStore,
1226
+ manifestStore: torrentOptions?.manifestStore,
1227
+ authorize: torrentOptions?.authorize,
1228
+ maxConcurrentServes: torrentOptions?.maxConcurrentServes,
1229
+ maxConcurrentServesPerPeer: torrentOptions?.maxConcurrentServesPerPeer,
1230
+ maxBytesPerPeerPerSec: torrentOptions?.maxBytesPerPeerPerSec,
1231
+ maxAnnouncesPerPeerPerMinute: torrentOptions?.maxAnnouncesPerPeerPerMinute,
1223
1232
  onLog,
1224
1233
  })
1225
1234
  const torrentHandle = attachService(node, servicesNetwork, torrentDescriptor)
@@ -51,6 +51,7 @@
51
51
  */
52
52
 
53
53
  import { createLazyRequire } from './internal/lazy-node-require.mjs'
54
+ import { decodeWireData } from './internal/wire-envelope.mjs'
54
55
 
55
56
  /** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
56
57
  const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
@@ -222,6 +223,7 @@ function resolveMeshRelayBackendClass() {
222
223
 
223
224
  /** @param {*} data */
224
225
  async #handleIncoming(data) {
226
+ data = decodeWireData(data)
225
227
  if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
226
228
  const { op, connId } = data
227
229
  if (!connId || typeof connId !== 'string') return
@@ -44,6 +44,8 @@
44
44
  */
45
45
 
46
46
  /** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
47
+ import { decodeWireData } from './internal/wire-envelope.mjs'
48
+
47
49
  const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
48
50
 
49
51
  // ---------------------------------------------------------------------------
@@ -193,6 +195,7 @@ export class MeshRelayHost {
193
195
  * @param {*} data
194
196
  */
195
197
  async #handleIncoming(fromPubKey, data) {
198
+ data = decodeWireData(data)
196
199
  if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
197
200
  const { op, connId } = data
198
201
  if (!connId || typeof connId !== 'string') return
@@ -27,10 +27,17 @@
27
27
  * invoking `callback(pubKey, envelope)` only for envelopes whose `.type`
28
28
  * matches `types` (a single string or an array of strings). Returns an
29
29
  * unsubscribe function, exactly like the underlying `onIncomingData()`.
30
- * - `ctx.sendTo(pubKey, type, payload)` -- wraps `peerNode.sendTo()`,
30
+ * A real transport carries an envelope as JSON text, so a string that
31
+ * is a JSON object/array is parsed before the `type` check -- `callback`
32
+ * always receives the parsed envelope object.
33
+ * - `ctx.sendTo(pubKey, type, payload, { channel })` -- wraps `peerNode.sendTo()`,
31
34
  * merging `{ type, ...payload }` into the envelope sent, matching the
32
35
  * `{ type: envelopeType, ...payload }` shape both `mesh-sync.mjs` and
33
- * `mesh-relay-host.mjs` already send.
36
+ * `mesh-relay-host.mjs` already send. The optional fourth argument
37
+ * `{ channel: 'control'|'bulk' }` picks the transport's data channel
38
+ * (default `'control'`); use `'bulk'` for large payloads such as file
39
+ * chunks so they cannot queue in front of control traffic. Transports
40
+ * without a bulk lane ignore it.
34
41
  * - `ctx.registry` -- the node's `PeerRegistry`, for `checkAccess()`.
35
42
  * - `ctx.peerNode` -- the raw `PeerNode`, for anything not covered above.
36
43
  * - `ctx.network` -- the `VirtualNetwork` passed to `attachService()`, if
@@ -126,6 +133,8 @@
126
133
  * No browser-only imports at module level.
127
134
  */
128
135
 
136
+ import { decodeWireData } from './internal/wire-envelope.mjs'
137
+
129
138
  /** Default scheme a descriptor's `createBackend` backend is registered under, if `backendScheme` is omitted. */
130
139
  const DEFAULT_BACKEND_SCHEME = 'svc'
131
140
 
@@ -226,8 +235,12 @@ function createEventBus() {
226
235
  * @property {(types: string|string[], callback: (pubKey: string, envelope: object) => void) => (() => void)} onIncomingData
227
236
  * Envelope-type-filtered subscription. `callback` only fires for envelopes
228
237
  * whose `.type` is in `types`. Returns an unsubscribe function.
229
- * @property {(pubKey: string, type: string, payload?: object) => Promise<void>} sendTo
238
+ * @property {(pubKey: string, type: string, payload?: object, opts?: { channel?: 'control'|'bulk' }) => Promise<void>} sendTo
230
239
  * Sends `{ type, ...payload }` to `pubKey` via `peerNode.sendTo()`.
240
+ * `opts.channel` picks the transport's data channel: `'control'` (the
241
+ * default) or `'bulk'` (the second, unordered channel meant for large
242
+ * payloads such as file chunks, so they cannot queue in front of control
243
+ * traffic). A transport with no bulk lane ignores it. See `PeerNode.sendTo()`.
231
244
  * @property {(event: string, data?: object) => void} emit
232
245
  * Publishes a curated, meaningful state-transition event for anything
233
246
  * subscribed via `attachService()`'s returned handle (`handle.on()`/
@@ -286,7 +299,12 @@ function createServiceContext({ peerNode, network, eventBus }) {
286
299
 
287
300
  onIncomingData(types, callback) {
288
301
  const typeSet = new Set(Array.isArray(types) ? types : [types])
289
- return peerNode.onIncomingData((pubKey, data) => {
302
+ return peerNode.onIncomingData((pubKey, rawData) => {
303
+ // A real transport (RTCDataChannel, WebSocket) can only carry
304
+ // strings/binary, so an envelope may arrive as its JSON text --
305
+ // parse it before the `type` check. Already-parsed objects (every
306
+ // in-process node, and transports that parse for us) pass through.
307
+ const data = decodeWireData(rawData)
290
308
  if (!data || typeof data !== 'object' || !typeSet.has(data.type)) return
291
309
  // `peerNode.onIncomingData()`'s own dispatch loop only catches a
292
310
  // SYNCHRONOUS throw from this callback. Every real handler in this
@@ -308,8 +326,12 @@ function createServiceContext({ peerNode, network, eventBus }) {
308
326
  })
309
327
  },
310
328
 
311
- async sendTo(pubKey, type, payload = {}) {
312
- await peerNode.sendTo(pubKey, { type, ...payload })
329
+ async sendTo(pubKey, type, payload = {}, { channel } = {}) {
330
+ // `channel` is forwarded only when the caller picked one, so a node
331
+ // (or duck-typed test double) that predates the option sees exactly
332
+ // the two-argument call it always did.
333
+ if (channel === undefined) await peerNode.sendTo(pubKey, { type, ...payload })
334
+ else await peerNode.sendTo(pubKey, { type, ...payload }, { channel })
313
335
  },
314
336
 
315
337
  emit(event, data) {
package/src/mesh-sync.mjs CHANGED
@@ -26,6 +26,7 @@
26
26
  */
27
27
 
28
28
  import { MeshSyncEngine, IndexedDBSyncStorage } from '@johnhenry/browsermesh-sync'
29
+ import { decodeWireData } from './internal/wire-envelope.mjs'
29
30
 
30
31
  /** Default `envelope.type` used to route sync payloads on the shared `onIncomingData()` bus. */
31
32
  const DEFAULT_ENVELOPE_TYPE = 'mesh-sync'
@@ -169,6 +170,7 @@ export class MeshSyncBinding {
169
170
  * @param {*} data
170
171
  */
171
172
  #handleIncoming(pubKey, data) {
173
+ data = decodeWireData(data)
172
174
  if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
173
175
  const { docId, docType, payload } = data
174
176
  if (!docId || !payload) return