@johnhenry/browsermesh-apps 0.0.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/apps.mjs ADDED
@@ -0,0 +1,1351 @@
1
+ /**
2
+ * clawser-mesh-apps.js -- Decentralized App Ecosystem for BrowserMesh.
3
+ *
4
+ * Provides a full app lifecycle for mesh-distributed applications:
5
+ * manifest definition, installation, permission checking, a distributed
6
+ * app store, inter-app RPC, and pub/sub eventing.
7
+ *
8
+ * Classes:
9
+ * AppManifest, AppInstance, AppPermissionChecker, AppRegistry,
10
+ * AppStore, AppRPC, AppEventBus
11
+ *
12
+ * No browser-only imports at module level.
13
+ *
14
+ * Run tests:
15
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-apps.test.mjs
16
+ */
17
+
18
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
19
+ import { silentCatch } from './silent-catch.mjs'
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Wire Constants (re-exported from canonical registry)
23
+ // ---------------------------------------------------------------------------
24
+
25
+ export const APP_MANIFEST = MESH_TYPE.APP_MANIFEST; // 0xe5
26
+ export const APP_INSTALL = MESH_TYPE.APP_INSTALL; // 0xe6
27
+ export const APP_UNINSTALL = MESH_TYPE.APP_UNINSTALL; // 0xe7
28
+ export const APP_STATE_SYNC = MESH_TYPE.APP_STATE_SYNC; // 0xe8
29
+ export const APP_RPC = MESH_TYPE.APP_RPC; // 0xe9
30
+ export const APP_EVENT = MESH_TYPE.APP_EVENT; // 0xea
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Valid permissions
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /** @type {readonly string[]} */
37
+ const VALID_PERMISSIONS = Object.freeze([
38
+ 'net', 'fs', 'identity', 'mesh', 'payment', 'compute', 'storage',
39
+ ]);
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // Version helpers
43
+ // ---------------------------------------------------------------------------
44
+
45
+ /**
46
+ * Check if a string matches semver-like x.y.z format.
47
+ *
48
+ * @param {string} v
49
+ * @returns {boolean}
50
+ */
51
+ function isValidVersion(v) {
52
+ return /^\d+\.\d+\.\d+$/.test(v);
53
+ }
54
+
55
+ /**
56
+ * Compare two semver-like version strings.
57
+ * Returns negative if a < b, 0 if equal, positive if a > b.
58
+ *
59
+ * @param {string} a
60
+ * @param {string} b
61
+ * @returns {number}
62
+ */
63
+ function compareVersions(a, b) {
64
+ const pa = a.split('.').map(Number);
65
+ const pb = b.split('.').map(Number);
66
+ for (let i = 0; i < 3; i++) {
67
+ if (pa[i] !== pb[i]) return pa[i] - pb[i];
68
+ }
69
+ return 0;
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // AppManifest
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /**
77
+ * Describes a mesh-distributed app.
78
+ *
79
+ * @class
80
+ */
81
+ export class AppManifest {
82
+ /**
83
+ * @param {object} opts
84
+ * @param {string} opts.id - Unique app identifier
85
+ * @param {string} opts.name - Human-readable name
86
+ * @param {string} opts.version - Semver-like version (x.y.z)
87
+ * @param {string|null} [opts.description]
88
+ * @param {string|null} [opts.author] - Pod ID of the author
89
+ * @param {string[]} opts.permissions - Required permissions
90
+ * @param {string} opts.entryPoint - URL or path to app entry
91
+ * @param {Array<{id: string, minVersion?: string}>} [opts.dependencies]
92
+ * @param {number} [opts.minPeers]
93
+ * @param {number|null} [opts.maxPeers]
94
+ * @param {object} [opts.metadata]
95
+ * @param {number|null} [opts.publishedAt]
96
+ * @param {string|null} [opts.signature]
97
+ */
98
+ constructor({
99
+ id,
100
+ name,
101
+ version,
102
+ description = null,
103
+ author = null,
104
+ permissions = [],
105
+ entryPoint,
106
+ dependencies = [],
107
+ minPeers = 1,
108
+ maxPeers = null,
109
+ metadata = {},
110
+ publishedAt = null,
111
+ signature = null,
112
+ } = {}) {
113
+ if (!id) throw new Error('id is required');
114
+ if (!name) throw new Error('name is required');
115
+ if (!version) throw new Error('version is required');
116
+ if (!entryPoint) throw new Error('entryPoint is required');
117
+
118
+ this.id = id;
119
+ this.name = name;
120
+ this.version = version;
121
+ this.description = description;
122
+ this.author = author;
123
+ this.permissions = [...permissions];
124
+ this.entryPoint = entryPoint;
125
+ this.dependencies = dependencies.map((d) => ({ ...d }));
126
+ this.minPeers = minPeers;
127
+ this.maxPeers = maxPeers;
128
+ this.metadata = { ...metadata };
129
+ this.publishedAt = publishedAt;
130
+ this.signature = signature;
131
+ }
132
+
133
+ /**
134
+ * Validate the manifest: required fields, version format.
135
+ *
136
+ * @returns {boolean}
137
+ */
138
+ validate() {
139
+ if (!this.id || !this.name || !this.version || !this.entryPoint) {
140
+ return false;
141
+ }
142
+ if (!isValidVersion(this.version)) {
143
+ return false;
144
+ }
145
+ return true;
146
+ }
147
+
148
+ /**
149
+ * Check whether this manifest satisfies a given dependency.
150
+ *
151
+ * @param {{ id: string, minVersion?: string }} dep
152
+ * @returns {boolean}
153
+ */
154
+ satisfiesDependency(dep) {
155
+ if (this.id !== dep.id) return false;
156
+ if (dep.minVersion) {
157
+ return compareVersions(this.version, dep.minVersion) >= 0;
158
+ }
159
+ return true;
160
+ }
161
+
162
+ /**
163
+ * Serialize to a plain JSON-safe object.
164
+ *
165
+ * @returns {object}
166
+ */
167
+ toJSON() {
168
+ return {
169
+ id: this.id,
170
+ name: this.name,
171
+ version: this.version,
172
+ description: this.description,
173
+ author: this.author,
174
+ permissions: [...this.permissions],
175
+ entryPoint: this.entryPoint,
176
+ dependencies: this.dependencies.map((d) => ({ ...d })),
177
+ minPeers: this.minPeers,
178
+ maxPeers: this.maxPeers,
179
+ metadata: { ...this.metadata },
180
+ publishedAt: this.publishedAt,
181
+ signature: this.signature,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Deserialize from a plain object.
187
+ *
188
+ * @param {object} data
189
+ * @returns {AppManifest}
190
+ */
191
+ static fromJSON(data) {
192
+ return new AppManifest(data);
193
+ }
194
+ }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // AppInstance
198
+ // ---------------------------------------------------------------------------
199
+
200
+ /**
201
+ * Valid app states.
202
+ * @type {readonly string[]}
203
+ */
204
+ const APP_STATES = Object.freeze([
205
+ 'installed', 'starting', 'running', 'paused', 'stopping', 'stopped', 'error',
206
+ ]);
207
+
208
+ /**
209
+ * A running instance of an app.
210
+ *
211
+ * @class
212
+ */
213
+ export class AppInstance {
214
+ /** @type {AppManifest} */
215
+ manifest;
216
+
217
+ /** @type {string} */
218
+ installedBy;
219
+
220
+ /** @type {number} */
221
+ installedAt;
222
+
223
+ /** @type {string} */
224
+ #state;
225
+
226
+ /** @type {object} */
227
+ #data;
228
+
229
+ /** @type {string[]} */
230
+ #peers;
231
+
232
+ /**
233
+ * @param {object} opts
234
+ * @param {AppManifest} opts.manifest
235
+ * @param {string} opts.installedBy - Pod ID of the installer
236
+ * @param {number} [opts.installedAt]
237
+ * @param {string} [opts.state]
238
+ * @param {object} [opts.data]
239
+ * @param {string[]} [opts.peers]
240
+ */
241
+ constructor({
242
+ manifest,
243
+ installedBy,
244
+ installedAt = Date.now(),
245
+ state = 'installed',
246
+ data = {},
247
+ peers = [],
248
+ } = {}) {
249
+ if (!manifest) throw new Error('manifest is required');
250
+ if (!installedBy) throw new Error('installedBy is required');
251
+
252
+ this.manifest = manifest;
253
+ this.installedBy = installedBy;
254
+ this.installedAt = installedAt;
255
+ this.#state = state;
256
+ this.#data = { ...data };
257
+ this.#peers = [...peers];
258
+ }
259
+
260
+ // -- Accessors ------------------------------------------------------------
261
+
262
+ /** App ID from manifest. */
263
+ get id() {
264
+ return this.manifest.id;
265
+ }
266
+
267
+ /** App name from manifest. */
268
+ get name() {
269
+ return this.manifest.name;
270
+ }
271
+
272
+ /** Current state. */
273
+ get state() {
274
+ return this.#state;
275
+ }
276
+
277
+ /** Current app data (copy). */
278
+ get data() {
279
+ return { ...this.#data };
280
+ }
281
+
282
+ /** Current peers (copy). */
283
+ get peers() {
284
+ return [...this.#peers];
285
+ }
286
+
287
+ // -- State transitions ----------------------------------------------------
288
+
289
+ /**
290
+ * Start the app: installed/paused -> starting -> running.
291
+ * Throws if current state does not allow starting.
292
+ */
293
+ start() {
294
+ if (this.#state !== 'installed' && this.#state !== 'paused') {
295
+ throw new Error(`Cannot start app in state '${this.#state}'`);
296
+ }
297
+ this.#state = 'starting';
298
+ this.#state = 'running';
299
+ }
300
+
301
+ /**
302
+ * Pause the app: running -> paused.
303
+ * Throws if not running.
304
+ */
305
+ pause() {
306
+ if (this.#state !== 'running') {
307
+ throw new Error(`Cannot pause app in state '${this.#state}'`);
308
+ }
309
+ this.#state = 'paused';
310
+ }
311
+
312
+ /**
313
+ * Stop the app: any active state -> stopping -> stopped.
314
+ * Throws if already stopped.
315
+ */
316
+ stop() {
317
+ if (this.#state === 'stopped') {
318
+ throw new Error(`Cannot stop app in state '${this.#state}'`);
319
+ }
320
+ this.#state = 'stopping';
321
+ this.#state = 'stopped';
322
+ }
323
+
324
+ /**
325
+ * Transition to error state.
326
+ *
327
+ * @param {string} error - Error description
328
+ */
329
+ setError(error) {
330
+ this.#state = 'error';
331
+ this._lastError = error;
332
+ }
333
+
334
+ // -- Data management ------------------------------------------------------
335
+
336
+ /**
337
+ * Merge patch into app data.
338
+ *
339
+ * @param {object} patch
340
+ */
341
+ updateData(patch) {
342
+ Object.assign(this.#data, patch);
343
+ }
344
+
345
+ // -- Peer management ------------------------------------------------------
346
+
347
+ /**
348
+ * Add a participating peer. Idempotent.
349
+ *
350
+ * @param {string} podId
351
+ */
352
+ addPeer(podId) {
353
+ if (!this.#peers.includes(podId)) {
354
+ this.#peers.push(podId);
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Remove a participating peer. Safe for non-existent.
360
+ *
361
+ * @param {string} podId
362
+ */
363
+ removePeer(podId) {
364
+ this.#peers = this.#peers.filter((p) => p !== podId);
365
+ }
366
+
367
+ /**
368
+ * Check if a peer is participating.
369
+ *
370
+ * @param {string} podId
371
+ * @returns {boolean}
372
+ */
373
+ hasPeer(podId) {
374
+ return this.#peers.includes(podId);
375
+ }
376
+
377
+ // -- Serialization --------------------------------------------------------
378
+
379
+ /**
380
+ * Serialize to a plain JSON-safe object.
381
+ *
382
+ * @returns {object}
383
+ */
384
+ toJSON() {
385
+ return {
386
+ manifest: this.manifest.toJSON(),
387
+ installedBy: this.installedBy,
388
+ installedAt: this.installedAt,
389
+ state: this.#state,
390
+ data: { ...this.#data },
391
+ peers: [...this.#peers],
392
+ };
393
+ }
394
+
395
+ /**
396
+ * Deserialize from a plain object.
397
+ *
398
+ * @param {object} data
399
+ * @returns {AppInstance}
400
+ */
401
+ static fromJSON(data) {
402
+ return new AppInstance({
403
+ manifest: AppManifest.fromJSON(data.manifest),
404
+ installedBy: data.installedBy,
405
+ installedAt: data.installedAt,
406
+ state: data.state,
407
+ data: data.data,
408
+ peers: data.peers,
409
+ });
410
+ }
411
+ }
412
+
413
+ // ---------------------------------------------------------------------------
414
+ // AppPermissionChecker
415
+ // ---------------------------------------------------------------------------
416
+
417
+ /**
418
+ * Validates app permission requests against a granted set.
419
+ *
420
+ * @class
421
+ */
422
+ export class AppPermissionChecker {
423
+ /** @type {Set<string>} */
424
+ #granted;
425
+
426
+ /**
427
+ * @param {object} opts
428
+ * @param {string[]} [opts.grantedPermissions]
429
+ */
430
+ constructor({ grantedPermissions = [] } = {}) {
431
+ this.#granted = new Set(grantedPermissions);
432
+ }
433
+
434
+ /**
435
+ * Check if a permission is granted.
436
+ *
437
+ * @param {string} permission
438
+ * @returns {boolean}
439
+ */
440
+ check(permission) {
441
+ return this.#granted.has(permission);
442
+ }
443
+
444
+ /**
445
+ * Check multiple permissions at once.
446
+ *
447
+ * @param {string[]} permissions
448
+ * @returns {{ granted: string[], denied: string[] }}
449
+ */
450
+ checkAll(permissions) {
451
+ const granted = [];
452
+ const denied = [];
453
+ for (const p of permissions) {
454
+ if (this.#granted.has(p)) {
455
+ granted.push(p);
456
+ } else {
457
+ denied.push(p);
458
+ }
459
+ }
460
+ return { granted, denied };
461
+ }
462
+
463
+ /**
464
+ * Grant a permission. Idempotent.
465
+ *
466
+ * @param {string} permission
467
+ */
468
+ grant(permission) {
469
+ this.#granted.add(permission);
470
+ }
471
+
472
+ /**
473
+ * Revoke a permission. Safe for non-existent.
474
+ *
475
+ * @param {string} permission
476
+ */
477
+ revoke(permission) {
478
+ this.#granted.delete(permission);
479
+ }
480
+
481
+ /**
482
+ * List all granted permissions.
483
+ *
484
+ * @returns {string[]}
485
+ */
486
+ listGranted() {
487
+ return [...this.#granted];
488
+ }
489
+ }
490
+
491
+ // ---------------------------------------------------------------------------
492
+ // AppRegistry
493
+ // ---------------------------------------------------------------------------
494
+
495
+ /**
496
+ * Manages installed apps for a local pod.
497
+ *
498
+ * @class
499
+ */
500
+ export class AppRegistry {
501
+ /** @type {string} */
502
+ #localPodId;
503
+
504
+ /** @type {Map<string, AppInstance>} appId -> instance */
505
+ #apps = new Map();
506
+
507
+ /** @type {Map<string, AppPermissionChecker>} appId -> checker */
508
+ #permissions = new Map();
509
+
510
+ /** @type {Function[]} */
511
+ #installCallbacks = [];
512
+
513
+ /** @type {Function[]} */
514
+ #uninstallCallbacks = [];
515
+
516
+ /** @type {Function[]} */
517
+ #stateChangeCallbacks = [];
518
+
519
+ /**
520
+ * @param {object} opts
521
+ * @param {string} opts.localPodId
522
+ */
523
+ constructor({ localPodId } = {}) {
524
+ if (!localPodId) throw new Error('localPodId is required');
525
+ this.#localPodId = localPodId;
526
+ }
527
+
528
+ /**
529
+ * Install an app from a manifest.
530
+ *
531
+ * @param {AppManifest} manifest
532
+ * @param {string[]} [grantPermissions] - Permissions to grant (subset of manifest.permissions)
533
+ * @returns {AppInstance}
534
+ */
535
+ install(manifest, grantPermissions) {
536
+ if (!manifest.validate()) {
537
+ throw new Error('Invalid manifest: validation failed');
538
+ }
539
+ if (this.#apps.has(manifest.id)) {
540
+ throw new Error(`App '${manifest.id}' is already installed`);
541
+ }
542
+
543
+ const inst = new AppInstance({
544
+ manifest,
545
+ installedBy: this.#localPodId,
546
+ });
547
+
548
+ const checker = new AppPermissionChecker({
549
+ grantedPermissions: grantPermissions || manifest.permissions,
550
+ });
551
+
552
+ this.#apps.set(manifest.id, inst);
553
+ this.#permissions.set(manifest.id, checker);
554
+ this.#fire(this.#installCallbacks, inst);
555
+ return inst;
556
+ }
557
+
558
+ /**
559
+ * Uninstall an app by ID.
560
+ *
561
+ * @param {string} appId
562
+ */
563
+ uninstall(appId) {
564
+ const inst = this.#apps.get(appId);
565
+ if (!inst) throw new Error(`App '${appId}' not found`);
566
+
567
+ // Stop if active
568
+ if (inst.state !== 'stopped' && inst.state !== 'error') {
569
+ try { inst.stop(); } catch (e) { silentCatch('clawser-mesh-apps', 'inst.stop', e) }
570
+ }
571
+
572
+ this.#apps.delete(appId);
573
+ this.#permissions.delete(appId);
574
+ this.#fire(this.#uninstallCallbacks, appId);
575
+ }
576
+
577
+ /**
578
+ * Get an AppInstance by ID.
579
+ *
580
+ * @param {string} appId
581
+ * @returns {AppInstance|undefined}
582
+ */
583
+ get(appId) {
584
+ return this.#apps.get(appId);
585
+ }
586
+
587
+ /**
588
+ * List installed apps, optionally filtering.
589
+ *
590
+ * @param {object} [filter]
591
+ * @param {string} [filter.state] - Filter by state
592
+ * @param {string} [filter.author] - Filter by author
593
+ * @param {string} [filter.name] - Filter by name substring
594
+ * @returns {AppInstance[]}
595
+ */
596
+ list(filter) {
597
+ let results = [...this.#apps.values()];
598
+ if (filter) {
599
+ if (filter.state) {
600
+ results = results.filter((i) => i.state === filter.state);
601
+ }
602
+ if (filter.author) {
603
+ results = results.filter((i) => i.manifest.author === filter.author);
604
+ }
605
+ if (filter.name) {
606
+ const lower = filter.name.toLowerCase();
607
+ results = results.filter((i) => i.manifest.name.toLowerCase().includes(lower));
608
+ }
609
+ }
610
+ return results;
611
+ }
612
+
613
+ /**
614
+ * Start an app by ID.
615
+ *
616
+ * @param {string} appId
617
+ */
618
+ start(appId) {
619
+ const inst = this.#apps.get(appId);
620
+ if (!inst) throw new Error(`App '${appId}' not found`);
621
+ inst.start();
622
+ this.#fire(this.#stateChangeCallbacks, appId, inst.state);
623
+ }
624
+
625
+ /**
626
+ * Pause an app by ID.
627
+ *
628
+ * @param {string} appId
629
+ */
630
+ pause(appId) {
631
+ const inst = this.#apps.get(appId);
632
+ if (!inst) throw new Error(`App '${appId}' not found`);
633
+ inst.pause();
634
+ this.#fire(this.#stateChangeCallbacks, appId, inst.state);
635
+ }
636
+
637
+ /**
638
+ * Stop an app by ID.
639
+ *
640
+ * @param {string} appId
641
+ */
642
+ stop(appId) {
643
+ const inst = this.#apps.get(appId);
644
+ if (!inst) throw new Error(`App '${appId}' not found`);
645
+ inst.stop();
646
+ this.#fire(this.#stateChangeCallbacks, appId, inst.state);
647
+ }
648
+
649
+ /**
650
+ * Update an app to a new version. Stops the old version, replaces manifest,
651
+ * restarts if the old version was running.
652
+ *
653
+ * @param {string} appId
654
+ * @param {AppManifest} newManifest
655
+ */
656
+ update(appId, newManifest) {
657
+ const inst = this.#apps.get(appId);
658
+ if (!inst) throw new Error(`App '${appId}' not found`);
659
+ if (!newManifest.validate()) {
660
+ throw new Error('Invalid manifest: validation failed');
661
+ }
662
+
663
+ const wasRunning = inst.state === 'running';
664
+
665
+ // Stop if active
666
+ if (inst.state !== 'stopped' && inst.state !== 'installed' && inst.state !== 'error') {
667
+ try { inst.stop(); } catch (e) { silentCatch('clawser-mesh-apps', 'inst.stop', e) }
668
+ }
669
+
670
+ // Create new instance with new manifest, preserving data
671
+ const newInst = new AppInstance({
672
+ manifest: newManifest,
673
+ installedBy: inst.installedBy,
674
+ installedAt: inst.installedAt,
675
+ data: inst.data,
676
+ peers: inst.peers,
677
+ });
678
+
679
+ this.#apps.set(appId, newInst);
680
+
681
+ if (wasRunning) {
682
+ newInst.start();
683
+ this.#fire(this.#stateChangeCallbacks, appId, newInst.state);
684
+ }
685
+ }
686
+
687
+ /**
688
+ * Get apps using a specific permission.
689
+ *
690
+ * @param {string} permission
691
+ * @returns {AppInstance[]}
692
+ */
693
+ getByPermission(permission) {
694
+ const results = [];
695
+ for (const [appId, inst] of this.#apps) {
696
+ if (inst.manifest.permissions.includes(permission)) {
697
+ results.push(inst);
698
+ }
699
+ }
700
+ return results;
701
+ }
702
+
703
+ /**
704
+ * Register a callback for install events.
705
+ *
706
+ * @param {Function} cb - Receives (AppInstance)
707
+ */
708
+ onInstall(cb) {
709
+ this.#installCallbacks.push(cb);
710
+ }
711
+
712
+ /**
713
+ * Register a callback for uninstall events.
714
+ *
715
+ * @param {Function} cb - Receives (appId)
716
+ */
717
+ onUninstall(cb) {
718
+ this.#uninstallCallbacks.push(cb);
719
+ }
720
+
721
+ /**
722
+ * Register a callback for state change events.
723
+ *
724
+ * @param {Function} cb - Receives (appId, newState)
725
+ */
726
+ onStateChange(cb) {
727
+ this.#stateChangeCallbacks.push(cb);
728
+ }
729
+
730
+ /**
731
+ * Get aggregate stats about installed apps.
732
+ *
733
+ * @returns {{ totalInstalled: number, running: number, paused: number, stopped: number }}
734
+ */
735
+ getStats() {
736
+ let running = 0;
737
+ let paused = 0;
738
+ let stopped = 0;
739
+ for (const inst of this.#apps.values()) {
740
+ if (inst.state === 'running') running++;
741
+ else if (inst.state === 'paused') paused++;
742
+ else if (inst.state === 'stopped') stopped++;
743
+ }
744
+ return {
745
+ totalInstalled: this.#apps.size,
746
+ running,
747
+ paused,
748
+ stopped,
749
+ };
750
+ }
751
+
752
+ /**
753
+ * Serialize to a JSON-safe object.
754
+ *
755
+ * @returns {object}
756
+ */
757
+ toJSON() {
758
+ const apps = {};
759
+ for (const [id, inst] of this.#apps) {
760
+ apps[id] = inst.toJSON();
761
+ }
762
+ return {
763
+ localPodId: this.#localPodId,
764
+ apps,
765
+ };
766
+ }
767
+
768
+ /**
769
+ * Deserialize from a plain object.
770
+ *
771
+ * @param {object} data
772
+ * @returns {AppRegistry}
773
+ */
774
+ static fromJSON(data) {
775
+ const registry = new AppRegistry({ localPodId: data.localPodId });
776
+ for (const [id, instData] of Object.entries(data.apps)) {
777
+ const inst = AppInstance.fromJSON(instData);
778
+ registry.#apps.set(id, inst);
779
+ registry.#permissions.set(id, new AppPermissionChecker({
780
+ grantedPermissions: inst.manifest.permissions,
781
+ }));
782
+ }
783
+ return registry;
784
+ }
785
+
786
+ // -- Private Helpers ------------------------------------------------------
787
+
788
+ /**
789
+ * Fire all callbacks in a list, swallowing listener errors.
790
+ *
791
+ * @param {Function[]} callbacks
792
+ * @param {...*} args
793
+ */
794
+ #fire(callbacks, ...args) {
795
+ for (const cb of callbacks) {
796
+ try {
797
+ cb(...args);
798
+ } catch {
799
+ /* listener errors do not propagate */
800
+ }
801
+ }
802
+ }
803
+ }
804
+
805
+ // ---------------------------------------------------------------------------
806
+ // AppStore
807
+ // ---------------------------------------------------------------------------
808
+
809
+ /**
810
+ * Distributed app store across the mesh.
811
+ *
812
+ * @class
813
+ */
814
+ export class AppStore {
815
+ /** @type {string} */
816
+ #localPodId;
817
+
818
+ /** @type {Map<string, AppManifest>} appId -> manifest */
819
+ #manifests = new Map();
820
+
821
+ /** @type {Map<string, number>} appId -> install count */
822
+ #installCounts = new Map();
823
+
824
+ /** @type {Function[]} */
825
+ #publishCallbacks = [];
826
+
827
+ /** @type {Function[]} */
828
+ #updateCallbacks = [];
829
+
830
+ /**
831
+ * @param {object} opts
832
+ * @param {string} opts.localPodId
833
+ */
834
+ constructor({ localPodId } = {}) {
835
+ if (!localPodId) throw new Error('localPodId is required');
836
+ this.#localPodId = localPodId;
837
+ }
838
+
839
+ /**
840
+ * Publish an app manifest to the store.
841
+ * If the app already exists, this is treated as an update.
842
+ *
843
+ * @param {AppManifest} manifest
844
+ */
845
+ publish(manifest) {
846
+ const existing = this.#manifests.has(manifest.id);
847
+ this.#manifests.set(manifest.id, manifest);
848
+ if (!this.#installCounts.has(manifest.id)) {
849
+ this.#installCounts.set(manifest.id, 0);
850
+ }
851
+ if (existing) {
852
+ this.#fire(this.#updateCallbacks, manifest);
853
+ } else {
854
+ this.#fire(this.#publishCallbacks, manifest);
855
+ }
856
+ }
857
+
858
+ /**
859
+ * Unpublish an app from the store. Only the author may unpublish.
860
+ *
861
+ * @param {string} appId
862
+ * @param {string} requesterPodId - Must match the manifest author
863
+ */
864
+ unpublish(appId, requesterPodId) {
865
+ const manifest = this.#manifests.get(appId);
866
+ if (!manifest) throw new Error(`App '${appId}' not found in store`);
867
+ if (manifest.author !== requesterPodId) {
868
+ throw new Error('Only the author can unpublish an app');
869
+ }
870
+ this.#manifests.delete(appId);
871
+ this.#installCounts.delete(appId);
872
+ }
873
+
874
+ /**
875
+ * Text search across app name and description.
876
+ *
877
+ * @param {string} query
878
+ * @returns {AppManifest[]}
879
+ */
880
+ search(query) {
881
+ const lower = query.toLowerCase();
882
+ const results = [];
883
+ for (const m of this.#manifests.values()) {
884
+ const nameMatch = m.name.toLowerCase().includes(lower);
885
+ const descMatch = m.description && m.description.toLowerCase().includes(lower);
886
+ if (nameMatch || descMatch) {
887
+ results.push(m);
888
+ }
889
+ }
890
+ return results;
891
+ }
892
+
893
+ /**
894
+ * Find a manifest by ID.
895
+ *
896
+ * @param {string} appId
897
+ * @returns {AppManifest|undefined}
898
+ */
899
+ getById(appId) {
900
+ return this.#manifests.get(appId);
901
+ }
902
+
903
+ /**
904
+ * Get all apps by an author.
905
+ *
906
+ * @param {string} authorPodId
907
+ * @returns {AppManifest[]}
908
+ */
909
+ getByAuthor(authorPodId) {
910
+ const results = [];
911
+ for (const m of this.#manifests.values()) {
912
+ if (m.author === authorPodId) {
913
+ results.push(m);
914
+ }
915
+ }
916
+ return results;
917
+ }
918
+
919
+ /**
920
+ * Get most installed apps, sorted by install count descending.
921
+ *
922
+ * @param {number} [limit=10]
923
+ * @returns {AppManifest[]}
924
+ */
925
+ getPopular(limit = 10) {
926
+ const sorted = [...this.#manifests.keys()]
927
+ .sort((a, b) => (this.#installCounts.get(b) || 0) - (this.#installCounts.get(a) || 0))
928
+ .slice(0, limit);
929
+ return sorted.map((id) => this.#manifests.get(id));
930
+ }
931
+
932
+ /**
933
+ * Increment the install counter for an app.
934
+ *
935
+ * @param {string} appId
936
+ */
937
+ addInstallCount(appId) {
938
+ if (!this.#manifests.has(appId)) {
939
+ throw new Error(`App '${appId}' not found in store`);
940
+ }
941
+ this.#installCounts.set(appId, (this.#installCounts.get(appId) || 0) + 1);
942
+ }
943
+
944
+ /**
945
+ * Get distinct categories from all manifests' metadata.
946
+ *
947
+ * @returns {string[]}
948
+ */
949
+ getCategories() {
950
+ const cats = new Set();
951
+ for (const m of this.#manifests.values()) {
952
+ if (m.metadata && m.metadata.category) {
953
+ cats.add(m.metadata.category);
954
+ }
955
+ }
956
+ return [...cats];
957
+ }
958
+
959
+ /**
960
+ * Register a callback for publish events (new apps).
961
+ *
962
+ * @param {Function} cb - Receives (AppManifest)
963
+ */
964
+ onPublish(cb) {
965
+ this.#publishCallbacks.push(cb);
966
+ }
967
+
968
+ /**
969
+ * Register a callback for update events (re-published apps).
970
+ *
971
+ * @param {Function} cb - Receives (AppManifest)
972
+ */
973
+ onUpdate(cb) {
974
+ this.#updateCallbacks.push(cb);
975
+ }
976
+
977
+ /**
978
+ * Serialize to a JSON-safe object.
979
+ *
980
+ * @returns {object}
981
+ */
982
+ toJSON() {
983
+ const manifests = {};
984
+ for (const [id, m] of this.#manifests) {
985
+ manifests[id] = m.toJSON();
986
+ }
987
+ const installCounts = {};
988
+ for (const [id, count] of this.#installCounts) {
989
+ installCounts[id] = count;
990
+ }
991
+ return {
992
+ localPodId: this.#localPodId,
993
+ manifests,
994
+ installCounts,
995
+ };
996
+ }
997
+
998
+ /**
999
+ * Deserialize from a plain object.
1000
+ *
1001
+ * @param {object} data
1002
+ * @returns {AppStore}
1003
+ */
1004
+ static fromJSON(data) {
1005
+ const store = new AppStore({ localPodId: data.localPodId });
1006
+ for (const [id, mData] of Object.entries(data.manifests)) {
1007
+ store.#manifests.set(id, AppManifest.fromJSON(mData));
1008
+ }
1009
+ for (const [id, count] of Object.entries(data.installCounts)) {
1010
+ store.#installCounts.set(id, count);
1011
+ }
1012
+ return store;
1013
+ }
1014
+
1015
+ // -- Private Helpers ------------------------------------------------------
1016
+
1017
+ /**
1018
+ * Fire all callbacks in a list, swallowing listener errors.
1019
+ *
1020
+ * @param {Function[]} callbacks
1021
+ * @param {...*} args
1022
+ */
1023
+ #fire(callbacks, ...args) {
1024
+ for (const cb of callbacks) {
1025
+ try {
1026
+ cb(...args);
1027
+ } catch {
1028
+ /* listener errors do not propagate */
1029
+ }
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ // ---------------------------------------------------------------------------
1035
+ // AppRPC
1036
+ // ---------------------------------------------------------------------------
1037
+
1038
+ /**
1039
+ * Inter-app and cross-pod RPC for apps.
1040
+ *
1041
+ * @class
1042
+ */
1043
+ export class AppRPC {
1044
+ /** @type {string} */
1045
+ #appId;
1046
+
1047
+ /** @type {string} */
1048
+ #localPodId;
1049
+
1050
+ /** @type {Map<string, Function>} method -> handler */
1051
+ #methods = new Map();
1052
+
1053
+ /** @type {Map<string, { resolve: Function, reject: Function }>} requestId -> pending */
1054
+ #pending = new Map();
1055
+
1056
+ /** @type {Function[]} */
1057
+ #callCallbacks = [];
1058
+
1059
+ /** @type {number} */
1060
+ #nextId = 1;
1061
+
1062
+ /** @type {object|null} */
1063
+ #lastOutgoing = null;
1064
+
1065
+ /**
1066
+ * @param {object} opts
1067
+ * @param {string} opts.appId
1068
+ * @param {string} opts.localPodId
1069
+ */
1070
+ constructor({ appId, localPodId } = {}) {
1071
+ if (!appId) throw new Error('appId is required');
1072
+ if (!localPodId) throw new Error('localPodId is required');
1073
+ this.#appId = appId;
1074
+ this.#localPodId = localPodId;
1075
+ }
1076
+
1077
+ /**
1078
+ * Register an RPC method.
1079
+ *
1080
+ * @param {string} method
1081
+ * @param {Function} handler - Receives (params) and returns result or throws
1082
+ */
1083
+ register(method, handler) {
1084
+ this.#methods.set(method, handler);
1085
+ }
1086
+
1087
+ /**
1088
+ * Remove an RPC method.
1089
+ *
1090
+ * @param {string} method
1091
+ */
1092
+ unregister(method) {
1093
+ this.#methods.delete(method);
1094
+ }
1095
+
1096
+ /**
1097
+ * Call a remote method on another pod.
1098
+ * Returns a promise that resolves when the response arrives.
1099
+ *
1100
+ * @param {string} targetPodId
1101
+ * @param {string} method
1102
+ * @param {*} [params]
1103
+ * @returns {Promise<*>}
1104
+ */
1105
+ async call(targetPodId, method, params) {
1106
+ const id = `rpc-${this.#nextId++}`;
1107
+ const message = {
1108
+ type: 'request',
1109
+ id,
1110
+ fromPodId: this.#localPodId,
1111
+ targetPodId,
1112
+ appId: this.#appId,
1113
+ method,
1114
+ params: params || {},
1115
+ };
1116
+
1117
+ this.#lastOutgoing = message;
1118
+
1119
+ const promise = new Promise((resolve, reject) => {
1120
+ this.#pending.set(id, { resolve, reject });
1121
+ });
1122
+
1123
+ this.#fire(this.#callCallbacks, message);
1124
+
1125
+ return promise;
1126
+ }
1127
+
1128
+ /**
1129
+ * List registered method names.
1130
+ *
1131
+ * @returns {string[]}
1132
+ */
1133
+ listMethods() {
1134
+ return [...this.#methods.keys()];
1135
+ }
1136
+
1137
+ /**
1138
+ * Process an incoming RPC message.
1139
+ * If it is a request, dispatch to the registered handler and return a response.
1140
+ * If it is a response, resolve the pending promise.
1141
+ *
1142
+ * @param {object} message
1143
+ * @returns {object|undefined} Response message for requests, undefined for responses
1144
+ */
1145
+ handleIncoming(message) {
1146
+ if (message.type === 'request') {
1147
+ const handler = this.#methods.get(message.method);
1148
+ if (!handler) {
1149
+ return {
1150
+ type: 'response',
1151
+ id: message.id,
1152
+ fromPodId: this.#localPodId,
1153
+ targetPodId: message.fromPodId,
1154
+ appId: this.#appId,
1155
+ result: null,
1156
+ error: `Method '${message.method}' not found`,
1157
+ };
1158
+ }
1159
+
1160
+ try {
1161
+ const result = handler(message.params);
1162
+ return {
1163
+ type: 'response',
1164
+ id: message.id,
1165
+ fromPodId: this.#localPodId,
1166
+ targetPodId: message.fromPodId,
1167
+ appId: this.#appId,
1168
+ result,
1169
+ error: null,
1170
+ };
1171
+ } catch (err) {
1172
+ return {
1173
+ type: 'response',
1174
+ id: message.id,
1175
+ fromPodId: this.#localPodId,
1176
+ targetPodId: message.fromPodId,
1177
+ appId: this.#appId,
1178
+ result: null,
1179
+ error: err.message,
1180
+ };
1181
+ }
1182
+ }
1183
+
1184
+ if (message.type === 'response') {
1185
+ const pending = this.#pending.get(message.id);
1186
+ if (pending) {
1187
+ this.#pending.delete(message.id);
1188
+ if (message.error) {
1189
+ pending.reject(new Error(message.error));
1190
+ } else {
1191
+ pending.resolve(message.result);
1192
+ }
1193
+ }
1194
+ }
1195
+
1196
+ return undefined;
1197
+ }
1198
+
1199
+ /**
1200
+ * Register a callback for outgoing calls (for transport layer).
1201
+ *
1202
+ * @param {Function} cb - Receives (message)
1203
+ */
1204
+ onCall(cb) {
1205
+ this.#callCallbacks.push(cb);
1206
+ }
1207
+
1208
+ /**
1209
+ * Get the last outgoing message (for testing transport simulation).
1210
+ *
1211
+ * @returns {object|null}
1212
+ */
1213
+ _getLastOutgoing() {
1214
+ return this.#lastOutgoing;
1215
+ }
1216
+
1217
+ // -- Private Helpers ------------------------------------------------------
1218
+
1219
+ /**
1220
+ * Fire all callbacks in a list, swallowing listener errors.
1221
+ *
1222
+ * @param {Function[]} callbacks
1223
+ * @param {...*} args
1224
+ */
1225
+ #fire(callbacks, ...args) {
1226
+ for (const cb of callbacks) {
1227
+ try {
1228
+ cb(...args);
1229
+ } catch {
1230
+ /* listener errors do not propagate */
1231
+ }
1232
+ }
1233
+ }
1234
+ }
1235
+
1236
+ // ---------------------------------------------------------------------------
1237
+ // AppEventBus
1238
+ // ---------------------------------------------------------------------------
1239
+
1240
+ /**
1241
+ * Pub/sub event system for apps.
1242
+ *
1243
+ * @class
1244
+ */
1245
+ export class AppEventBus {
1246
+ /** @type {string} */
1247
+ #appId;
1248
+
1249
+ /** @type {Map<string, Function[]>} eventType -> listeners */
1250
+ #listeners = new Map();
1251
+
1252
+ /**
1253
+ * @param {object} opts
1254
+ * @param {string} opts.appId
1255
+ */
1256
+ constructor({ appId } = {}) {
1257
+ if (!appId) throw new Error('appId is required');
1258
+ this.#appId = appId;
1259
+ }
1260
+
1261
+ /**
1262
+ * Publish an event to all subscribers.
1263
+ *
1264
+ * @param {string} eventType
1265
+ * @param {*} data
1266
+ */
1267
+ emit(eventType, data) {
1268
+ const listeners = this.#listeners.get(eventType);
1269
+ if (!listeners) return;
1270
+ for (const cb of [...listeners]) {
1271
+ try {
1272
+ cb(data);
1273
+ } catch {
1274
+ /* listener errors do not propagate */
1275
+ }
1276
+ }
1277
+ }
1278
+
1279
+ /**
1280
+ * Subscribe to an event type.
1281
+ *
1282
+ * @param {string} eventType
1283
+ * @param {Function} cb
1284
+ */
1285
+ on(eventType, cb) {
1286
+ if (!this.#listeners.has(eventType)) {
1287
+ this.#listeners.set(eventType, []);
1288
+ }
1289
+ this.#listeners.get(eventType).push(cb);
1290
+ }
1291
+
1292
+ /**
1293
+ * Unsubscribe from an event type.
1294
+ *
1295
+ * @param {string} eventType
1296
+ * @param {Function} cb
1297
+ */
1298
+ off(eventType, cb) {
1299
+ const listeners = this.#listeners.get(eventType);
1300
+ if (!listeners) return;
1301
+ const idx = listeners.indexOf(cb);
1302
+ if (idx >= 0) {
1303
+ listeners.splice(idx, 1);
1304
+ }
1305
+ if (listeners.length === 0) {
1306
+ this.#listeners.delete(eventType);
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * Subscribe to an event type for one event only.
1312
+ *
1313
+ * @param {string} eventType
1314
+ * @param {Function} cb
1315
+ */
1316
+ once(eventType, cb) {
1317
+ const wrapper = (data) => {
1318
+ this.off(eventType, wrapper);
1319
+ cb(data);
1320
+ };
1321
+ this.on(eventType, wrapper);
1322
+ }
1323
+
1324
+ /**
1325
+ * List active event types with subscriber counts.
1326
+ *
1327
+ * @returns {Array<{ eventType: string, count: number }>}
1328
+ */
1329
+ listEventTypes() {
1330
+ const types = [];
1331
+ for (const [eventType, listeners] of this.#listeners) {
1332
+ if (listeners.length > 0) {
1333
+ types.push({ eventType, count: listeners.length });
1334
+ }
1335
+ }
1336
+ return types;
1337
+ }
1338
+
1339
+ /**
1340
+ * Remove all listeners, optionally for a specific event type.
1341
+ *
1342
+ * @param {string} [eventType] - If omitted, clears all event types
1343
+ */
1344
+ removeAllListeners(eventType) {
1345
+ if (eventType !== undefined) {
1346
+ this.#listeners.delete(eventType);
1347
+ } else {
1348
+ this.#listeners.clear();
1349
+ }
1350
+ }
1351
+ }