@johnhenry/browsermesh-apps 0.4.3 → 0.7.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 +6 -6
- package/package.json +6 -2
- package/src/cloud-storage-backend.mjs +65 -6
- package/src/cloud-storage.mjs +3 -3
- package/src/kernel-mesh.mjs +11 -5
- package/src/key-distribution.mjs +16 -6
- package/src/mesh-bootstrap.mjs +22 -23
- package/src/mesh-dht.mjs +21 -1
- package/src/mesh-fetch.mjs +30 -1
- package/src/mesh-hardening.mjs +11 -4
- package/src/mesh-keepalive.mjs +96 -17
- package/src/mesh-relay-backend.mjs +62 -6
- package/src/mesh-swarm.mjs +26 -8
- package/src/mesh-websocket.mjs +23 -1
- package/src/serverless-fetch.mjs +21 -1
- package/src/webrtc-negotiator.mjs +22 -4
package/README.md
CHANGED
|
@@ -49,9 +49,9 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
49
49
|
| peer-verification | `VerificationQuorum`, `Attestation` |
|
|
50
50
|
| marketplace-ui | `SkillMarketplace` |
|
|
51
51
|
| mesh-relay-host | `MeshRelayHost` |
|
|
52
|
-
| mesh-relay-backend | `
|
|
52
|
+
| mesh-relay-backend | `createMeshRelayBackend` |
|
|
53
53
|
| mesh-service | `attachService`, `MeshService` (attach convention) |
|
|
54
|
-
| cloud-storage-backend | `
|
|
54
|
+
| cloud-storage-backend | `createCloudStorageBackend` |
|
|
55
55
|
| grant-log | `GrantLog`, `createGrantLogService` |
|
|
56
56
|
| key-distribution | `createKeyDistributionService` |
|
|
57
57
|
| manifest-sync | `createManifestSyncService` |
|
|
@@ -232,17 +232,17 @@ alice.registry.grantCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
|
|
|
232
232
|
alice.registry.revokeCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
|
|
233
233
|
```
|
|
234
234
|
|
|
235
|
-
On the client side (the peer being granted access), `
|
|
236
|
-
`browsermesh-netway` `Backend` -- register it on your own `VirtualNetwork`
|
|
235
|
+
On the client side (the peer being granted access), `createMeshRelayBackend()`
|
|
236
|
+
builds a `browsermesh-netway` `Backend` -- register it on your own `VirtualNetwork`
|
|
237
237
|
under any scheme you like, and connect through the normal API, treating the
|
|
238
238
|
service name as the "host":
|
|
239
239
|
|
|
240
240
|
```js
|
|
241
|
-
import {
|
|
241
|
+
import { createMeshRelayBackend } from '@johnhenry/browsermesh-apps';
|
|
242
242
|
import { VirtualNetwork } from '@johnhenry/browsermesh-netway';
|
|
243
243
|
|
|
244
244
|
const bobNetwork = new VirtualNetwork();
|
|
245
|
-
bobNetwork.addBackend('via-alice',
|
|
245
|
+
bobNetwork.addBackend('via-alice', createMeshRelayBackend({ node: bob, relayPeerPubKey: alice.podId }));
|
|
246
246
|
|
|
247
247
|
const socket = await bobNetwork.connect('via-alice://s3-local'); // refused (ConnectionRefusedError) until granted
|
|
248
248
|
```
|
package/package.json
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-apps",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./src/index.mjs",
|
|
9
|
-
"./compat": "./src/compat.mjs"
|
|
9
|
+
"./compat": "./src/compat.mjs",
|
|
10
|
+
"./mesh-rpc": "./src/mesh-rpc.mjs",
|
|
11
|
+
"./mesh-fetch": "./src/mesh-fetch.mjs",
|
|
12
|
+
"./mesh-service": "./src/mesh-service.mjs",
|
|
13
|
+
"./peer-registry": "./src/peer-registry.mjs"
|
|
10
14
|
},
|
|
11
15
|
"files": [
|
|
12
16
|
"src",
|
|
@@ -140,12 +140,40 @@
|
|
|
140
140
|
* is byte-for-byte identical to before this phase existed.
|
|
141
141
|
*
|
|
142
142
|
* No browser-only imports at module level.
|
|
143
|
+
*
|
|
144
|
+
* `@johnhenry/browsermesh-netway` (an optional peerDependency) is lazily
|
|
145
|
+
* resolved via `createRequire(import.meta.url)` -- Node's stable
|
|
146
|
+
* synchronous `require()` of an ES module (Node >=22.12/23, well within
|
|
147
|
+
* this package's own `engines.node: >=24` floor). `Backend` is used as a
|
|
148
|
+
* base class (`class CloudStorageBackend extends Backend`); a class's
|
|
149
|
+
* `extends` clause is evaluated at class-DECLARATION time, and a
|
|
150
|
+
* `class ... extends ... {}` statement written at module top level always
|
|
151
|
+
* runs at module-LOAD time, no matter how the `Backend` reference feeding
|
|
152
|
+
* it is obtained -- there is no way to defer that with a plain lazy
|
|
153
|
+
* import, sync or async. The fix here instead moves the class declaration
|
|
154
|
+
* itself out of module-top-level scope, into a function that resolves
|
|
155
|
+
* `Backend` via `require()` and builds+memoizes the class on first call, so
|
|
156
|
+
* it still only runs once, lazily, the first time this file is actually
|
|
157
|
+
* used, not merely imported. (`@johnhenry/browsermesh-sync` and
|
|
158
|
+
* `@johnhenry/browsermesh-primitives`, imported below, are both REQUIRED
|
|
159
|
+
* -- not optional -- peerDependencies of this package, so they stay
|
|
160
|
+
* imported eagerly; only `browsermesh-netway` needed this treatment.)
|
|
161
|
+
*
|
|
162
|
+
* **BREAKING CHANGE**: `CloudStorageBackend` is no longer exported as a
|
|
163
|
+
* class. Replace `new CloudStorageBackend(opts)` with
|
|
164
|
+
* `createCloudStorageBackend(opts)` (same `opts` shape, still returns a
|
|
165
|
+
* real `CloudStorageBackend` instance with the exact same instance API) --
|
|
166
|
+
* see the CHANGELOG entry documenting this fix across the package for the
|
|
167
|
+
* full rationale and the sibling `mesh-relay-backend.mjs` fix.
|
|
143
168
|
*/
|
|
144
169
|
|
|
145
|
-
import {
|
|
170
|
+
import { createRequire } from 'node:module'
|
|
171
|
+
|
|
146
172
|
import { IndexedDBChunkStore, IndexedDBSyncStorage, TRANSFER_DEFAULTS } from '@johnhenry/browsermesh-sync'
|
|
147
173
|
import { LWWMap } from '@johnhenry/browsermesh-primitives'
|
|
148
174
|
|
|
175
|
+
const require = createRequire(import.meta.url)
|
|
176
|
+
|
|
149
177
|
/** 256KB, matching `MeshFileTransfer`'s existing chunking convention exactly (imported, not duplicated as a literal). */
|
|
150
178
|
const CHUNK_SIZE = TRANSFER_DEFAULTS.chunkSize
|
|
151
179
|
|
|
@@ -286,13 +314,26 @@ function bytesEqual(a, b) {
|
|
|
286
314
|
// CloudStorageBackend
|
|
287
315
|
// ---------------------------------------------------------------------------
|
|
288
316
|
|
|
317
|
+
let _CloudStorageBackendClass = null
|
|
318
|
+
|
|
289
319
|
/**
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
*
|
|
293
|
-
*
|
|
320
|
+
* Lazily builds (and memoizes) the `CloudStorageBackend` class, deferring
|
|
321
|
+
* resolution of `@johnhenry/browsermesh-netway`'s `Backend`/`StreamSocket`
|
|
322
|
+
* past module-load time -- see module doc comment. Only ever runs once per
|
|
323
|
+
* process; every later call returns the same class reference.
|
|
324
|
+
* @returns {typeof CloudStorageBackend}
|
|
294
325
|
*/
|
|
295
|
-
|
|
326
|
+
function resolveCloudStorageBackendClass() {
|
|
327
|
+
if (_CloudStorageBackendClass) return _CloudStorageBackendClass
|
|
328
|
+
const { Backend, StreamSocket } = require('@johnhenry/browsermesh-netway')
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* A `Backend` exposing a durable, encrypted-at-rest, single-peer S3-like
|
|
332
|
+
* object store over a JSON-command-over-socket protocol.
|
|
333
|
+
*
|
|
334
|
+
* @extends Backend
|
|
335
|
+
*/
|
|
336
|
+
class CloudStorageBackend extends Backend {
|
|
296
337
|
/** @type {string} */
|
|
297
338
|
#bucket
|
|
298
339
|
|
|
@@ -929,4 +970,22 @@ export class CloudStorageBackend extends Backend {
|
|
|
929
970
|
this.#manifestStorage.close?.()
|
|
930
971
|
this.#keyStorage.close?.()
|
|
931
972
|
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
_CloudStorageBackendClass = CloudStorageBackend
|
|
976
|
+
return CloudStorageBackend
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* Construct a `CloudStorageBackend` -- the class itself is no longer
|
|
981
|
+
* exported directly (see module doc comment's "BREAKING CHANGE" note).
|
|
982
|
+
*
|
|
983
|
+
* @param {object} opts - Same shape as `CloudStorageBackend`'s constructor:
|
|
984
|
+
* `{bucket, dbName?, chunkStore?, manifestStorage?, keyStorage?, nodeId?, onLog?}`.
|
|
985
|
+
* @returns {import('@johnhenry/browsermesh-netway').Backend} A real
|
|
986
|
+
* `CloudStorageBackend` instance (the full instance API is unchanged).
|
|
987
|
+
*/
|
|
988
|
+
export function createCloudStorageBackend(opts) {
|
|
989
|
+
const CloudStorageBackend = resolveCloudStorageBackendClass()
|
|
990
|
+
return new CloudStorageBackend(opts)
|
|
932
991
|
}
|
package/src/cloud-storage.mjs
CHANGED
|
@@ -198,7 +198,7 @@
|
|
|
198
198
|
*/
|
|
199
199
|
|
|
200
200
|
import { attachService, createEventBus } from './mesh-service.mjs'
|
|
201
|
-
import {
|
|
201
|
+
import { createCloudStorageBackend } from './cloud-storage-backend.mjs'
|
|
202
202
|
import { createGrantLogService } from './grant-log.mjs'
|
|
203
203
|
import { createKeyDistributionService } from './key-distribution.mjs'
|
|
204
204
|
import { createManifestSyncService } from './manifest-sync.mjs'
|
|
@@ -304,7 +304,7 @@ export class CloudStorage {
|
|
|
304
304
|
/** @type {import('@johnhenry/browsermesh-netway').VirtualNetwork|null} */
|
|
305
305
|
#network
|
|
306
306
|
|
|
307
|
-
/** @type {CloudStorageBackend} */
|
|
307
|
+
/** @type {import('./cloud-storage-backend.mjs').CloudStorageBackend} */
|
|
308
308
|
#backend
|
|
309
309
|
|
|
310
310
|
/** @type {import('@johnhenry/browsermesh-netway').StreamSocket|null} lazily-opened private local socket to `#backend` */
|
|
@@ -415,7 +415,7 @@ export class CloudStorage {
|
|
|
415
415
|
})
|
|
416
416
|
}
|
|
417
417
|
|
|
418
|
-
this.#backend =
|
|
418
|
+
this.#backend = createCloudStorageBackend({
|
|
419
419
|
bucket,
|
|
420
420
|
dbName,
|
|
421
421
|
chunkStore,
|
package/src/kernel-mesh.mjs
CHANGED
|
@@ -29,11 +29,10 @@
|
|
|
29
29
|
* with no adapter code needed -- this module's only real job is making that
|
|
30
30
|
* dependency direction, and the one-import convenience, explicit.
|
|
31
31
|
*
|
|
32
|
-
* No browser-only imports at module level
|
|
32
|
+
* No browser-only imports at module level -- @johnhenry/browsermesh-kernel
|
|
33
|
+
* is imported lazily inside createMeshKernel() (see below).
|
|
33
34
|
*/
|
|
34
35
|
|
|
35
|
-
import { Kernel } from '@johnhenry/browsermesh-kernel'
|
|
36
|
-
|
|
37
36
|
/**
|
|
38
37
|
* Construct a Kernel whose MESH capability is backed by a real, connected
|
|
39
38
|
* `PeerNode`. Any tenant created via the returned kernel with
|
|
@@ -49,8 +48,15 @@ import { Kernel } from '@johnhenry/browsermesh-kernel'
|
|
|
49
48
|
* `new Kernel()`.
|
|
50
49
|
* @param {object} [opts.kernelOpts] - Passed through to the Kernel
|
|
51
50
|
* constructor (`clock`, `rng`, `tracerOpts`, `loggerOpts`, `resourceOpts`).
|
|
52
|
-
* @returns {Kernel}
|
|
51
|
+
* @returns {Promise<Kernel>}
|
|
53
52
|
*/
|
|
54
|
-
export function createMeshKernel({ peerNode, kernelOpts = {} } = {}) {
|
|
53
|
+
export async function createMeshKernel({ peerNode, kernelOpts = {} } = {}) {
|
|
54
|
+
// Lazily imported so this module doesn't force @johnhenry/browsermesh-kernel
|
|
55
|
+
// (an optional peerDependency) on every consumer of this package's
|
|
56
|
+
// top-level `.` entrypoint, which `export *`s from this file among 70+
|
|
57
|
+
// others -- see the CHANGELOG entry documenting this fix for the full
|
|
58
|
+
// rationale. BREAKING: this function is now async (was sync); the only
|
|
59
|
+
// in-repo caller (test/real-peer/kernel-mesh.test.mjs) is updated to match.
|
|
60
|
+
const { Kernel } = await import('@johnhenry/browsermesh-kernel')
|
|
55
61
|
return new Kernel({ ...kernelOpts, mesh: peerNode || null })
|
|
56
62
|
}
|
package/src/key-distribution.mjs
CHANGED
|
@@ -168,7 +168,13 @@
|
|
|
168
168
|
*/
|
|
169
169
|
|
|
170
170
|
import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives'
|
|
171
|
-
|
|
171
|
+
// @johnhenry/browsermesh-core (an optional peerDependency) is imported
|
|
172
|
+
// lazily, at each of the three call sites below, rather than eagerly here
|
|
173
|
+
// -- so this module doesn't force it on every consumer of this package's
|
|
174
|
+
// top-level `.` entrypoint. Dynamic import() is cached by the module
|
|
175
|
+
// system after the first real resolution, so this costs nothing on repeat
|
|
176
|
+
// calls. See the CHANGELOG entry documenting this fix for the full
|
|
177
|
+
// rationale.
|
|
172
178
|
|
|
173
179
|
/** Default `envelope.type` used to route key-distribution payloads on the shared `onIncomingData()` bus. */
|
|
174
180
|
const DEFAULT_ENVELOPE_TYPE = 'bucket-key'
|
|
@@ -315,11 +321,13 @@ export function createKeyDistributionService({
|
|
|
315
321
|
|
|
316
322
|
function ensureKeyPair() {
|
|
317
323
|
if (!keyPairPromise) {
|
|
318
|
-
keyPairPromise =
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
324
|
+
keyPairPromise = import('@johnhenry/browsermesh-core')
|
|
325
|
+
.then(({ generateEncryptionKeyPair }) => generateEncryptionKeyPair())
|
|
326
|
+
.then(async (kp) => {
|
|
327
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))
|
|
328
|
+
localPublicKeyB64 = toBase64(raw)
|
|
329
|
+
return kp
|
|
330
|
+
})
|
|
323
331
|
}
|
|
324
332
|
return keyPairPromise
|
|
325
333
|
}
|
|
@@ -330,6 +338,7 @@ export function createKeyDistributionService({
|
|
|
330
338
|
|
|
331
339
|
/** Wrap `rawKeyBytes` for `recipientPublicKey` and sign a `deliver` record over the result. */
|
|
332
340
|
async function buildDeliverRecord(rawKeyBytes, recipientPublicKey) {
|
|
341
|
+
const { wrapKeyForMember } = await import('@johnhenry/browsermesh-core')
|
|
333
342
|
const importable = await crypto.subtle.importKey('raw', rawKeyBytes, { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])
|
|
334
343
|
const envelope = await wrapKeyForMember(importable, recipientPublicKey)
|
|
335
344
|
|
|
@@ -464,6 +473,7 @@ export function createKeyDistributionService({
|
|
|
464
473
|
|
|
465
474
|
let rawKeyBytes
|
|
466
475
|
try {
|
|
476
|
+
const { unwrapKeyForMember } = await import('@johnhenry/browsermesh-core')
|
|
467
477
|
const keyPair = await ensureKeyPair()
|
|
468
478
|
const unwrapped = await unwrapKeyForMember(envelope, keyPair.privateKey)
|
|
469
479
|
rawKeyBytes = new Uint8Array(await crypto.subtle.exportKey('raw', unwrapped))
|
package/src/mesh-bootstrap.mjs
CHANGED
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
* e.g. one with a `GatewayBackend` reaching a real local service), attached
|
|
54
54
|
* as `node.relayHost`. This is the "share my `VirtualNetwork` access with
|
|
55
55
|
* specific peers" side; the client side is `mesh-relay-backend.mjs`'s
|
|
56
|
-
* `
|
|
56
|
+
* `createMeshRelayBackend()`, called directly (not via this function) and
|
|
57
57
|
* registered on the *client's own* `VirtualNetwork`.
|
|
58
58
|
*
|
|
59
59
|
* **Transport hardening is opt-in via `{ enableHardening: true,
|
|
@@ -300,29 +300,12 @@
|
|
|
300
300
|
* detection). Attached to the returned node as `node.swarm` (the
|
|
301
301
|
* `attachService()` handle -- also reachable via `node.services.get('swarm')`).
|
|
302
302
|
*
|
|
303
|
-
* No browser-only imports at module level.
|
|
303
|
+
* No browser-only imports at module level. @johnhenry/browsermesh-core/
|
|
304
|
+
* -discovery/-transport (all optional peerDependencies) are imported
|
|
305
|
+
* lazily inside createMeshNode() itself, not here -- see that function's
|
|
306
|
+
* own comment and the CHANGELOG entry documenting this fix.
|
|
304
307
|
*/
|
|
305
308
|
|
|
306
|
-
import {
|
|
307
|
-
IdentityWallet,
|
|
308
|
-
MeshIdentityManager,
|
|
309
|
-
MeshPeerManager,
|
|
310
|
-
TrustGraph,
|
|
311
|
-
MeshACL,
|
|
312
|
-
CapabilityValidator,
|
|
313
|
-
CapabilityToken,
|
|
314
|
-
} from '@johnhenry/browsermesh-core'
|
|
315
|
-
import {
|
|
316
|
-
DiscoveryManager,
|
|
317
|
-
DiscoveryRecord,
|
|
318
|
-
BroadcastChannelStrategy,
|
|
319
|
-
} from '@johnhenry/browsermesh-discovery'
|
|
320
|
-
import {
|
|
321
|
-
MeshTransportNegotiator,
|
|
322
|
-
WebRTCMeshManager,
|
|
323
|
-
mergeIceServers,
|
|
324
|
-
} from '@johnhenry/browsermesh-transport'
|
|
325
|
-
|
|
326
309
|
import { PeerNode } from './peer-node.mjs'
|
|
327
310
|
import { PeerRegistry } from './peer-registry.mjs'
|
|
328
311
|
import { MeshSignalingChannel } from './signaling.mjs'
|
|
@@ -876,6 +859,22 @@ export async function createMeshNode(options = {}) {
|
|
|
876
859
|
)
|
|
877
860
|
}
|
|
878
861
|
|
|
862
|
+
// @johnhenry/browsermesh-core/-discovery/-transport (all optional
|
|
863
|
+
// peerDependencies) are imported lazily here, not eagerly at module
|
|
864
|
+
// top-level, so this module doesn't force them on every consumer of
|
|
865
|
+
// this package's top-level `.` entrypoint -- see the CHANGELOG entry
|
|
866
|
+
// documenting this fix. createMeshNode() was already async, so this
|
|
867
|
+
// adds no signature change.
|
|
868
|
+
const [
|
|
869
|
+
{ IdentityWallet, MeshIdentityManager, MeshPeerManager, TrustGraph, MeshACL, CapabilityValidator, CapabilityToken },
|
|
870
|
+
{ DiscoveryManager, DiscoveryRecord, BroadcastChannelStrategy },
|
|
871
|
+
{ MeshTransportNegotiator, WebRTCMeshManager, mergeIceServers },
|
|
872
|
+
] = await Promise.all([
|
|
873
|
+
import('@johnhenry/browsermesh-core'),
|
|
874
|
+
import('@johnhenry/browsermesh-discovery'),
|
|
875
|
+
import('@johnhenry/browsermesh-transport'),
|
|
876
|
+
])
|
|
877
|
+
|
|
879
878
|
// -- Identity ---------------------------------------------------------
|
|
880
879
|
const identityManager = providedIdentityManager || new MeshIdentityManager({ onLog })
|
|
881
880
|
const wallet = new IdentityWallet({ identityManager, onLog })
|
|
@@ -980,7 +979,7 @@ export async function createMeshNode(options = {}) {
|
|
|
980
979
|
// same `transportNegotiator` reference, so it sees adapters registered on
|
|
981
980
|
// it regardless of when registration happens relative to wrapping.
|
|
982
981
|
const hardening = enableHardening
|
|
983
|
-
? createHardenedNegotiator({
|
|
982
|
+
? await createHardenedNegotiator({
|
|
984
983
|
negotiator: transportNegotiator,
|
|
985
984
|
retryOptions: hardeningOptions?.retry,
|
|
986
985
|
onLog,
|
package/src/mesh-dht.mjs
CHANGED
|
@@ -49,9 +49,25 @@
|
|
|
49
49
|
* supplying that out-of-band knowledge yourself.
|
|
50
50
|
*
|
|
51
51
|
* No browser-only imports at module level.
|
|
52
|
+
*
|
|
53
|
+
* `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
|
|
54
|
+
* lazily resolved via `createRequire(import.meta.url)` -- Node's stable
|
|
55
|
+
* synchronous `require()` of an ES module (Node >=22.12/23, well within
|
|
56
|
+
* this package's own `engines.node: >=24` floor), not a dynamic `import()`.
|
|
57
|
+
* `createMeshDht()` is synchronous, has a directly-tested synchronous
|
|
58
|
+
* validation-throw contract (`test/mesh-dht.test.mjs`'s
|
|
59
|
+
* `assert.throws(...)`), and returns `{strategy, dhtNode, teardown}`
|
|
60
|
+
* directly to ~11 synchronous call sites in its own test file -- an async
|
|
61
|
+
* `import()` would have broken all of that (see the CHANGELOG entry
|
|
62
|
+
* documenting this fix across the package). `require()` resolves lazily
|
|
63
|
+
* (only when `createMeshDht()` is actually called, after its own
|
|
64
|
+
* validation throws) while staying fully synchronous, so none of that
|
|
65
|
+
* changes.
|
|
52
66
|
*/
|
|
53
67
|
|
|
54
|
-
import {
|
|
68
|
+
import { createRequire } from 'node:module'
|
|
69
|
+
|
|
70
|
+
const require = createRequire(import.meta.url)
|
|
55
71
|
|
|
56
72
|
/** Default `type` tag for DHT wire messages multiplexed onto a shared transport. */
|
|
57
73
|
const DEFAULT_MESSAGE_TYPE = 'dht-relay'
|
|
@@ -146,6 +162,10 @@ export function createMeshDht({
|
|
|
146
162
|
throw new Error('createMeshDht: options.transport is required and must implement send(msg)/onMessage(cb)')
|
|
147
163
|
}
|
|
148
164
|
|
|
165
|
+
// Lazy, synchronous (see module doc comment) -- only reached once
|
|
166
|
+
// validation above has already passed.
|
|
167
|
+
const { DhtDiscoveryStrategy } = require('@johnhenry/browsermesh-discovery')
|
|
168
|
+
|
|
149
169
|
const sendFn = (targetId, msg) => {
|
|
150
170
|
transport.send({ type: messageType, from: localPodId, to: targetId, payload: msg })
|
|
151
171
|
}
|
package/src/mesh-fetch.mjs
CHANGED
|
@@ -92,9 +92,33 @@
|
|
|
92
92
|
* send failure represents.
|
|
93
93
|
*
|
|
94
94
|
* No browser-only imports at module level.
|
|
95
|
+
*
|
|
96
|
+
* `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
|
|
97
|
+
* lazily resolved via `createRequire(import.meta.url)` -- Node's stable
|
|
98
|
+
* synchronous `require()` of an ES module (Node >=22.12/23, well within
|
|
99
|
+
* this package's own `engines.node: >=24` floor) -- rather than a dynamic
|
|
100
|
+
* `import()`. This matters because `browserMeshFetch(url, init)` below is
|
|
101
|
+
* deliberately NOT async (see "ERROR-VS-REJECT SEMANTICS" above -- it must
|
|
102
|
+
* throw a `TypeError` *synchronously* for a malformed URL, matching real
|
|
103
|
+
* `fetch()`), and `createBrowserMeshFetch()`'s own synchronous
|
|
104
|
+
* meshRpcApi-validation throw is directly tested
|
|
105
|
+
* (`test/mesh-fetch.test.mjs`'s `assert.throws(() => createBrowserMeshFetch(...))`).
|
|
106
|
+
* A dynamic `import()` is inherently async and would have broken both of
|
|
107
|
+
* those; `require()` resolves the module lazily (only when
|
|
108
|
+
* `createBrowserMeshFetch()` is actually called, not at this module's own
|
|
109
|
+
* load time -- achieving the same "optional peer" goal a dynamic import
|
|
110
|
+
* would) while staying fully synchronous, so neither function's signature
|
|
111
|
+
* or throw semantics change at all. See the CHANGELOG entry documenting
|
|
112
|
+
* this fix across the package for the sibling files that use the same
|
|
113
|
+
* technique, and `mesh-websocket.mjs`'s module doc comment for the one
|
|
114
|
+
* case (a constructor) where a dynamic `import()` genuinely could not have
|
|
115
|
+
* worked even with an async rewrite, which is what led to trying
|
|
116
|
+
* `require()` here in the first place.
|
|
95
117
|
*/
|
|
96
118
|
|
|
97
|
-
import {
|
|
119
|
+
import { createRequire } from 'node:module'
|
|
120
|
+
|
|
121
|
+
const require = createRequire(import.meta.url)
|
|
98
122
|
|
|
99
123
|
/**
|
|
100
124
|
* @typedef {object} MeshRpcApi
|
|
@@ -121,6 +145,11 @@ export function createBrowserMeshFetch(meshRpcApi) {
|
|
|
121
145
|
)
|
|
122
146
|
}
|
|
123
147
|
|
|
148
|
+
// Lazy, synchronous (see module doc comment) -- only resolved once a
|
|
149
|
+
// caller actually builds a browserMeshFetch, and cached by require()'s
|
|
150
|
+
// own module cache for every subsequent call.
|
|
151
|
+
const { parseMeshRequest } = require('@johnhenry/browsermesh-discovery')
|
|
152
|
+
|
|
124
153
|
/**
|
|
125
154
|
* `browserMeshFetch()` itself -- deliberately NOT an `async function` (see
|
|
126
155
|
* the module doc comment's "ERROR-VS-REJECT SEMANTICS" section for why: a
|
package/src/mesh-hardening.mjs
CHANGED
|
@@ -85,7 +85,10 @@
|
|
|
85
85
|
* No browser-only imports at module level.
|
|
86
86
|
*/
|
|
87
87
|
|
|
88
|
-
|
|
88
|
+
// @johnhenry/browsermesh-core (an optional peerDependency) is imported
|
|
89
|
+
// lazily inside createHardenedNegotiator() below, not eagerly here -- so
|
|
90
|
+
// this module doesn't force it on every consumer of this package's
|
|
91
|
+
// top-level `.` entrypoint. See the CHANGELOG entry documenting this fix.
|
|
89
92
|
|
|
90
93
|
const DEFAULT_METRICS_KEY = 'unknown'
|
|
91
94
|
|
|
@@ -192,17 +195,21 @@ function instrumentTransport(transport, metrics) {
|
|
|
192
195
|
* `new RetryWithBackoff()` (maxRetries/baseDelayMs/maxDelayMs/jitterFactor/
|
|
193
196
|
* resetTimeoutMs -- see hardening.mjs).
|
|
194
197
|
* @param {Function} [opts.onLog]
|
|
195
|
-
* @returns {{
|
|
198
|
+
* @returns {Promise<{
|
|
196
199
|
* negotiate: (endpoints: object, auth?: object) => Promise<object>,
|
|
197
200
|
* metrics: import('@johnhenry/browsermesh-core').MetricsRegistry,
|
|
198
201
|
* failovers: Map<string, import('@johnhenry/browsermesh-core').TransportFailover>,
|
|
199
202
|
* retries: Map<string, import('@johnhenry/browsermesh-core').RetryWithBackoff>,
|
|
200
|
-
* }}
|
|
203
|
+
* }>}
|
|
201
204
|
*/
|
|
202
|
-
export function createHardenedNegotiator({ negotiator, retryOptions, onLog }) {
|
|
205
|
+
export async function createHardenedNegotiator({ negotiator, retryOptions, onLog }) {
|
|
203
206
|
if (!negotiator) {
|
|
204
207
|
throw new Error('createHardenedNegotiator: options.negotiator is required')
|
|
205
208
|
}
|
|
209
|
+
// Lazily imported (an optional peerDependency) -- see the CHANGELOG entry
|
|
210
|
+
// documenting this fix. BREAKING: this function is now async (was sync);
|
|
211
|
+
// its one in-repo caller (mesh-bootstrap.mjs) is updated to match.
|
|
212
|
+
const { RetryWithBackoff, TransportFailover, MetricsRegistry } = await import('@johnhenry/browsermesh-core')
|
|
206
213
|
const log = onLog || (() => {})
|
|
207
214
|
const metrics = new MetricsRegistry()
|
|
208
215
|
const failovers = new Map()
|
package/src/mesh-keepalive.mjs
CHANGED
|
@@ -117,9 +117,27 @@
|
|
|
117
117
|
* instance was found -- see "HARDENING INTEGRATION" above).
|
|
118
118
|
*
|
|
119
119
|
* No browser-only imports at module level.
|
|
120
|
+
*
|
|
121
|
+
* `@johnhenry/browsermesh-core` (an optional peerDependency) is lazily
|
|
122
|
+
* imported inside `startCheckFor()`, guarded by a reservation/cancellation
|
|
123
|
+
* scheme rather than a bare `checks.has(pubKey)` de-dup: `startCheckFor()`
|
|
124
|
+
* is called both from a synchronous event handler and synchronously inside
|
|
125
|
+
* `attach()`'s initial peer-scan loop, so a naive lazy import would open a
|
|
126
|
+
* real race (two rapid calls for the same peer both passing the de-dup
|
|
127
|
+
* check before the first call's import resolves, leaking an orphaned,
|
|
128
|
+
* un-stoppable `TransportHealthCheck`). The fix: `checks.set(pubKey, {
|
|
129
|
+
* pending: true, cancelled: false })` happens SYNCHRONOUSLY, before the
|
|
130
|
+
* `await import()` -- so the de-dup guard (`checks.has(pubKey)`) is
|
|
131
|
+
* correct the instant `startCheckFor()` returns, regardless of how long
|
|
132
|
+
* the import takes. A concurrent `stopCheckFor()` arriving while pending
|
|
133
|
+
* flips `cancelled` and removes the map entry immediately; when the import
|
|
134
|
+
* later resolves, a cancelled reservation is a no-op (no orphaned check
|
|
135
|
+
* gets installed). Every other `checks.get(pubKey)` read site (the pong
|
|
136
|
+
* handler, `handleTransportClose`/`handleTransportError`,
|
|
137
|
+
* `getStatus()`/`getCheck()`) is reservation-aware -- see each site's own
|
|
138
|
+
* comment. See `test/mesh-keepalive.test.mjs`'s dedicated race tests.
|
|
120
139
|
*/
|
|
121
140
|
|
|
122
|
-
import { TransportHealthCheck } from '@johnhenry/browsermesh-core'
|
|
123
141
|
import { endpointsKey } from './mesh-hardening.mjs'
|
|
124
142
|
|
|
125
143
|
/** Envelope type for the outbound liveness probe. */
|
|
@@ -172,9 +190,19 @@ export function createMeshKeepaliveService({
|
|
|
172
190
|
)
|
|
173
191
|
}
|
|
174
192
|
|
|
175
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* pubKey -> either a real health check, or a pending reservation
|
|
195
|
+
* (`{pending: true, cancelled: boolean}`) while `TransportHealthCheck`
|
|
196
|
+
* is being lazily imported -- see module doc comment.
|
|
197
|
+
* @type {Map<string, import('@johnhenry/browsermesh-core').TransportHealthCheck | {pending: true, cancelled: boolean}>}
|
|
198
|
+
*/
|
|
176
199
|
const checks = new Map()
|
|
177
200
|
|
|
201
|
+
/** @param {*} entry @returns {boolean} */
|
|
202
|
+
function isReservation(entry) {
|
|
203
|
+
return !!entry && entry.pending === true
|
|
204
|
+
}
|
|
205
|
+
|
|
178
206
|
/**
|
|
179
207
|
* Best-effort lookup of the `TransportFailover` instance
|
|
180
208
|
* `mesh-hardening.mjs` scoped to this peer -- see module doc comment's
|
|
@@ -204,10 +232,33 @@ export function createMeshKeepaliveService({
|
|
|
204
232
|
}
|
|
205
233
|
}
|
|
206
234
|
|
|
207
|
-
/**
|
|
235
|
+
/**
|
|
236
|
+
* Claims the `pubKey` slot synchronously (closing the lazy-import
|
|
237
|
+
* race -- see module doc comment), then lazily imports
|
|
238
|
+
* `TransportHealthCheck` and installs a real check, unless the
|
|
239
|
+
* reservation was cancelled (via `stopCheckFor()`) in the meantime.
|
|
240
|
+
* @param {string} pubKey
|
|
241
|
+
*/
|
|
208
242
|
function startCheckFor(pubKey) {
|
|
209
243
|
if (!pubKey || checks.has(pubKey)) return
|
|
210
244
|
|
|
245
|
+
const reservation = { pending: true, cancelled: false }
|
|
246
|
+
checks.set(pubKey, reservation)
|
|
247
|
+
|
|
248
|
+
buildCheck(pubKey, reservation).catch((err) => {
|
|
249
|
+
if (checks.get(pubKey) === reservation) checks.delete(pubKey)
|
|
250
|
+
log('mesh-keepalive:start-check-failed', { pubKey, error: err?.message || String(err) })
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* @param {string} pubKey
|
|
256
|
+
* @param {{pending: true, cancelled: boolean}} reservation
|
|
257
|
+
*/
|
|
258
|
+
async function buildCheck(pubKey, reservation) {
|
|
259
|
+
const { TransportHealthCheck } = await import('@johnhenry/browsermesh-core')
|
|
260
|
+
if (reservation.cancelled) return
|
|
261
|
+
|
|
211
262
|
const check = new TransportHealthCheck({
|
|
212
263
|
// TransportHealthCheck requires a truthy `transport` but only
|
|
213
264
|
// threads it through to pingFn/its own emitted event payloads --
|
|
@@ -242,12 +293,21 @@ export function createMeshKeepaliveService({
|
|
|
242
293
|
check.start()
|
|
243
294
|
}
|
|
244
295
|
|
|
245
|
-
/**
|
|
296
|
+
/**
|
|
297
|
+
* If `pubKey` is still a pending reservation, cancels it (the
|
|
298
|
+
* in-flight lazy import will no-op when it resolves). Otherwise stops
|
|
299
|
+
* and removes the real check.
|
|
300
|
+
* @param {string} pubKey
|
|
301
|
+
*/
|
|
246
302
|
function stopCheckFor(pubKey) {
|
|
247
|
-
const
|
|
248
|
-
if (!
|
|
249
|
-
check.stop()
|
|
303
|
+
const entry = checks.get(pubKey)
|
|
304
|
+
if (!entry) return
|
|
250
305
|
checks.delete(pubKey)
|
|
306
|
+
if (isReservation(entry)) {
|
|
307
|
+
entry.cancelled = true
|
|
308
|
+
return
|
|
309
|
+
}
|
|
310
|
+
entry.stop()
|
|
251
311
|
}
|
|
252
312
|
|
|
253
313
|
// -----------------------------------------------------------------
|
|
@@ -264,15 +324,19 @@ export function createMeshKeepaliveService({
|
|
|
264
324
|
// NATIVE-TRANSPORT-CLOSE WIRING". A stronger, immediate signal than
|
|
265
325
|
// waiting out maxMissed ping/pong cycles.
|
|
266
326
|
function handleTransportClose({ pubKey } = {}) {
|
|
267
|
-
|
|
268
|
-
|
|
327
|
+
const entry = checks.get(pubKey)
|
|
328
|
+
if (!pubKey || !entry) return
|
|
329
|
+
// A pending reservation has 0 missed pings so far -- matches
|
|
330
|
+
// TransportHealthCheck's own #missedCount = 0 default (hardening.mjs).
|
|
331
|
+
ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: isReservation(entry) ? 0 : entry.missedCount, reason: 'transport-close' })
|
|
269
332
|
triggerFailover(pubKey, 'keepalive:transport-close').catch((err) => {
|
|
270
333
|
log('mesh-keepalive:trigger-failover-error', { pubKey, error: err?.message || String(err) })
|
|
271
334
|
})
|
|
272
335
|
}
|
|
273
336
|
function handleTransportError({ pubKey, error } = {}) {
|
|
274
|
-
|
|
275
|
-
|
|
337
|
+
const entry = checks.get(pubKey)
|
|
338
|
+
if (!pubKey || !entry) return
|
|
339
|
+
ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: isReservation(entry) ? 0 : entry.missedCount, reason: 'transport-error' })
|
|
276
340
|
log('mesh-keepalive:transport-error', { pubKey, error })
|
|
277
341
|
triggerFailover(pubKey, 'keepalive:transport-error').catch((err) => {
|
|
278
342
|
log('mesh-keepalive:trigger-failover-error', { pubKey, error: err?.message || String(err) })
|
|
@@ -307,8 +371,12 @@ export function createMeshKeepaliveService({
|
|
|
307
371
|
log('mesh-keepalive:pong-send-failed', { to: fromPubKey, error: err?.message || String(err) })
|
|
308
372
|
})
|
|
309
373
|
} else if (msg.type === PONG_TYPE) {
|
|
310
|
-
const
|
|
311
|
-
|
|
374
|
+
const entry = checks.get(fromPubKey)
|
|
375
|
+
// A pong arriving while still a pending reservation would be a
|
|
376
|
+
// stray/duplicate from a prior connection -- this file can't have
|
|
377
|
+
// sent a ping for this peer yet (check.start() hasn't run), so
|
|
378
|
+
// it's safe to drop.
|
|
379
|
+
if (entry && !isReservation(entry)) entry.recordPong()
|
|
312
380
|
}
|
|
313
381
|
})
|
|
314
382
|
|
|
@@ -316,18 +384,29 @@ export function createMeshKeepaliveService({
|
|
|
316
384
|
/**
|
|
317
385
|
* @param {string} pubKey
|
|
318
386
|
* @returns {'healthy'|'degraded'|'unhealthy'|null} `null` if this
|
|
319
|
-
* peer is not currently tracked (never connected
|
|
320
|
-
* disconnected).
|
|
387
|
+
* peer is not currently tracked (never connected or already
|
|
388
|
+
* disconnected). A pending reservation (lazy import still in
|
|
389
|
+
* flight) reports `'healthy'` -- matching `TransportHealthCheck`'s
|
|
390
|
+
* own `#status = 'healthy'` default at construction, before
|
|
391
|
+
* `start()` runs (`hardening.mjs`) -- not `null`, so callers see
|
|
392
|
+
* the exact same synchronous-default behavior as before this file
|
|
393
|
+
* lazy-loaded the class.
|
|
321
394
|
*/
|
|
322
395
|
getStatus(pubKey) {
|
|
323
|
-
|
|
396
|
+
const entry = checks.get(pubKey)
|
|
397
|
+
if (!entry) return null
|
|
398
|
+
return isReservation(entry) ? 'healthy' : entry.status
|
|
324
399
|
},
|
|
325
400
|
/**
|
|
326
401
|
* @param {string} pubKey
|
|
327
402
|
* @returns {import('@johnhenry/browsermesh-core').TransportHealthCheck|null}
|
|
403
|
+
* `null` also while a pending reservation hasn't finished
|
|
404
|
+
* installing yet -- never returns the internal reservation shape.
|
|
328
405
|
*/
|
|
329
406
|
getCheck(pubKey) {
|
|
330
|
-
|
|
407
|
+
const entry = checks.get(pubKey)
|
|
408
|
+
if (!entry || isReservation(entry)) return null
|
|
409
|
+
return entry
|
|
331
410
|
},
|
|
332
411
|
/** @returns {string[]} pubKeys currently tracked. */
|
|
333
412
|
listTracked() {
|
|
@@ -23,9 +23,34 @@
|
|
|
23
23
|
* explicit "out of scope" list (UDP relay, inbound listen-relay).
|
|
24
24
|
*
|
|
25
25
|
* No browser-only imports at module level.
|
|
26
|
+
*
|
|
27
|
+
* `@johnhenry/browsermesh-netway` (an optional peerDependency) is lazily
|
|
28
|
+
* resolved via `createRequire(import.meta.url)` -- Node's stable
|
|
29
|
+
* synchronous `require()` of an ES module (Node >=22.12/23, well within
|
|
30
|
+
* this package's own `engines.node: >=24` floor). `Backend` is used as a
|
|
31
|
+
* base class (`class MeshRelayBackend extends Backend`); a class's
|
|
32
|
+
* `extends` clause is evaluated at class-DECLARATION time, and a
|
|
33
|
+
* `class ... extends ... {}` statement written at module top level always
|
|
34
|
+
* runs at module-LOAD time, no matter how the `Backend` reference feeding
|
|
35
|
+
* it is obtained -- there is no way to defer that with a plain lazy
|
|
36
|
+
* import, sync or async (see `cloud-storage-backend.mjs`'s identical
|
|
37
|
+
* constraint). The fix here instead moves the class declaration itself out
|
|
38
|
+
* of module-top-level scope, into a function that resolves `Backend` via
|
|
39
|
+
* `require()` and builds+memoizes the class on first call, so it still
|
|
40
|
+
* only runs once, lazily, the first time this file is actually used, not
|
|
41
|
+
* merely imported.
|
|
42
|
+
*
|
|
43
|
+
* **BREAKING CHANGE**: `MeshRelayBackend` is no longer exported as a
|
|
44
|
+
* class. Replace `new MeshRelayBackend(opts)` with
|
|
45
|
+
* `createMeshRelayBackend(opts)` (same `opts` shape, still returns a real
|
|
46
|
+
* `MeshRelayBackend` instance with the exact same instance API) -- see the
|
|
47
|
+
* CHANGELOG entry documenting this fix across the package for the full
|
|
48
|
+
* rationale and the sibling `cloud-storage-backend.mjs` fix.
|
|
26
49
|
*/
|
|
27
50
|
|
|
28
|
-
import {
|
|
51
|
+
import { createRequire } from 'node:module'
|
|
52
|
+
|
|
53
|
+
const require = createRequire(import.meta.url)
|
|
29
54
|
|
|
30
55
|
/** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
|
|
31
56
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
|
|
@@ -62,13 +87,26 @@ function fromBase64(str) {
|
|
|
62
87
|
// MeshRelayBackend
|
|
63
88
|
// ---------------------------------------------------------------------------
|
|
64
89
|
|
|
90
|
+
let _MeshRelayBackendClass = null
|
|
91
|
+
|
|
65
92
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
93
|
+
* Lazily builds (and memoizes) the `MeshRelayBackend` class, deferring
|
|
94
|
+
* resolution of `@johnhenry/browsermesh-netway`'s `Backend` past
|
|
95
|
+
* module-load time -- see module doc comment. Only ever runs once per
|
|
96
|
+
* process; every later call returns the same class reference.
|
|
97
|
+
* @returns {typeof MeshRelayBackend}
|
|
70
98
|
*/
|
|
71
|
-
|
|
99
|
+
function resolveMeshRelayBackendClass() {
|
|
100
|
+
if (_MeshRelayBackendClass) return _MeshRelayBackendClass
|
|
101
|
+
const { Backend, StreamSocket, ConnectionRefusedError } = require('@johnhenry/browsermesh-netway')
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A `Backend` that relays TCP-like `connect()`s through one specific mesh
|
|
105
|
+
* peer's `MeshRelayHost`, over `PeerNode.sendTo()`/`onIncomingData()`.
|
|
106
|
+
*
|
|
107
|
+
* @extends Backend
|
|
108
|
+
*/
|
|
109
|
+
class MeshRelayBackend extends Backend {
|
|
72
110
|
/** @type {import('./peer-node.mjs').PeerNode} */
|
|
73
111
|
#node
|
|
74
112
|
|
|
@@ -284,6 +322,24 @@ export class MeshRelayBackend extends Backend {
|
|
|
284
322
|
pending.reject(new Error('MeshRelayBackend closed'))
|
|
285
323
|
}
|
|
286
324
|
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
_MeshRelayBackendClass = MeshRelayBackend
|
|
328
|
+
return MeshRelayBackend
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Construct a `MeshRelayBackend` -- the class itself is no longer exported
|
|
333
|
+
* directly (see module doc comment's "BREAKING CHANGE" note).
|
|
334
|
+
*
|
|
335
|
+
* @param {object} opts - Same shape as `MeshRelayBackend`'s constructor:
|
|
336
|
+
* `{node, relayPeerPubKey, envelopeType?, connectTimeoutMs?, onLog?}`.
|
|
337
|
+
* @returns {import('@johnhenry/browsermesh-netway').Backend} A real
|
|
338
|
+
* `MeshRelayBackend` instance (the full instance API is unchanged).
|
|
339
|
+
*/
|
|
340
|
+
export function createMeshRelayBackend(opts) {
|
|
341
|
+
const MeshRelayBackend = resolveMeshRelayBackendClass()
|
|
342
|
+
return new MeshRelayBackend(opts)
|
|
287
343
|
}
|
|
288
344
|
|
|
289
345
|
export { DEFAULT_ENVELOPE_TYPE }
|
package/src/mesh-swarm.mjs
CHANGED
|
@@ -204,16 +204,24 @@
|
|
|
204
204
|
* received a task notification from a remote submitter.
|
|
205
205
|
*
|
|
206
206
|
* No browser-only imports at module level.
|
|
207
|
+
*
|
|
208
|
+
* `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
|
|
209
|
+
* lazily resolved via `createRequire(import.meta.url)` -- Node's stable
|
|
210
|
+
* synchronous `require()` of an ES module (Node >=22.12/23, well within
|
|
211
|
+
* this package's own `engines.node: >=24` floor), not a dynamic `import()`.
|
|
212
|
+
* `SwimMembership`/`SwarmCoordinator` are both constructed synchronously
|
|
213
|
+
* inside this service's `attach()`, whose synchronous-return contract is a
|
|
214
|
+
* hard, repo-wide convention (`mesh-service.mjs`'s `attachService()`,
|
|
215
|
+
* relied on -- without `await` -- throughout `mesh-bootstrap.mjs`); an
|
|
216
|
+
* async `import()` would have broken that (see the CHANGELOG entry
|
|
217
|
+
* documenting this fix across the package). `require()` resolves lazily
|
|
218
|
+
* (only when `attach()` actually runs) while staying fully synchronous, so
|
|
219
|
+
* `attach()`'s contract doesn't change.
|
|
207
220
|
*/
|
|
208
221
|
|
|
209
|
-
import {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
SWARM_JOIN,
|
|
213
|
-
SWARM_LEAVE,
|
|
214
|
-
SWARM_HEARTBEAT,
|
|
215
|
-
SWARM_TASK_ASSIGN,
|
|
216
|
-
} from '@johnhenry/browsermesh-discovery'
|
|
222
|
+
import { createRequire } from 'node:module'
|
|
223
|
+
|
|
224
|
+
const require = createRequire(import.meta.url)
|
|
217
225
|
|
|
218
226
|
const DEFAULT_SWIM_ENVELOPE_TYPE = 'swarm-swim'
|
|
219
227
|
const DEFAULT_HEARTBEAT_ENVELOPE_TYPE = 'swarm-heartbeat'
|
|
@@ -279,6 +287,16 @@ export function createSwarmService(opts = {}) {
|
|
|
279
287
|
attach(peerNode, ctx) {
|
|
280
288
|
const localPodId = peerNode.podId
|
|
281
289
|
|
|
290
|
+
// Lazy, synchronous (see module doc comment).
|
|
291
|
+
const {
|
|
292
|
+
SwarmCoordinator,
|
|
293
|
+
SwimMembership,
|
|
294
|
+
SWARM_JOIN,
|
|
295
|
+
SWARM_LEAVE,
|
|
296
|
+
SWARM_HEARTBEAT,
|
|
297
|
+
SWARM_TASK_ASSIGN,
|
|
298
|
+
} = require('@johnhenry/browsermesh-discovery')
|
|
299
|
+
|
|
282
300
|
// -----------------------------------------------------------------
|
|
283
301
|
// SwimMembership -- see module doc comment's "SWIM BRIDGE" section.
|
|
284
302
|
// -----------------------------------------------------------------
|
package/src/mesh-websocket.mjs
CHANGED
|
@@ -205,9 +205,28 @@
|
|
|
205
205
|
* side (this peer's own `close()` or a received `ws-close`).
|
|
206
206
|
*
|
|
207
207
|
* No browser-only imports at module level.
|
|
208
|
+
*
|
|
209
|
+
* `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
|
|
210
|
+
* lazily resolved via `createRequire(import.meta.url)` -- Node's stable
|
|
211
|
+
* synchronous `require()` of an ES module (Node >=22.12/23, well within
|
|
212
|
+
* this package's own `engines.node: >=24` floor). This is the file that
|
|
213
|
+
* motivated trying `require()` at all: `parseMeshRequest()` is used inside
|
|
214
|
+
* `BrowserMeshWebSocket`'s *constructor*, which can never be `async` --
|
|
215
|
+
* `import()` was a dead end here (an async factory replacing direct `new
|
|
216
|
+
* BrowserMeshWebSocket(...)` construction would have been a real,
|
|
217
|
+
* unwanted breaking change to this class's whole reason for existing: matching
|
|
218
|
+
* real `new WebSocket(url)` construction ergonomics as closely as
|
|
219
|
+
* possible, per this file's own "API SHAPE DECISION" precedent in
|
|
220
|
+
* `mesh-fetch.mjs`). `require()` resolves synchronously, so it works
|
|
221
|
+
* directly inside the constructor with zero API changes: the module is
|
|
222
|
+
* only actually loaded the first time a `BrowserMeshWebSocket` is
|
|
223
|
+
* constructed (or `createMeshWebSocketService()`'s `api.connect()` is
|
|
224
|
+
* called), not at this module's own load time.
|
|
208
225
|
*/
|
|
209
226
|
|
|
210
|
-
import {
|
|
227
|
+
import { createRequire } from 'node:module'
|
|
228
|
+
|
|
229
|
+
const require = createRequire(import.meta.url)
|
|
211
230
|
|
|
212
231
|
/** Default `envelope.type` used to route mesh-websocket payloads on the shared `onIncomingData()` bus. */
|
|
213
232
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-websocket'
|
|
@@ -355,6 +374,9 @@ export class BrowserMeshWebSocket {
|
|
|
355
374
|
if (!peerNode || typeof peerNode.sendTo !== 'function' || typeof peerNode.onIncomingData !== 'function') {
|
|
356
375
|
throw new Error('BrowserMeshWebSocket: opts.peerNode is required and must provide sendTo()/onIncomingData()')
|
|
357
376
|
}
|
|
377
|
+
// Lazy, synchronous (see module doc comment) -- cached by require()'s
|
|
378
|
+
// own module cache after the first construction.
|
|
379
|
+
const { parseMeshRequest } = require('@johnhenry/browsermesh-discovery')
|
|
358
380
|
const parsed = parseMeshRequest(url)
|
|
359
381
|
if (!parsed) {
|
|
360
382
|
throw new Error(`BrowserMeshWebSocket: invalid mesh URL '${url}' (expected mesh://podId/path or https://podId.mesh.local/path)`)
|
package/src/serverless-fetch.mjs
CHANGED
|
@@ -33,11 +33,28 @@
|
|
|
33
33
|
* option's shape exactly, no adapter needed.
|
|
34
34
|
*
|
|
35
35
|
* @module serverless-fetch
|
|
36
|
+
*
|
|
37
|
+
* `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
|
|
38
|
+
* lazily resolved via `createRequire(import.meta.url)` -- Node's stable
|
|
39
|
+
* synchronous `require()` of an ES module (Node >=22.12/23, well within
|
|
40
|
+
* this package's own `engines.node: >=24` floor), not a dynamic `import()`.
|
|
41
|
+
* `createServerlessFetchRouter()` is synchronous, has a directly-tested
|
|
42
|
+
* synchronous validation-throw contract (`test/serverless-fetch.test.mjs`'s
|
|
43
|
+
* `assert.throws(...)`), and returns a real `MeshFetchRouter` instance
|
|
44
|
+
* directly to ~10 synchronous call sites in its own test file -- an async
|
|
45
|
+
* `import()` would have broken all of that (see the CHANGELOG entry
|
|
46
|
+
* documenting this fix across the package). `require()` resolves lazily
|
|
47
|
+
* (only when `createServerlessFetchRouter()` is actually called, after its
|
|
48
|
+
* own validation throw) while staying fully synchronous, so none of that
|
|
49
|
+
* changes.
|
|
36
50
|
*/
|
|
37
51
|
|
|
38
|
-
import {
|
|
52
|
+
import { createRequire } from 'node:module'
|
|
53
|
+
|
|
39
54
|
import { decodeWireResponse } from './serverless-wire.mjs'
|
|
40
55
|
|
|
56
|
+
const require = createRequire(import.meta.url)
|
|
57
|
+
|
|
41
58
|
/**
|
|
42
59
|
* @param {{request: (podId: string, req: {method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}>}} meshRpcApi
|
|
43
60
|
* The `.api` returned by attaching a `mesh-rpc.mjs`-based service bound to
|
|
@@ -59,6 +76,9 @@ export function createServerlessFetchRouter(meshRpcApi, { resolveSite } = {}) {
|
|
|
59
76
|
throw new Error('createServerlessFetchRouter: meshRpcApi (a mesh-rpc.mjs service api with .request()) is required')
|
|
60
77
|
}
|
|
61
78
|
|
|
79
|
+
// Lazy, synchronous (see module doc comment).
|
|
80
|
+
const { MeshFetchRouter } = require('@johnhenry/browsermesh-discovery')
|
|
81
|
+
|
|
62
82
|
return new MeshFetchRouter({
|
|
63
83
|
onRpc: async ({ podId: siteOrPodId, method, path, headers, body }) => {
|
|
64
84
|
const resolved = typeof resolveSite === 'function' ? resolveSite(siteOrPodId) : null
|
|
@@ -30,9 +30,11 @@
|
|
|
30
30
|
* regardless of which side initiated it.
|
|
31
31
|
*
|
|
32
32
|
* ## Multiple connections per peer (issue #116)
|
|
33
|
-
* `auth.connectionId` (default `DEFAULT_CONNECTION_ID`,
|
|
34
|
-
* `@johnhenry/browsermesh-transport`
|
|
35
|
-
*
|
|
33
|
+
* `auth.connectionId` (default `DEFAULT_CONNECTION_ID`, duplicated locally
|
|
34
|
+
* in this file rather than imported from `@johnhenry/browsermesh-transport`
|
|
35
|
+
* -- see that constant's own definition below for why) selects which of
|
|
36
|
+
* possibly-several independent `RTCPeerConnection`s to `endpoint` this call
|
|
37
|
+
* negotiates --
|
|
36
38
|
* `PeerNode.connectToPeer(pubKey, endpoints, auth)` already threads `auth`
|
|
37
39
|
* straight through to `negotiator.negotiate(endpoints, auth)`, so callers
|
|
38
40
|
* can request a second, fully independent connection to a peer already
|
|
@@ -48,7 +50,21 @@
|
|
|
48
50
|
* No browser-only imports at module level.
|
|
49
51
|
*/
|
|
50
52
|
|
|
51
|
-
|
|
53
|
+
// @johnhenry/browsermesh-transport (an optional peerDependency) is imported
|
|
54
|
+
// lazily, at each of the two `WebRTCTransportAdapter` call sites below, not
|
|
55
|
+
// eagerly here -- so this module doesn't force it on every consumer of
|
|
56
|
+
// this package's top-level `.` entrypoint. See the CHANGELOG entry
|
|
57
|
+
// documenting this fix.
|
|
58
|
+
//
|
|
59
|
+
// DEFAULT_CONNECTION_ID is duplicated locally (its real value, confirmed by
|
|
60
|
+
// reading browsermesh-transport/src/webrtc.mjs directly: `export const
|
|
61
|
+
// DEFAULT_CONNECTION_ID = 'default'`) rather than lazily imported --
|
|
62
|
+
// unlike WebRTCTransportAdapter, it's used as a *default parameter value*
|
|
63
|
+
// in several places below, which is evaluated at call time from whatever
|
|
64
|
+
// is in scope; a lazily-imported `let` binding could still be `undefined`
|
|
65
|
+
// the first time one of those calls happens before the import resolves. A
|
|
66
|
+
// plain literal has no such timing hazard.
|
|
67
|
+
const DEFAULT_CONNECTION_ID = 'default'
|
|
52
68
|
|
|
53
69
|
/** Default time to wait for an SDP answer before giving up. */
|
|
54
70
|
const DEFAULT_ANSWER_TIMEOUT_MS = 15_000
|
|
@@ -158,6 +174,7 @@ export function createWebRTCTransportFactory({
|
|
|
158
174
|
// side gets from connectToPeer() -- see PeerNode.adoptIncomingSession().
|
|
159
175
|
if (typeof onIncomingConnection === 'function') {
|
|
160
176
|
await waitForOpen(conn, defaultOpenTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS)
|
|
177
|
+
const { WebRTCTransportAdapter } = await import('@johnhenry/browsermesh-transport')
|
|
161
178
|
const adapter = new WebRTCTransportAdapter(conn)
|
|
162
179
|
await adapter.connect()
|
|
163
180
|
onIncomingConnection(fromPodId, adapter, connectionId)
|
|
@@ -222,6 +239,7 @@ export function createWebRTCTransportFactory({
|
|
|
222
239
|
throw new Error(`WebRTC DataChannel with ${remotePodId} did not open in time`)
|
|
223
240
|
}
|
|
224
241
|
|
|
242
|
+
const { WebRTCTransportAdapter } = await import('@johnhenry/browsermesh-transport')
|
|
225
243
|
const adapter = new WebRTCTransportAdapter(conn)
|
|
226
244
|
await adapter.connect()
|
|
227
245
|
return adapter
|