@dxos/client-services 0.1.49 → 0.1.50-next.1bfebf8

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.
Files changed (35) hide show
  1. package/dist/lib/browser/{chunk-YLH4UYUT.mjs → chunk-UL74TKNZ.mjs} +497 -1095
  2. package/dist/lib/browser/chunk-UL74TKNZ.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +601 -9
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/packlets/testing/index.mjs +1 -1
  7. package/dist/lib/node/index.cjs +1098 -1158
  8. package/dist/lib/node/index.cjs.map +4 -4
  9. package/dist/lib/node/meta.json +1 -1
  10. package/dist/lib/node/packlets/testing/index.cjs +238 -726
  11. package/dist/lib/node/packlets/testing/index.cjs.map +4 -4
  12. package/dist/types/src/index.d.ts +1 -0
  13. package/dist/types/src/index.d.ts.map +1 -1
  14. package/dist/types/src/packlets/locks/browser.d.ts +16 -0
  15. package/dist/types/src/packlets/locks/browser.d.ts.map +1 -0
  16. package/dist/types/src/packlets/locks/index.d.ts +3 -0
  17. package/dist/types/src/packlets/locks/index.d.ts.map +1 -0
  18. package/dist/types/src/packlets/locks/node.d.ts +13 -0
  19. package/dist/types/src/packlets/locks/node.d.ts.map +1 -0
  20. package/dist/types/src/packlets/locks/resource-lock.d.ts +16 -0
  21. package/dist/types/src/packlets/locks/resource-lock.d.ts.map +1 -0
  22. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  23. package/dist/types/src/packlets/vault/index.d.ts +0 -1
  24. package/dist/types/src/packlets/vault/index.d.ts.map +1 -1
  25. package/package.json +33 -30
  26. package/src/index.ts +1 -0
  27. package/src/packlets/{vault/vault-resource-lock.ts → locks/browser.ts} +12 -11
  28. package/src/packlets/locks/index.ts +6 -0
  29. package/src/packlets/locks/node.ts +52 -0
  30. package/src/packlets/locks/resource-lock.ts +24 -0
  31. package/src/packlets/services/service-host.ts +13 -13
  32. package/src/packlets/vault/index.ts +0 -1
  33. package/dist/lib/browser/chunk-YLH4UYUT.mjs.map +0 -7
  34. package/dist/types/src/packlets/vault/vault-resource-lock.d.ts +0 -20
  35. package/dist/types/src/packlets/vault/vault-resource-lock.d.ts.map +0 -1
@@ -44,6 +44,7 @@ __export(src_exports, {
44
44
  InvitationsHandler: () => InvitationsHandler,
45
45
  InvitationsServiceImpl: () => InvitationsServiceImpl,
46
46
  LocalClientServices: () => LocalClientServices,
47
+ Lock: () => Lock,
47
48
  MemoryShellRuntime: () => MemoryShellRuntime,
48
49
  ServiceContext: () => ServiceContext,
49
50
  ServiceRegistry: () => ServiceRegistry,
@@ -51,12 +52,12 @@ __export(src_exports, {
51
52
  SpaceInvitationProtocol: () => SpaceInvitationProtocol,
52
53
  SpacesServiceImpl: () => SpacesServiceImpl,
53
54
  TrustedKeySetAuthVerifier: () => TrustedKeySetAuthVerifier,
54
- VaultResourceLock: () => VaultResourceLock,
55
55
  WorkerRuntime: () => WorkerRuntime,
56
56
  WorkerSession: () => WorkerSession,
57
57
  createAuthProvider: () => createAuthProvider,
58
58
  createStorageObjects: () => createStorageObjects,
59
59
  getNetworkPeers: () => getNetworkPeers,
60
+ isLocked: () => isLocked,
60
61
  subscribeToFeedBlocks: () => subscribeToFeedBlocks,
61
62
  subscribeToFeeds: () => subscribeToFeeds,
62
63
  subscribeToNetworkStatus: () => subscribeToNetworkStatus,
@@ -2127,16 +2128,16 @@ var SpaceInvitationProtocol = class {
2127
2128
  };
2128
2129
 
2129
2130
  // packages/sdk/client-services/src/packlets/services/service-host.ts
2130
- var import_node_assert14 = __toESM(require("node:assert"));
2131
- var import_async23 = require("@dxos/async");
2132
- var import_client_protocol9 = require("@dxos/client-protocol");
2131
+ var import_node_assert12 = __toESM(require("node:assert"));
2132
+ var import_async18 = require("@dxos/async");
2133
+ var import_client_protocol4 = require("@dxos/client-protocol");
2133
2134
  var import_echo_pipeline4 = require("@dxos/echo-pipeline");
2134
2135
  var import_keys11 = require("@dxos/keys");
2135
- var import_log19 = require("@dxos/log");
2136
- var import_messaging3 = require("@dxos/messaging");
2137
- var import_network_manager5 = require("@dxos/network-manager");
2136
+ var import_log15 = require("@dxos/log");
2137
+ var import_messaging = require("@dxos/messaging");
2138
+ var import_network_manager2 = require("@dxos/network-manager");
2138
2139
  var import_protocols9 = require("@dxos/protocols");
2139
- var import_services13 = require("@dxos/protocols/proto/dxos/client/services");
2140
+ var import_services11 = require("@dxos/protocols/proto/dxos/client/services");
2140
2141
 
2141
2142
  // packages/sdk/client-services/src/packlets/devices/devices-service.ts
2142
2143
  var import_async10 = require("@dxos/async");
@@ -2185,24 +2186,82 @@ var DevicesServiceImpl = class {
2185
2186
  }
2186
2187
  };
2187
2188
 
2188
- // packages/sdk/client-services/src/packlets/logging/logging-service.ts
2189
+ // packages/sdk/client-services/src/packlets/locks/node.ts
2190
+ var import_lockfile = __toESM(require("lockfile"));
2189
2191
  var import_async11 = require("@dxos/async");
2190
- var import_codec_protobuf10 = require("@dxos/codec-protobuf");
2191
2192
  var import_log8 = require("@dxos/log");
2193
+ var __decorate = function(decorators, target, key, desc) {
2194
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2195
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2196
+ r = Reflect.decorate(decorators, target, key, desc);
2197
+ else
2198
+ for (var i = decorators.length - 1; i >= 0; i--)
2199
+ if (d = decorators[i])
2200
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2201
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2202
+ };
2203
+ var Lock = class {
2204
+ constructor({ lockKey: lockPath, onAcquire, onRelease }) {
2205
+ this._releaseTrigger = new import_async11.Trigger();
2206
+ this._lockPath = lockPath;
2207
+ this._onAcquire = onAcquire;
2208
+ this._onRelease = onRelease;
2209
+ }
2210
+ get lockKey() {
2211
+ return this._lockPath;
2212
+ }
2213
+ async acquire() {
2214
+ var _a;
2215
+ (0, import_log8.log)("acquiring lock...", {}, {
2216
+ file: "node.ts",
2217
+ line: 31,
2218
+ scope: this,
2219
+ callSite: (f, a) => f(...a)
2220
+ });
2221
+ if (import_lockfile.default.checkSync(this.lockKey)) {
2222
+ throw new Error(`Lock already acquired: ${this._lockPath}`);
2223
+ }
2224
+ import_lockfile.default.lockSync(this._lockPath);
2225
+ await ((_a = this._onAcquire) == null ? void 0 : _a.call(this));
2226
+ (0, import_log8.log)("acquired lock", {}, {
2227
+ file: "node.ts",
2228
+ line: 39,
2229
+ scope: this,
2230
+ callSite: (f, a) => f(...a)
2231
+ });
2232
+ }
2233
+ async release() {
2234
+ var _a;
2235
+ if (!import_lockfile.default.checkSync(this._lockPath)) {
2236
+ throw new Error(`Lock already acquired: ${this._lockPath}`);
2237
+ }
2238
+ await ((_a = this._onRelease) == null ? void 0 : _a.call(this));
2239
+ import_lockfile.default.unlockSync(this._lockPath);
2240
+ }
2241
+ };
2242
+ __decorate([
2243
+ import_log8.logInfo
2244
+ ], Lock.prototype, "lockKey", null);
2245
+ var isLocked = (lockPath) => import_lockfile.default.checkSync(lockPath);
2246
+
2247
+ // packages/sdk/client-services/src/packlets/logging/logging-service.ts
2248
+ var import_async12 = require("@dxos/async");
2249
+ var import_codec_protobuf10 = require("@dxos/codec-protobuf");
2250
+ var import_log9 = require("@dxos/log");
2192
2251
  var import_util3 = require("@dxos/util");
2193
2252
  var LoggingServiceImpl = class {
2194
2253
  constructor() {
2195
- this._logs = new import_async11.Event();
2254
+ this._logs = new import_async12.Event();
2196
2255
  this._logProcessor = (_config, entry2) => {
2197
2256
  this._logs.emit(entry2);
2198
2257
  };
2199
2258
  }
2200
2259
  async open() {
2201
- import_log8.log.runtimeConfig.processors.push(this._logProcessor);
2260
+ import_log9.log.runtimeConfig.processors.push(this._logProcessor);
2202
2261
  }
2203
2262
  async close() {
2204
- const index = import_log8.log.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
2205
- import_log8.log.runtimeConfig.processors.splice(index, 1);
2263
+ const index = import_log9.log.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
2264
+ import_log9.log.runtimeConfig.processors.splice(index, 1);
2206
2265
  }
2207
2266
  queryLogs(request) {
2208
2267
  var _a;
@@ -2213,10 +2272,10 @@ var LoggingServiceImpl = class {
2213
2272
  if (((_a2 = entry2.meta) == null ? void 0 : _a2.file.includes("logging-service")) || entry2.context && Object.values(entry2.context).some((value) => typeof value === "string" && value.includes("LoggingService"))) {
2214
2273
  return;
2215
2274
  }
2216
- if ((0, import_log8.shouldLog)(entry2, filters)) {
2275
+ if ((0, import_log9.shouldLog)(entry2, filters)) {
2217
2276
  const record = {
2218
2277
  ...entry2,
2219
- context: (0, import_util3.jsonify)((0, import_log8.getContextFromEntry)(entry2))
2278
+ context: (0, import_util3.jsonify)((0, import_log9.getContextFromEntry)(entry2))
2220
2279
  };
2221
2280
  (_b = record.meta) == null ? true : delete _b.bugcheck;
2222
2281
  (_c = record.meta) == null ? true : delete _c.scope;
@@ -2265,35 +2324,35 @@ var NetworkServiceImpl = class {
2265
2324
 
2266
2325
  // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
2267
2326
  var import_node_assert10 = __toESM(require("node:assert"));
2268
- var import_async14 = require("@dxos/async");
2327
+ var import_async15 = require("@dxos/async");
2269
2328
  var import_context7 = require("@dxos/context");
2270
2329
  var import_credentials12 = require("@dxos/credentials");
2271
2330
  var import_keys9 = require("@dxos/keys");
2272
- var import_log11 = require("@dxos/log");
2331
+ var import_log12 = require("@dxos/log");
2273
2332
  var import_protocols6 = require("@dxos/protocols");
2274
2333
  var import_services8 = require("@dxos/protocols/proto/dxos/client/services");
2275
2334
  var import_teleport_extension_gossip = require("@dxos/teleport-extension-gossip");
2276
2335
  var import_util6 = require("@dxos/util");
2277
2336
 
2278
2337
  // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2279
- var import_async13 = require("@dxos/async");
2338
+ var import_async14 = require("@dxos/async");
2280
2339
  var import_client_protocol3 = require("@dxos/client-protocol");
2281
2340
  var import_context6 = require("@dxos/context");
2282
2341
  var import_debug3 = require("@dxos/debug");
2283
2342
  var import_echo_pipeline = require("@dxos/echo-pipeline");
2284
2343
  var import_errors3 = require("@dxos/errors");
2285
2344
  var import_keys8 = require("@dxos/keys");
2286
- var import_log10 = require("@dxos/log");
2345
+ var import_log11 = require("@dxos/log");
2287
2346
  var import_services7 = require("@dxos/protocols/proto/dxos/client/services");
2288
2347
  var import_credentials9 = require("@dxos/protocols/proto/dxos/halo/credentials");
2289
2348
  var import_util5 = require("@dxos/util");
2290
2349
 
2291
2350
  // packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts
2292
2351
  var import_node_assert9 = __toESM(require("node:assert"));
2293
- var import_async12 = require("@dxos/async");
2352
+ var import_async13 = require("@dxos/async");
2294
2353
  var import_context5 = require("@dxos/context");
2295
2354
  var import_keys7 = require("@dxos/keys");
2296
- var import_log9 = require("@dxos/log");
2355
+ var import_log10 = require("@dxos/log");
2297
2356
  var import_protocols5 = require("@dxos/protocols");
2298
2357
  var import_teleport2 = require("@dxos/teleport");
2299
2358
  var import_util4 = require("@dxos/util");
@@ -2304,7 +2363,7 @@ var WRITER_NOT_SET_ERROR_CODE = "WRITER_NOT_SET";
2304
2363
  var NotarizationPlugin = class {
2305
2364
  constructor() {
2306
2365
  this._ctx = new import_context5.Context();
2307
- this._extensionOpened = new import_async12.Event();
2366
+ this._extensionOpened = new import_async13.Event();
2308
2367
  this._extensions = /* @__PURE__ */ new Set();
2309
2368
  this._processedCredentials = new import_util4.ComplexSet(import_keys7.PublicKey.hash);
2310
2369
  this._processCredentialsTriggers = new import_util4.ComplexMap(import_keys7.PublicKey.hash);
@@ -2318,7 +2377,7 @@ var NotarizationPlugin = class {
2318
2377
  * Request credentials to be notarized.
2319
2378
  */
2320
2379
  async notarize({ ctx: opCtx, credentials, timeout = DEFAULT_NOTARIZE_TIMEOUT, retryTimeout = DEFAULT_RETRY_TIMEOUT, successDelay = DEFAULT_SUCCESS_DELAY }) {
2321
- (0, import_log9.log)("notarize", {
2380
+ (0, import_log10.log)("notarize", {
2322
2381
  credentials
2323
2382
  }, {
2324
2383
  file: "notarization-plugin.ts",
@@ -2327,10 +2386,10 @@ var NotarizationPlugin = class {
2327
2386
  callSite: (f, a) => f(...a)
2328
2387
  });
2329
2388
  (0, import_node_assert9.default)(credentials.every((credential) => credential.id), "Credentials must have an id");
2330
- const errors = new import_async12.Trigger();
2389
+ const errors = new import_async13.Trigger();
2331
2390
  const ctx = this._ctx.derive({
2332
2391
  onError: (err) => {
2333
- import_log9.log.warn("Notarization error", {
2392
+ import_log10.log.warn("Notarization error", {
2334
2393
  err
2335
2394
  }, {
2336
2395
  file: "notarization-plugin.ts",
@@ -2344,8 +2403,8 @@ var NotarizationPlugin = class {
2344
2403
  });
2345
2404
  opCtx == null ? void 0 : opCtx.onDispose(() => ctx.dispose());
2346
2405
  if (timeout !== 0) {
2347
- (0, import_async12.scheduleTask)(ctx, () => {
2348
- import_log9.log.warn("Notarization timeout", {
2406
+ (0, import_async13.scheduleTask)(ctx, () => {
2407
+ import_log10.log.warn("Notarization timeout", {
2349
2408
  timeout,
2350
2409
  peers: Array.from(this._extensions).map((extension) => extension.remotePeerId)
2351
2410
  }, {
@@ -2355,12 +2414,12 @@ var NotarizationPlugin = class {
2355
2414
  callSite: (f, a) => f(...a)
2356
2415
  });
2357
2416
  void ctx.dispose();
2358
- errors.throw(new import_async12.TimeoutError(timeout, "Notarization timed out"));
2417
+ errors.throw(new import_async13.TimeoutError(timeout, "Notarization timed out"));
2359
2418
  }, timeout);
2360
2419
  }
2361
2420
  const allNotarized = Promise.all(credentials.map((credential) => this._waitUntilProcessed(credential.id)));
2362
2421
  const peersTried = /* @__PURE__ */ new Set();
2363
- const notarizeTask = new import_async12.DeferredTask(ctx, async () => {
2422
+ const notarizeTask = new import_async13.DeferredTask(ctx, async () => {
2364
2423
  try {
2365
2424
  if (this._extensions.size === 0) {
2366
2425
  return;
@@ -2369,7 +2428,7 @@ var NotarizationPlugin = class {
2369
2428
  ...this._extensions
2370
2429
  ].find((peer2) => !peersTried.has(peer2));
2371
2430
  if (!peer) {
2372
- import_log9.log.warn("Exhausted all peers to notarize with", {
2431
+ import_log10.log.warn("Exhausted all peers to notarize with", {
2373
2432
  retryIn: retryTimeout
2374
2433
  }, {
2375
2434
  file: "notarization-plugin.ts",
@@ -2378,11 +2437,11 @@ var NotarizationPlugin = class {
2378
2437
  callSite: (f, a) => f(...a)
2379
2438
  });
2380
2439
  peersTried.clear();
2381
- (0, import_async12.scheduleTask)(ctx, () => notarizeTask.schedule(), retryTimeout);
2440
+ (0, import_async13.scheduleTask)(ctx, () => notarizeTask.schedule(), retryTimeout);
2382
2441
  return;
2383
2442
  }
2384
2443
  peersTried.add(peer);
2385
- (0, import_log9.log)("try notarizing", {
2444
+ (0, import_log10.log)("try notarizing", {
2386
2445
  peer: peer.localPeerId,
2387
2446
  credentialId: credentials.map((credential) => credential.id)
2388
2447
  }, {
@@ -2394,16 +2453,16 @@ var NotarizationPlugin = class {
2394
2453
  await peer.rpc.NotarizationService.notarize({
2395
2454
  credentials: credentials.filter((credential) => !this._processedCredentials.has(credential.id))
2396
2455
  });
2397
- (0, import_log9.log)("success", {}, {
2456
+ (0, import_log10.log)("success", {}, {
2398
2457
  file: "notarization-plugin.ts",
2399
2458
  line: 144,
2400
2459
  scope: this,
2401
2460
  callSite: (f, a) => f(...a)
2402
2461
  });
2403
- await (0, import_async12.sleep)(successDelay);
2462
+ await (0, import_async13.sleep)(successDelay);
2404
2463
  } catch (err) {
2405
2464
  if (!ctx.disposed && !err.message.includes(WRITER_NOT_SET_ERROR_CODE)) {
2406
- import_log9.log.warn("error notarizing (recoverable)", err, {
2465
+ import_log10.log.warn("error notarizing (recoverable)", err, {
2407
2466
  file: "notarization-plugin.ts",
2408
2467
  line: 148,
2409
2468
  scope: this,
@@ -2421,7 +2480,7 @@ var NotarizationPlugin = class {
2421
2480
  allNotarized,
2422
2481
  errors.wait()
2423
2482
  ]);
2424
- (0, import_log9.log)("done", {}, {
2483
+ (0, import_log10.log)("done", {}, {
2425
2484
  file: "notarization-plugin.ts",
2426
2485
  line: 159,
2427
2486
  scope: this,
@@ -2451,7 +2510,7 @@ var NotarizationPlugin = class {
2451
2510
  if (this._processedCredentials.has(id)) {
2452
2511
  return;
2453
2512
  }
2454
- await (0, import_util4.entry)(this._processCredentialsTriggers, id).orInsert(new import_async12.Trigger()).value.wait();
2513
+ await (0, import_util4.entry)(this._processCredentialsTriggers, id).orInsert(new import_async13.Trigger()).value.wait();
2455
2514
  }
2456
2515
  /**
2457
2516
  * Requests from other peers to notarize credentials.
@@ -2472,7 +2531,7 @@ var NotarizationPlugin = class {
2472
2531
  createExtension() {
2473
2532
  const extension = new NotarizationTeleportExtension({
2474
2533
  onOpen: async () => {
2475
- (0, import_log9.log)("extension opened", {
2534
+ (0, import_log10.log)("extension opened", {
2476
2535
  peer: extension.localPeerId
2477
2536
  }, {
2478
2537
  file: "notarization-plugin.ts",
@@ -2484,7 +2543,7 @@ var NotarizationPlugin = class {
2484
2543
  this._extensionOpened.emit();
2485
2544
  },
2486
2545
  onClose: async () => {
2487
- (0, import_log9.log)("extension closed", {
2546
+ (0, import_log10.log)("extension closed", {
2488
2547
  peer: extension.localPeerId
2489
2548
  }, {
2490
2549
  file: "notarization-plugin.ts",
@@ -2531,7 +2590,7 @@ var NotarizationTeleportExtension = class extends import_teleport2.RpcExtension
2531
2590
  };
2532
2591
 
2533
2592
  // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2534
- var __decorate = function(decorators, target, key, desc) {
2593
+ var __decorate2 = function(decorators, target, key, desc) {
2535
2594
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2536
2595
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2537
2596
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2549,7 +2608,7 @@ var DataSpace = class DataSpace2 {
2549
2608
  * Error for _state === SpaceState.ERROR.
2550
2609
  */
2551
2610
  this.error = void 0;
2552
- this.stateUpdate = new import_async13.Event();
2611
+ this.stateUpdate = new import_async14.Event();
2553
2612
  this.metrics = {};
2554
2613
  var _a;
2555
2614
  this._inner = params.inner;
@@ -2620,13 +2679,13 @@ var DataSpace = class DataSpace2 {
2620
2679
  * Initialize the data pipeline in a separate task.
2621
2680
  */
2622
2681
  initializeDataPipelineAsync() {
2623
- (0, import_async13.scheduleTask)(this._ctx, async () => {
2682
+ (0, import_async14.scheduleTask)(this._ctx, async () => {
2624
2683
  try {
2625
2684
  this.metrics.pipelineInitBegin = new Date();
2626
2685
  await this.initializeDataPipeline();
2627
2686
  } catch (err) {
2628
2687
  if (err instanceof import_errors3.CancelledError) {
2629
- (0, import_log10.log)("Data pipeline initialization cancelled", err, {
2688
+ (0, import_log11.log)("Data pipeline initialization cancelled", err, {
2630
2689
  file: "data-space.ts",
2631
2690
  line: 172,
2632
2691
  scope: this,
@@ -2634,7 +2693,7 @@ var DataSpace = class DataSpace2 {
2634
2693
  });
2635
2694
  return;
2636
2695
  }
2637
- import_log10.log.error("Error initializing data pipeline", err, {
2696
+ import_log11.log.error("Error initializing data pipeline", err, {
2638
2697
  file: "data-space.ts",
2639
2698
  line: 176,
2640
2699
  scope: this,
@@ -2660,7 +2719,7 @@ var DataSpace = class DataSpace2 {
2660
2719
  });
2661
2720
  this.metrics.controlPipelineReady = new Date();
2662
2721
  await this._createWritableFeeds();
2663
- (0, import_log10.log)("Writable feeds created", {}, {
2722
+ (0, import_log11.log)("Writable feeds created", {}, {
2664
2723
  file: "data-space.ts",
2665
2724
  line: 201,
2666
2725
  scope: this,
@@ -2675,7 +2734,7 @@ var DataSpace = class DataSpace2 {
2675
2734
  await this._inner.initializeDataPipeline();
2676
2735
  this.metrics.dataPipelineOpen = new Date();
2677
2736
  await (0, import_context6.cancelWithContext)(this._ctx, this._inner.dataPipeline.ensureEpochInitialized());
2678
- (0, import_log10.log)("waiting for data pipeline to reach target timeframe", {}, {
2737
+ (0, import_log11.log)("waiting for data pipeline to reach target timeframe", {}, {
2679
2738
  file: "data-space.ts",
2680
2739
  line: 220,
2681
2740
  scope: this,
@@ -2686,7 +2745,7 @@ var DataSpace = class DataSpace2 {
2686
2745
  breakOnStall: false
2687
2746
  });
2688
2747
  this.metrics.dataPipelineReady = new Date();
2689
- (0, import_log10.log)("data pipeline ready", {}, {
2748
+ (0, import_log11.log)("data pipeline ready", {}, {
2690
2749
  file: "data-space.ts",
2691
2750
  line: 229,
2692
2751
  scope: this,
@@ -2762,11 +2821,11 @@ var DataSpace = class DataSpace2 {
2762
2821
  }
2763
2822
  }
2764
2823
  };
2765
- __decorate([
2824
+ __decorate2([
2766
2825
  (0, import_debug3.timed)(1e4)
2767
2826
  ], DataSpace.prototype, "_createWritableFeeds", null);
2768
- DataSpace = __decorate([
2769
- (0, import_async13.trackLeaks)("open", "close")
2827
+ DataSpace = __decorate2([
2828
+ (0, import_async14.trackLeaks)("open", "close")
2770
2829
  ], DataSpace);
2771
2830
 
2772
2831
  // packages/sdk/client-services/src/packlets/spaces/genesis.ts
@@ -2840,7 +2899,7 @@ var spaceGenesis = async (keyring, signingContext, space) => {
2840
2899
  };
2841
2900
 
2842
2901
  // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
2843
- var __decorate2 = function(decorators, target, key, desc) {
2902
+ var __decorate3 = function(decorators, target, key, desc) {
2844
2903
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2845
2904
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2846
2905
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2859,7 +2918,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2859
2918
  this._signingContext = _signingContext;
2860
2919
  this._feedStore = _feedStore;
2861
2920
  this._ctx = new import_context7.Context();
2862
- this.updated = new import_async14.Event();
2921
+ this.updated = new import_async15.Event();
2863
2922
  this._spaces = new import_util6.ComplexMap(import_keys9.PublicKey.hash);
2864
2923
  this._isOpen = false;
2865
2924
  this._instanceId = import_keys9.PublicKey.random().toHex();
@@ -2869,13 +2928,13 @@ var DataSpaceManager = class DataSpaceManager2 {
2869
2928
  return this._spaces;
2870
2929
  }
2871
2930
  async open() {
2872
- (0, import_log11.log)("open", {}, {
2931
+ (0, import_log12.log)("open", {}, {
2873
2932
  file: "data-space-manager.ts",
2874
2933
  line: 80,
2875
2934
  scope: this,
2876
2935
  callSite: (f, a) => f(...a)
2877
2936
  });
2878
- import_log11.log.trace("dxos.echo.data-space-manager.open", import_protocols6.trace.begin({
2937
+ import_log12.log.trace("dxos.echo.data-space-manager.open", import_protocols6.trace.begin({
2879
2938
  id: this._instanceId
2880
2939
  }), {
2881
2940
  file: "data-space-manager.ts",
@@ -2884,7 +2943,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2884
2943
  callSite: (f, a) => f(...a)
2885
2944
  });
2886
2945
  await this._metadataStore.load();
2887
- (0, import_log11.log)("metadata loaded", {
2946
+ (0, import_log12.log)("metadata loaded", {
2888
2947
  spaces: this._metadataStore.spaces.length
2889
2948
  }, {
2890
2949
  file: "data-space-manager.ts",
@@ -2894,7 +2953,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2894
2953
  });
2895
2954
  for (const spaceMetadata of this._metadataStore.spaces) {
2896
2955
  try {
2897
- (0, import_log11.log)("load space", {
2956
+ (0, import_log12.log)("load space", {
2898
2957
  spaceMetadata
2899
2958
  }, {
2900
2959
  file: "data-space-manager.ts",
@@ -2905,7 +2964,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2905
2964
  const space = await this._constructSpace(spaceMetadata);
2906
2965
  space.initializeDataPipelineAsync();
2907
2966
  } catch (err) {
2908
- import_log11.log.error("Error loading space", {
2967
+ import_log12.log.error("Error loading space", {
2909
2968
  spaceMetadata,
2910
2969
  err
2911
2970
  }, {
@@ -2918,7 +2977,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2918
2977
  }
2919
2978
  this._isOpen = true;
2920
2979
  this.updated.emit();
2921
- import_log11.log.trace("dxos.echo.data-space-manager.open", import_protocols6.trace.end({
2980
+ import_log12.log.trace("dxos.echo.data-space-manager.open", import_protocols6.trace.end({
2922
2981
  id: this._instanceId
2923
2982
  }), {
2924
2983
  file: "data-space-manager.ts",
@@ -2928,7 +2987,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2928
2987
  });
2929
2988
  }
2930
2989
  async close() {
2931
- (0, import_log11.log)("close", {}, {
2990
+ (0, import_log12.log)("close", {}, {
2932
2991
  file: "data-space-manager.ts",
2933
2992
  line: 102,
2934
2993
  scope: this,
@@ -2954,7 +3013,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2954
3013
  controlFeedKey,
2955
3014
  dataFeedKey
2956
3015
  };
2957
- (0, import_log11.log)("creating space...", {
3016
+ (0, import_log12.log)("creating space...", {
2958
3017
  spaceKey
2959
3018
  }, {
2960
3019
  file: "data-space-manager.ts",
@@ -2974,7 +3033,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2974
3033
  }
2975
3034
  // TODO(burdon): Rename join space.
2976
3035
  async acceptSpace(opts) {
2977
- (0, import_log11.log)("accept space", {
3036
+ (0, import_log12.log)("accept space", {
2978
3037
  opts
2979
3038
  }, {
2980
3039
  file: "data-space-manager.ts",
@@ -3008,7 +3067,7 @@ var DataSpaceManager = class DataSpaceManager2 {
3008
3067
  }));
3009
3068
  }
3010
3069
  async _constructSpace(metadata) {
3011
- (0, import_log11.log)("construct space", {
3070
+ (0, import_log12.log)("construct space", {
3012
3071
  metadata
3013
3072
  }, {
3014
3073
  file: "data-space-manager.ts",
@@ -3046,7 +3105,7 @@ var DataSpaceManager = class DataSpaceManager2 {
3046
3105
  session.addExtension("dxos.mesh.teleport.notarization", dataSpace.notarizationPlugin.createExtension());
3047
3106
  },
3048
3107
  onAuthFailure: () => {
3049
- import_log11.log.warn("auth failure", {}, {
3108
+ import_log12.log.warn("auth failure", {}, {
3050
3109
  file: "data-space-manager.ts",
3051
3110
  line: 212,
3052
3111
  scope: this,
@@ -3067,7 +3126,7 @@ var DataSpaceManager = class DataSpaceManager2 {
3067
3126
  signingContext: this._signingContext,
3068
3127
  callbacks: {
3069
3128
  beforeReady: async () => {
3070
- (0, import_log11.log)("before space ready", {
3129
+ (0, import_log12.log)("before space ready", {
3071
3130
  space: space.key
3072
3131
  }, {
3073
3132
  file: "data-space-manager.ts",
@@ -3078,7 +3137,7 @@ var DataSpaceManager = class DataSpaceManager2 {
3078
3137
  this._dataServiceSubscriptions.registerSpace(space.key, dataSpace.dataPipeline.databaseHost.createDataServiceHost());
3079
3138
  },
3080
3139
  afterReady: async () => {
3081
- (0, import_log11.log)("after space ready", {
3140
+ (0, import_log12.log)("after space ready", {
3082
3141
  space: space.key,
3083
3142
  open: this._isOpen
3084
3143
  }, {
@@ -3105,28 +3164,28 @@ var DataSpaceManager = class DataSpaceManager2 {
3105
3164
  return dataSpace;
3106
3165
  }
3107
3166
  };
3108
- __decorate2([
3109
- import_async14.synchronized
3167
+ __decorate3([
3168
+ import_async15.synchronized
3110
3169
  ], DataSpaceManager.prototype, "open", null);
3111
- __decorate2([
3112
- import_async14.synchronized
3170
+ __decorate3([
3171
+ import_async15.synchronized
3113
3172
  ], DataSpaceManager.prototype, "close", null);
3114
- __decorate2([
3115
- import_async14.synchronized
3173
+ __decorate3([
3174
+ import_async15.synchronized
3116
3175
  ], DataSpaceManager.prototype, "createSpace", null);
3117
- __decorate2([
3118
- import_async14.synchronized
3176
+ __decorate3([
3177
+ import_async15.synchronized
3119
3178
  ], DataSpaceManager.prototype, "acceptSpace", null);
3120
- DataSpaceManager = __decorate2([
3121
- (0, import_async14.trackLeaks)("open", "close")
3179
+ DataSpaceManager = __decorate3([
3180
+ (0, import_async15.trackLeaks)("open", "close")
3122
3181
  ], DataSpaceManager);
3123
3182
 
3124
3183
  // packages/sdk/client-services/src/packlets/spaces/spaces-service.ts
3125
- var import_async15 = require("@dxos/async");
3184
+ var import_async16 = require("@dxos/async");
3126
3185
  var import_codec_protobuf12 = require("@dxos/codec-protobuf");
3127
3186
  var import_debug5 = require("@dxos/debug");
3128
3187
  var import_echo_pipeline2 = require("@dxos/echo-pipeline");
3129
- var import_log12 = require("@dxos/log");
3188
+ var import_log13 = require("@dxos/log");
3130
3189
  var import_protocols7 = require("@dxos/protocols");
3131
3190
  var import_services9 = require("@dxos/protocols/proto/dxos/client/services");
3132
3191
  var import_util7 = require("@dxos/util");
@@ -3154,7 +3213,7 @@ var SpacesServiceImpl = class {
3154
3213
  const onUpdate = async () => {
3155
3214
  const dataSpaceManager = await this._getDataSpaceManager();
3156
3215
  const spaces = Array.from(dataSpaceManager.spaces.values()).map((space) => this._transformSpace(space));
3157
- (0, import_log12.log)("update", {
3216
+ (0, import_log13.log)("update", {
3158
3217
  spaces
3159
3218
  }, {
3160
3219
  file: "spaces-service.ts",
@@ -3166,9 +3225,9 @@ var SpacesServiceImpl = class {
3166
3225
  spaces
3167
3226
  });
3168
3227
  };
3169
- (0, import_async15.scheduleTask)(ctx, async () => {
3228
+ (0, import_async16.scheduleTask)(ctx, async () => {
3170
3229
  const dataSpaceManager = await this._getDataSpaceManager();
3171
- const subscriptions = new import_async15.EventSubscriptions();
3230
+ const subscriptions = new import_async16.EventSubscriptions();
3172
3231
  ctx.onDispose(() => subscriptions.clear());
3173
3232
  const subscribeSpaces = () => {
3174
3233
  subscriptions.clear();
@@ -3203,7 +3262,7 @@ var SpacesServiceImpl = class {
3203
3262
  }
3204
3263
  subscribeMessages({ spaceKey, channel }) {
3205
3264
  return new import_codec_protobuf12.Stream(({ ctx, next }) => {
3206
- (0, import_async15.scheduleTask)(ctx, async () => {
3265
+ (0, import_async16.scheduleTask)(ctx, async () => {
3207
3266
  var _a;
3208
3267
  const dataSpaceManager = await this._getDataSpaceManager();
3209
3268
  const space = (_a = dataSpaceManager.spaces.get(spaceKey)) != null ? _a : (0, import_debug5.raise)(new import_echo_pipeline2.SpaceNotFoundError(spaceKey));
@@ -3224,7 +3283,7 @@ var SpacesServiceImpl = class {
3224
3283
  }
3225
3284
  });
3226
3285
  ctx.onDispose(() => processor.close());
3227
- (0, import_async15.scheduleTask)(ctx, () => processor.open());
3286
+ (0, import_async16.scheduleTask)(ctx, () => processor.open());
3228
3287
  });
3229
3288
  }
3230
3289
  async writeCredentials({ spaceKey, credentials }) {
@@ -3364,1216 +3423,1096 @@ var SystemServiceImpl = class {
3364
3423
  }
3365
3424
  };
3366
3425
 
3367
- // packages/sdk/client-services/src/packlets/vault/iframe-host-runtime.ts
3426
+ // packages/sdk/client-services/src/packlets/services/service-context.ts
3427
+ var import_node_assert11 = __toESM(require("node:assert"));
3368
3428
  var import_async17 = require("@dxos/async");
3369
- var import_client_protocol5 = require("@dxos/client-protocol");
3370
- var import_log13 = require("@dxos/log");
3371
- var import_messaging = require("@dxos/messaging");
3372
- var import_network_manager2 = require("@dxos/network-manager");
3373
- var import_util8 = require("@dxos/util");
3374
-
3375
- // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
3376
- var import_codec_protobuf14 = require("@dxos/codec-protobuf");
3429
+ var import_credentials13 = require("@dxos/credentials");
3377
3430
  var import_debug6 = require("@dxos/debug");
3378
- var import_rpc = require("@dxos/rpc");
3379
- var ClientRpcServer = class {
3380
- constructor(params) {
3381
- this._handlerCache = /* @__PURE__ */ new Map();
3382
- const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
3383
- this._handleCall = handleCall;
3384
- this._handleStream = handleStream;
3385
- this._serviceRegistry = serviceRegistry;
3386
- this._rpcPeer = new import_rpc.RpcPeer({
3387
- ...rpcOptions,
3388
- callHandler: (method, params2) => {
3389
- const [serviceName, methodName] = (0, import_rpc.parseMethodName)(method);
3390
- const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
3391
- if (this._handleCall) {
3392
- return this._handleCall(methodName, params2, handler);
3393
- } else {
3394
- return handler(methodName, params2);
3395
- }
3396
- },
3397
- streamHandler: (method, params2) => {
3398
- const [serviceName, methodName] = (0, import_rpc.parseMethodName)(method);
3399
- const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
3400
- if (this._handleStream) {
3401
- return import_codec_protobuf14.Stream.unwrapPromise(this._handleStream(methodName, params2, handler));
3402
- } else {
3403
- return handler(methodName, params2);
3431
+ var import_echo_pipeline3 = require("@dxos/echo-pipeline");
3432
+ var import_feed_store4 = require("@dxos/feed-store");
3433
+ var import_keyring = require("@dxos/keyring");
3434
+ var import_keys10 = require("@dxos/keys");
3435
+ var import_log14 = require("@dxos/log");
3436
+ var import_protocols8 = require("@dxos/protocols");
3437
+ var import_services10 = require("@dxos/protocols/proto/dxos/client/services");
3438
+ var ServiceContext = class {
3439
+ // prettier-ignore
3440
+ constructor(storage, networkManager, signalManager, modelFactory) {
3441
+ this.storage = storage;
3442
+ this.networkManager = networkManager;
3443
+ this.signalManager = signalManager;
3444
+ this.modelFactory = modelFactory;
3445
+ this.initialized = new import_async17.Trigger();
3446
+ this.dataServiceSubscriptions = new import_echo_pipeline3.DataServiceSubscriptions();
3447
+ this._handlerFactories = /* @__PURE__ */ new Map();
3448
+ this._instanceId = import_keys10.PublicKey.random().toHex();
3449
+ this.metadataStore = new import_echo_pipeline3.MetadataStore(storage.createDirectory("metadata"));
3450
+ this.snapshotStore = new import_echo_pipeline3.SnapshotStore(storage.createDirectory("snapshots"));
3451
+ this.keyring = new import_keyring.Keyring(storage.createDirectory("keyring"));
3452
+ this.feedStore = new import_feed_store4.FeedStore({
3453
+ factory: new import_feed_store4.FeedFactory({
3454
+ root: storage.createDirectory("feeds"),
3455
+ signer: this.keyring,
3456
+ hypercore: {
3457
+ valueEncoding: import_echo_pipeline3.valueEncoding
3404
3458
  }
3405
- }
3459
+ })
3460
+ });
3461
+ this.spaceManager = new import_echo_pipeline3.SpaceManager({
3462
+ feedStore: this.feedStore,
3463
+ networkManager: this.networkManager,
3464
+ metadataStore: this.metadataStore,
3465
+ modelFactory: this.modelFactory,
3466
+ snapshotStore: this.snapshotStore
3406
3467
  });
3468
+ this.identityManager = new IdentityManager(this.metadataStore, this.keyring, this.feedStore, this.spaceManager);
3469
+ this.invitations = new InvitationsHandler(this.networkManager);
3470
+ this._handlerFactories.set(import_services10.Invitation.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => {
3471
+ var _a;
3472
+ return (_a = this.identityManager.identity) != null ? _a : (0, import_debug6.failUndefined)();
3473
+ }, this._acceptIdentity.bind(this)));
3407
3474
  }
3408
3475
  async open() {
3409
- await this._rpcPeer.open();
3476
+ import_log14.log.trace("dxos.sdk.service-context.open", import_protocols8.trace.begin({
3477
+ id: this._instanceId
3478
+ }), {
3479
+ file: "service-context.ts",
3480
+ line: 119,
3481
+ scope: this,
3482
+ callSite: (f, a) => f(...a)
3483
+ });
3484
+ await this._checkStorageVersion();
3485
+ (0, import_log14.log)("opening...", {}, {
3486
+ file: "service-context.ts",
3487
+ line: 123,
3488
+ scope: this,
3489
+ callSite: (f, a) => f(...a)
3490
+ });
3491
+ await this.signalManager.open();
3492
+ await this.networkManager.open();
3493
+ await this.spaceManager.open();
3494
+ await this.identityManager.open();
3495
+ if (this.identityManager.identity) {
3496
+ await this._initialize();
3497
+ }
3498
+ (0, import_log14.log)("opened", {}, {
3499
+ file: "service-context.ts",
3500
+ line: 131,
3501
+ scope: this,
3502
+ callSite: (f, a) => f(...a)
3503
+ });
3504
+ import_log14.log.trace("dxos.sdk.service-context.open", import_protocols8.trace.end({
3505
+ id: this._instanceId
3506
+ }), {
3507
+ file: "service-context.ts",
3508
+ line: 132,
3509
+ scope: this,
3510
+ callSite: (f, a) => f(...a)
3511
+ });
3410
3512
  }
3411
3513
  async close() {
3412
- await this._rpcPeer.close();
3413
- }
3414
- _getServiceHandler(serviceName) {
3415
- var _a;
3416
- if (!this._handlerCache.has(serviceName)) {
3417
- const [key, descriptor] = (_a = Object.entries(this._serviceRegistry.descriptors).find(([key2, descriptor2]) => descriptor2.name === serviceName)) != null ? _a : (0, import_debug6.raise)(new Error(`Service not available: ${serviceName}`));
3418
- const service = this._serviceRegistry.services[key];
3419
- if (!service) {
3420
- throw new Error(`Service not available: ${serviceName}`);
3421
- }
3422
- this._handlerCache.set(serviceName, descriptor.createServer(service));
3423
- }
3424
- return this._handlerCache.get(serviceName);
3514
+ var _a, _b;
3515
+ (0, import_log14.log)("closing...", {}, {
3516
+ file: "service-context.ts",
3517
+ line: 136,
3518
+ scope: this,
3519
+ callSite: (f, a) => f(...a)
3520
+ });
3521
+ await ((_a = this._deviceSpaceSync) == null ? void 0 : _a.close());
3522
+ await ((_b = this.dataSpaceManager) == null ? void 0 : _b.close());
3523
+ await this.identityManager.close();
3524
+ await this.spaceManager.close();
3525
+ await this.feedStore.close();
3526
+ await this.networkManager.close();
3527
+ await this.signalManager.close();
3528
+ this.dataServiceSubscriptions.clear();
3529
+ (0, import_log14.log)("closed", {}, {
3530
+ file: "service-context.ts",
3531
+ line: 145,
3532
+ scope: this,
3533
+ callSite: (f, a) => f(...a)
3534
+ });
3425
3535
  }
3426
- };
3427
-
3428
- // packages/sdk/client-services/src/packlets/vault/shell-runtime.ts
3429
- var import_node_assert11 = __toESM(require("node:assert"));
3430
- var import_async16 = require("@dxos/async");
3431
- var import_client_protocol4 = require("@dxos/client-protocol");
3432
- var import_iframe = require("@dxos/protocols/proto/dxos/iframe");
3433
- var import_rpc2 = require("@dxos/rpc");
3434
- var ShellRuntimeImpl = class {
3435
- constructor(_port) {
3436
- this._port = _port;
3437
- this.layoutUpdate = new import_async16.Event();
3438
- this._layout = import_iframe.ShellLayout.DEFAULT;
3536
+ async createIdentity(params = {}) {
3537
+ const identity = await this.identityManager.createIdentity(params);
3538
+ await this._initialize();
3539
+ return identity;
3439
3540
  }
3440
- get layout() {
3441
- return this._layout;
3541
+ getInvitationHandler(invitation) {
3542
+ const factory = this._handlerFactories.get(invitation.kind);
3543
+ (0, import_node_assert11.default)(factory, `Unknown invitation kind: ${invitation.kind}`);
3544
+ return factory(invitation);
3442
3545
  }
3443
- get invitationCode() {
3444
- return this._invitationCode;
3546
+ async _acceptIdentity(params) {
3547
+ const identity = await this.identityManager.acceptIdentity(params);
3548
+ await this._initialize();
3549
+ return identity;
3445
3550
  }
3446
- get spaceKey() {
3447
- return this._spaceKey;
3551
+ async _checkStorageVersion() {
3552
+ await this.metadataStore.load();
3553
+ if (this.metadataStore.version !== import_protocols8.STORAGE_VERSION) {
3554
+ throw new Error(`Invalid storage version: current=${this.metadataStore.version}, expected=${import_protocols8.STORAGE_VERSION}`);
3555
+ }
3448
3556
  }
3449
- setLayout(layout, options = {}) {
3450
- this._layout = layout;
3451
- this._invitationCode = options.invitationCode;
3452
- this._spaceKey = options.spaceKey;
3453
- this.layoutUpdate.emit({
3454
- layout,
3455
- ...options
3557
+ // Called when identity is created.
3558
+ async _initialize() {
3559
+ var _a;
3560
+ (0, import_log14.log)("initializing spaces...", {}, {
3561
+ file: "service-context.ts",
3562
+ line: 178,
3563
+ scope: this,
3564
+ callSite: (f, a) => f(...a)
3456
3565
  });
3457
- }
3458
- async setAppContext(context) {
3459
- (0, import_node_assert11.default)(this._appRpc, "runtime not open");
3460
- await this._appRpc.rpc.AppService.setContext(context);
3461
- }
3462
- async open() {
3463
- this._appRpc = (0, import_rpc2.createProtoRpcPeer)({
3464
- requested: import_client_protocol4.appServiceBundle,
3465
- exposed: import_client_protocol4.shellServiceBundle,
3466
- handlers: {
3467
- ShellService: {
3468
- setLayout: async (request) => {
3469
- this._layout = request.layout;
3470
- this._invitationCode = request.invitationCode;
3471
- this._spaceKey = request.spaceKey;
3472
- this.layoutUpdate.emit(request);
3566
+ const identity = (_a = this.identityManager.identity) != null ? _a : (0, import_debug6.failUndefined)();
3567
+ const signingContext = {
3568
+ credentialSigner: identity.getIdentityCredentialSigner(),
3569
+ identityKey: identity.identityKey,
3570
+ deviceKey: identity.deviceKey,
3571
+ profile: identity.profileDocument,
3572
+ recordCredential: async (credential) => {
3573
+ await identity.controlPipeline.writer.write({
3574
+ credential: {
3575
+ credential
3473
3576
  }
3577
+ });
3578
+ }
3579
+ };
3580
+ this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.dataServiceSubscriptions, this.keyring, signingContext, this.feedStore);
3581
+ await this.dataSpaceManager.open();
3582
+ this._handlerFactories.set(import_services10.Invitation.Kind.SPACE, (invitation) => {
3583
+ (0, import_node_assert11.default)(this.dataSpaceManager, "dataSpaceManager not initialized yet");
3584
+ return new SpaceInvitationProtocol(this.dataSpaceManager, signingContext, this.keyring, invitation.spaceKey);
3585
+ });
3586
+ this.initialized.wake();
3587
+ this._deviceSpaceSync = identity.space.spaceState.registerProcessor({
3588
+ process: async (credential) => {
3589
+ const assertion = (0, import_credentials13.getCredentialAssertion)(credential);
3590
+ if (assertion["@type"] !== "dxos.halo.credentials.SpaceMember") {
3591
+ return;
3474
3592
  }
3475
- },
3476
- port: this._port
3593
+ if (assertion.spaceKey.equals(identity.space.key)) {
3594
+ return;
3595
+ }
3596
+ if (!this.dataSpaceManager) {
3597
+ (0, import_log14.log)("dataSpaceManager not initialized yet, ignoring space admission", {
3598
+ details: assertion
3599
+ }, {
3600
+ file: "service-context.ts",
3601
+ line: 217,
3602
+ scope: this,
3603
+ callSite: (f, a) => f(...a)
3604
+ });
3605
+ return;
3606
+ }
3607
+ if (this.dataSpaceManager.spaces.has(assertion.spaceKey)) {
3608
+ (0, import_log14.log)("space already exists, ignoring space admission", {
3609
+ details: assertion
3610
+ }, {
3611
+ file: "service-context.ts",
3612
+ line: 221,
3613
+ scope: this,
3614
+ callSite: (f, a) => f(...a)
3615
+ });
3616
+ return;
3617
+ }
3618
+ try {
3619
+ (0, import_log14.log)("accepting space recorded in halo", {
3620
+ details: assertion
3621
+ }, {
3622
+ file: "service-context.ts",
3623
+ line: 226,
3624
+ scope: this,
3625
+ callSite: (f, a) => f(...a)
3626
+ });
3627
+ await this.dataSpaceManager.acceptSpace({
3628
+ spaceKey: assertion.spaceKey,
3629
+ genesisFeedKey: assertion.genesisFeedKey
3630
+ });
3631
+ } catch (err) {
3632
+ import_log14.log.catch(err, {}, {
3633
+ file: "service-context.ts",
3634
+ line: 232,
3635
+ scope: this,
3636
+ callSite: (f, a) => f(...a)
3637
+ });
3638
+ }
3639
+ }
3477
3640
  });
3478
- await this._appRpc.open();
3479
- }
3480
- async close() {
3481
- var _a;
3482
- await ((_a = this._appRpc) == null ? void 0 : _a.close());
3483
- this._appRpc = void 0;
3641
+ await this._deviceSpaceSync.open();
3484
3642
  }
3485
3643
  };
3486
- var MemoryShellRuntime = class {
3487
- constructor({ layout, invitationCode, spaceKey } = {}) {
3488
- this.layoutUpdate = new import_async16.Event();
3489
- this.contextUpdate = new import_async16.Event();
3490
- this._layout = layout != null ? layout : import_iframe.ShellLayout.DEFAULT;
3491
- this._invitationCode = invitationCode;
3492
- this._spaceKey = spaceKey;
3644
+
3645
+ // packages/sdk/client-services/src/packlets/services/service-registry.ts
3646
+ var ServiceRegistry = class {
3647
+ // prettier-ignore
3648
+ constructor(_serviceBundle, _handlers = {}) {
3649
+ this._serviceBundle = _serviceBundle;
3650
+ this._handlers = _handlers;
3493
3651
  }
3494
- get layout() {
3495
- return this._layout;
3652
+ get descriptors() {
3653
+ return this._serviceBundle;
3496
3654
  }
3497
- get invitationCode() {
3498
- return this._invitationCode;
3655
+ get services() {
3656
+ return this._handlers;
3499
3657
  }
3500
- get spaceKey() {
3501
- return this._spaceKey;
3658
+ setServices(services) {
3659
+ this._handlers = services;
3502
3660
  }
3503
- setLayout(layout, options = {}) {
3504
- this._layout = layout;
3505
- this._invitationCode = options.invitationCode;
3506
- this._spaceKey = options.spaceKey;
3507
- this.layoutUpdate.emit({
3508
- layout,
3509
- ...options
3510
- });
3661
+ addService(name, service) {
3662
+ this._handlers[name] = service;
3511
3663
  }
3512
- async setAppContext(context) {
3513
- this.contextUpdate.emit(context);
3664
+ removeService(name) {
3665
+ delete this._handlers[name];
3514
3666
  }
3515
3667
  };
3516
3668
 
3517
- // packages/sdk/client-services/src/packlets/vault/iframe-host-runtime.ts
3518
- var __decorate3 = function(decorators, target, key, desc) {
3519
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3520
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3521
- r = Reflect.decorate(decorators, target, key, desc);
3522
- else
3523
- for (var i = decorators.length - 1; i >= 0; i--)
3524
- if (d = decorators[i])
3525
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3526
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3527
- };
3528
- var LOCK_KEY = "DXOS_RESOURCE_LOCK";
3529
- var IFrameHostRuntime = class {
3530
- constructor({ config, origin, appPort, shellPort }) {
3531
- this._ready = new import_async17.Trigger();
3532
- this._configProvider = config;
3533
- this.origin = origin;
3534
- this._appPort = appPort;
3535
- this._shellPort = shellPort;
3536
- if (this._shellPort) {
3537
- this._shellRuntime = new ShellRuntimeImpl(this._shellPort);
3669
+ // packages/sdk/client-services/src/packlets/services/service-host.ts
3670
+ var ClientServicesHost = class {
3671
+ constructor({
3672
+ config,
3673
+ modelFactory = (0, import_client_protocol4.createDefaultModelFactory)(),
3674
+ // TODO(burdon): Create ApolloLink abstraction (see Client).
3675
+ transportFactory,
3676
+ signalManager,
3677
+ connectionLog,
3678
+ storage,
3679
+ // TODO(wittjosiah): Turn this on by default.
3680
+ lockKey
3681
+ } = {}) {
3682
+ this._statusUpdate = new import_async18.Event();
3683
+ this._opening = false;
3684
+ this._open = false;
3685
+ this._storage = storage;
3686
+ this._modelFactory = modelFactory;
3687
+ if (config) {
3688
+ this.initialize({
3689
+ config,
3690
+ transportFactory,
3691
+ signalManager
3692
+ });
3693
+ }
3694
+ if (lockKey) {
3695
+ this._resourceLock = new Lock({
3696
+ lockKey,
3697
+ onAcquire: () => {
3698
+ if (!this._opening) {
3699
+ void this.open();
3700
+ }
3701
+ },
3702
+ onRelease: () => this.close()
3703
+ });
3538
3704
  }
3705
+ this._systemService = new SystemServiceImpl({
3706
+ config: this._config,
3707
+ statusUpdate: this._statusUpdate,
3708
+ getCurrentStatus: () => this.isOpen ? import_services11.SystemStatus.ACTIVE : import_services11.SystemStatus.INACTIVE,
3709
+ onUpdateStatus: async (status) => {
3710
+ var _a, _b;
3711
+ if (!this.isOpen && status === import_services11.SystemStatus.ACTIVE) {
3712
+ await ((_a = this._resourceLock) == null ? void 0 : _a.acquire());
3713
+ } else if (this.isOpen && status === import_services11.SystemStatus.INACTIVE) {
3714
+ await ((_b = this._resourceLock) == null ? void 0 : _b.release());
3715
+ }
3716
+ },
3717
+ onReset: async () => {
3718
+ await this.reset();
3719
+ }
3720
+ });
3721
+ this._loggingService = new LoggingServiceImpl();
3722
+ this._serviceRegistry = new ServiceRegistry(import_client_protocol4.clientServiceBundle, {
3723
+ SystemService: this._systemService
3724
+ });
3725
+ }
3726
+ get isOpen() {
3727
+ return this._open;
3728
+ }
3729
+ get serviceRegistry() {
3730
+ return this._serviceRegistry;
3731
+ }
3732
+ get descriptors() {
3733
+ return this._serviceRegistry.descriptors;
3539
3734
  }
3540
3735
  get services() {
3541
- return this._clientServices;
3736
+ return this._serviceRegistry.services;
3542
3737
  }
3543
- get shell() {
3544
- return this._shellRuntime;
3738
+ /**
3739
+ * Initialize the service host with the config.
3740
+ * Config can also be provided in the constructor.
3741
+ * Can only be called once.
3742
+ */
3743
+ initialize({ config, ...options }) {
3744
+ var _a, _b, _c;
3745
+ (0, import_node_assert12.default)(!this._open, "service host is open");
3746
+ if (config) {
3747
+ (0, import_node_assert12.default)(!this._config, "config already set");
3748
+ this._config = config;
3749
+ if (!this._storage) {
3750
+ this._storage = createStorageObjects(config.get("runtime.client.storage", {})).storage;
3751
+ }
3752
+ }
3753
+ const { connectionLog = true, transportFactory = (0, import_network_manager2.createWebRTCTransportFactory)({
3754
+ iceServers: (_a = this._config) == null ? void 0 : _a.get("runtime.services.ice")
3755
+ }), signalManager = new import_messaging.WebsocketSignalManager((_c = (_b = this._config) == null ? void 0 : _b.get("runtime.services.signaling")) != null ? _c : []) } = options;
3756
+ this._signalManager = signalManager;
3757
+ (0, import_node_assert12.default)(!this._networkManager, "network manager already set");
3758
+ this._networkManager = new import_network_manager2.NetworkManager({
3759
+ log: connectionLog,
3760
+ transportFactory,
3761
+ signalManager
3762
+ });
3545
3763
  }
3546
- async start() {
3547
- var _a;
3548
- (0, import_log13.log)("starting...", {}, {
3549
- file: "iframe-host-runtime.ts",
3550
- line: 70,
3764
+ async open() {
3765
+ var _a, _b, _c;
3766
+ if (this._open) {
3767
+ return;
3768
+ }
3769
+ const traceId = import_keys11.PublicKey.random().toHex();
3770
+ import_log15.log.trace("dxos.sdk.client-services-host.open", import_protocols9.trace.begin({
3771
+ id: traceId
3772
+ }), {
3773
+ file: "service-host.ts",
3774
+ line: 187,
3551
3775
  scope: this,
3552
3776
  callSite: (f, a) => f(...a)
3553
3777
  });
3554
- try {
3555
- this._config = await (0, import_util8.getAsyncValue)(this._configProvider);
3556
- this._transportFactory = (0, import_network_manager2.createWebRTCTransportFactory)({
3557
- iceServers: this._config.get("runtime.services.ice")
3558
- });
3559
- const signals = this._config.get("runtime.services.signaling");
3560
- this._clientServices = new LocalClientServices({
3561
- lockKey: LOCK_KEY,
3562
- config: this._config,
3563
- signalManager: signals ? new import_messaging.WebsocketSignalManager(signals) : new import_messaging.MemorySignalManager(new import_messaging.MemorySignalManagerContext()),
3564
- transportFactory: this._transportFactory
3565
- });
3566
- const middleware = {
3567
- handleCall: async (method, params, handler) => {
3568
- const error = await this._ready.wait({
3569
- timeout: import_client_protocol5.PROXY_CONNECTION_TIMEOUT
3570
- });
3571
- if (error) {
3572
- throw error;
3573
- }
3574
- return handler(method, params);
3575
- },
3576
- handleStream: async (method, params, handler) => {
3577
- const error = await this._ready.wait({
3578
- timeout: import_client_protocol5.PROXY_CONNECTION_TIMEOUT
3579
- });
3580
- if (error) {
3581
- throw error;
3582
- }
3583
- return handler(method, params);
3584
- }
3585
- };
3586
- this._clientRpc = new ClientRpcServer({
3587
- serviceRegistry: this._clientServices.host.serviceRegistry,
3588
- port: this._appPort,
3589
- ...middleware
3590
- });
3591
- await Promise.all([
3592
- this._clientServices.open(),
3593
- this._clientRpc.open(),
3594
- (_a = this._shellRuntime) == null ? void 0 : _a.open()
3595
- ]);
3596
- this._ready.wake(void 0);
3597
- (0, import_log13.log)("started", {}, {
3598
- file: "iframe-host-runtime.ts",
3599
- line: 113,
3600
- scope: this,
3601
- callSite: (f, a) => f(...a)
3602
- });
3603
- } catch (err) {
3604
- this._ready.wake(err);
3605
- import_log13.log.catch(err, {}, {
3606
- file: "iframe-host-runtime.ts",
3607
- line: 116,
3608
- scope: this,
3609
- callSite: (f, a) => f(...a)
3610
- });
3611
- }
3612
- }
3613
- async stop() {
3614
- var _a;
3615
- (0, import_log13.log)("stopping...", {}, {
3616
- file: "iframe-host-runtime.ts",
3617
- line: 121,
3778
+ (0, import_node_assert12.default)(this._config, "config not set");
3779
+ (0, import_node_assert12.default)(this._storage, "storage not set");
3780
+ (0, import_node_assert12.default)(this._signalManager, "signal manager not set");
3781
+ (0, import_node_assert12.default)(this._networkManager, "network manager not set");
3782
+ this._opening = true;
3783
+ (0, import_log15.log)("opening...", {
3784
+ lockKey: (_a = this._resourceLock) == null ? void 0 : _a.lockKey
3785
+ }, {
3786
+ file: "service-host.ts",
3787
+ line: 195,
3618
3788
  scope: this,
3619
3789
  callSite: (f, a) => f(...a)
3620
3790
  });
3621
- await this._clientRpc.close();
3622
- await this._clientServices.close();
3623
- await ((_a = this._shellRuntime) == null ? void 0 : _a.close());
3624
- (0, import_log13.log)("stopped", {}, {
3625
- file: "iframe-host-runtime.ts",
3626
- line: 125,
3791
+ await ((_b = this._resourceLock) == null ? void 0 : _b.acquire());
3792
+ await this._loggingService.open();
3793
+ this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._signalManager, this._modelFactory);
3794
+ this._serviceRegistry.setServices({
3795
+ SystemService: this._systemService,
3796
+ IdentityService: new IdentityServiceImpl(this._serviceContext),
3797
+ InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitations, (invitation) => this._serviceContext.getInvitationHandler(invitation)),
3798
+ DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),
3799
+ SpacesService: new SpacesServiceImpl(this._serviceContext.identityManager, this._serviceContext.spaceManager, this._serviceContext.dataServiceSubscriptions, async () => {
3800
+ await this._serviceContext.initialized.wait();
3801
+ return this._serviceContext.dataSpaceManager;
3802
+ }),
3803
+ DataService: new import_echo_pipeline4.DataServiceImpl(this._serviceContext.dataServiceSubscriptions),
3804
+ NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager, this._serviceContext.signalManager),
3805
+ LoggingService: this._loggingService,
3806
+ // TODO(burdon): Move to new protobuf definitions.
3807
+ DevtoolsHost: new DevtoolsServiceImpl({
3808
+ events: new DevtoolsHostEvents(),
3809
+ config: this._config,
3810
+ context: this._serviceContext
3811
+ })
3812
+ });
3813
+ await this._serviceContext.open();
3814
+ this._opening = false;
3815
+ this._open = true;
3816
+ this._statusUpdate.emit();
3817
+ const deviceKey = (_c = this._serviceContext.identityManager.identity) == null ? void 0 : _c.deviceKey;
3818
+ (0, import_log15.log)("opened", {
3819
+ deviceKey
3820
+ }, {
3821
+ file: "service-host.ts",
3822
+ line: 250,
3627
3823
  scope: this,
3628
3824
  callSite: (f, a) => f(...a)
3629
3825
  });
3630
- }
3631
- };
3632
- __decorate3([
3633
- import_log13.logInfo
3634
- ], IFrameHostRuntime.prototype, "origin", void 0);
3635
-
3636
- // packages/sdk/client-services/src/packlets/vault/iframe-proxy-runtime.ts
3637
- var import_async18 = require("@dxos/async");
3638
- var import_client_protocol6 = require("@dxos/client-protocol");
3639
- var import_errors5 = require("@dxos/errors");
3640
- var import_log14 = require("@dxos/log");
3641
- var import_network_manager3 = require("@dxos/network-manager");
3642
- var import_rpc3 = require("@dxos/rpc");
3643
- var import_util9 = require("@dxos/util");
3644
- var IFrameProxyRuntime = class {
3645
- constructor({ config, systemPort, shellPort }) {
3646
- this._id = String(Math.floor(Math.random() * 1e6));
3647
- this._release = new import_async18.Trigger();
3648
- this._configProvider = config;
3649
- this._systemPort = systemPort;
3650
- this._shellPort = shellPort;
3651
- if (this._shellPort) {
3652
- this._shellRuntime = new ShellRuntimeImpl(this._shellPort);
3653
- }
3654
- }
3655
- get shell() {
3656
- return this._shellRuntime;
3657
- }
3658
- async open(origin) {
3659
- var _a;
3660
- this._config = await (0, import_util9.getAsyncValue)(this._configProvider);
3661
- this._transportService = new import_network_manager3.WebRTCTransportService({
3662
- iceServers: this._config.get("runtime.services.ice")
3663
- });
3664
- this._systemRpc = (0, import_rpc3.createProtoRpcPeer)({
3665
- requested: import_client_protocol6.workerServiceBundle,
3666
- exposed: import_client_protocol6.iframeServiceBundle,
3667
- handlers: {
3668
- BridgeService: this._transportService
3669
- },
3670
- port: this._systemPort,
3671
- timeout: 200
3826
+ import_log15.log.trace("dxos.sdk.client-services-host.open", import_protocols9.trace.end({
3827
+ id: traceId
3828
+ }), {
3829
+ file: "service-host.ts",
3830
+ line: 251,
3831
+ scope: this,
3832
+ callSite: (f, a) => f(...a)
3672
3833
  });
3673
- let lockKey;
3674
- if (typeof navigator !== "undefined") {
3675
- lockKey = this._lockKey(origin);
3676
- this._release = new import_async18.Trigger();
3677
- const ready = new import_async18.Trigger();
3678
- void navigator.locks.request(lockKey, async () => {
3679
- ready.wake();
3680
- await this._release.wait();
3681
- });
3682
- await ready.wait();
3683
- }
3684
- try {
3685
- await this._systemRpc.open();
3686
- await this._systemRpc.rpc.WorkerService.start({
3687
- origin,
3688
- lockKey
3689
- });
3690
- } catch (err) {
3691
- import_log14.log.catch(err, {}, {
3692
- file: "iframe-proxy-runtime.ts",
3693
- line: 85,
3694
- scope: this,
3695
- callSite: (f, a) => f(...a)
3696
- });
3697
- throw new import_errors5.RemoteServiceConnectionError("Failed to connect to worker");
3698
- }
3699
- await ((_a = this._shellRuntime) == null ? void 0 : _a.open());
3700
3834
  }
3701
3835
  async close() {
3702
3836
  var _a;
3703
- this._release.wake();
3704
- await ((_a = this._shellRuntime) == null ? void 0 : _a.close());
3705
- await this._systemRpc.rpc.WorkerService.stop();
3706
- await this._systemRpc.close();
3707
- }
3708
- _lockKey(origin) {
3709
- return `${origin}-${this._id}`;
3710
- }
3711
- };
3712
-
3713
- // packages/sdk/client-services/src/packlets/vault/vault-resource-lock.ts
3714
- var import_async19 = require("@dxos/async");
3715
- var import_client_protocol7 = require("@dxos/client-protocol");
3716
- var import_log15 = require("@dxos/log");
3717
- var __decorate4 = function(decorators, target, key, desc) {
3718
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3719
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3720
- r = Reflect.decorate(decorators, target, key, desc);
3721
- else
3722
- for (var i = decorators.length - 1; i >= 0; i--)
3723
- if (d = decorators[i])
3724
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3725
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3726
- };
3727
- var Message;
3728
- (function(Message2) {
3729
- Message2["ACQUIRING"] = "acquiring";
3730
- })(Message || (Message = {}));
3731
- var VaultResourceLock = class {
3732
- constructor({ lockKey, onAcquire, onRelease }) {
3733
- this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
3734
- this._releaseTrigger = new import_async19.Trigger();
3735
- this._lockKey = lockKey;
3736
- this._onAcquire = onAcquire;
3737
- this._onRelease = onRelease;
3738
- this._broadcastChannel.onmessage = this._onMessage.bind(this);
3739
- }
3740
- get lockKey() {
3741
- return this._lockKey;
3742
- }
3743
- async acquire() {
3744
- this._broadcastChannel.postMessage({
3745
- message: Message.ACQUIRING
3746
- });
3747
- try {
3748
- (0, import_log15.log)("aquiring lock...", {}, {
3749
- file: "vault-resource-lock.ts",
3750
- line: 46,
3751
- scope: this,
3752
- callSite: (f, a) => f(...a)
3753
- });
3754
- await (0, import_async19.asyncTimeout)(this._requestLock(), import_client_protocol7.RESOURCE_LOCK_TIMEOUT);
3755
- (0, import_log15.log)("acquired lock", {}, {
3756
- file: "vault-resource-lock.ts",
3757
- line: 48,
3758
- scope: this,
3759
- callSite: (f, a) => f(...a)
3760
- });
3761
- } catch (e) {
3762
- (0, import_log15.log)("stealing lock...", {}, {
3763
- file: "vault-resource-lock.ts",
3764
- line: 50,
3765
- scope: this,
3766
- callSite: (f, a) => f(...a)
3767
- });
3768
- await this._requestLock(true);
3769
- (0, import_log15.log)("stolen lock", {}, {
3770
- file: "vault-resource-lock.ts",
3771
- line: 52,
3772
- scope: this,
3773
- callSite: (f, a) => f(...a)
3774
- });
3775
- }
3776
- }
3777
- async release() {
3778
- this._releaseTrigger.wake();
3779
- }
3780
- _onMessage(event) {
3781
- if (event.data.message === Message.ACQUIRING) {
3782
- this._releaseTrigger.wake();
3837
+ if (!this._open) {
3838
+ return;
3783
3839
  }
3784
- }
3785
- async _requestLock(steal = false) {
3786
- (0, import_log15.log)("requesting lock...", {
3787
- steal
3840
+ const deviceKey = (_a = this._serviceContext.identityManager.identity) == null ? void 0 : _a.deviceKey;
3841
+ (0, import_log15.log)("closing...", {
3842
+ deviceKey
3788
3843
  }, {
3789
- file: "vault-resource-lock.ts",
3790
- line: 67,
3844
+ file: "service-host.ts",
3845
+ line: 260,
3791
3846
  scope: this,
3792
3847
  callSite: (f, a) => f(...a)
3793
3848
  });
3794
- const acquired = new import_async19.Trigger();
3795
- void navigator.locks.request(this._lockKey, {
3796
- steal
3797
- }, async () => {
3798
- var _a, _b;
3799
- await ((_a = this._onAcquire) == null ? void 0 : _a.call(this));
3800
- acquired.wake();
3801
- this._releaseTrigger = new import_async19.Trigger();
3802
- await this._releaseTrigger.wait();
3803
- (0, import_log15.log)("releasing lock...", {}, {
3804
- file: "vault-resource-lock.ts",
3805
- line: 76,
3806
- scope: this,
3807
- callSite: (f, a) => f(...a)
3808
- });
3809
- await ((_b = this._onRelease) == null ? void 0 : _b.call(this));
3810
- (0, import_log15.log)("released lock", {}, {
3811
- file: "vault-resource-lock.ts",
3812
- line: 78,
3813
- scope: this,
3814
- callSite: (f, a) => f(...a)
3815
- });
3816
- }).catch(async () => {
3817
- var _a;
3818
- await ((_a = this._onRelease) == null ? void 0 : _a.call(this));
3849
+ this._serviceRegistry.setServices({
3850
+ SystemService: this._systemService
3819
3851
  });
3820
- await acquired.wait();
3821
- (0, import_log15.log)("recieved lock", {
3822
- steal
3852
+ await this._loggingService.close();
3853
+ await this._serviceContext.close();
3854
+ this._open = false;
3855
+ this._statusUpdate.emit();
3856
+ (0, import_log15.log)("closed", {
3857
+ deviceKey
3823
3858
  }, {
3824
- file: "vault-resource-lock.ts",
3825
- line: 85,
3859
+ file: "service-host.ts",
3860
+ line: 266,
3826
3861
  scope: this,
3827
3862
  callSite: (f, a) => f(...a)
3828
3863
  });
3829
3864
  }
3830
- };
3831
- __decorate4([
3832
- import_log15.logInfo
3833
- ], VaultResourceLock.prototype, "lockKey", null);
3834
-
3835
- // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
3836
- var import_async21 = require("@dxos/async");
3837
- var import_log17 = require("@dxos/log");
3838
- var import_messaging2 = require("@dxos/messaging");
3839
- var import_network_manager4 = require("@dxos/network-manager");
3840
-
3841
- // packages/sdk/client-services/src/packlets/vault/worker-session.ts
3842
- var import_node_assert12 = __toESM(require("node:assert"));
3843
- var import_async20 = require("@dxos/async");
3844
- var import_client_protocol8 = require("@dxos/client-protocol");
3845
- var import_log16 = require("@dxos/log");
3846
- var import_rpc4 = require("@dxos/rpc");
3847
- var import_util10 = require("@dxos/util");
3848
- var __decorate5 = function(decorators, target, key, desc) {
3849
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3850
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3851
- r = Reflect.decorate(decorators, target, key, desc);
3852
- else
3853
- for (var i = decorators.length - 1; i >= 0; i--)
3854
- if (d = decorators[i])
3855
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3856
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3857
- };
3858
- var WorkerSession = class {
3859
- constructor({ serviceHost, systemPort, appPort, shellPort, readySignal }) {
3860
- this._startTrigger = new import_async20.Trigger();
3861
- this.onClose = new import_util10.Callback();
3862
- (0, import_node_assert12.default)(serviceHost);
3863
- this._serviceHost = serviceHost;
3864
- const middleware = {
3865
- handleCall: async (method, params, handler) => {
3866
- const error = await readySignal.wait({
3867
- timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
3868
- });
3869
- if (error) {
3870
- throw error;
3871
- }
3872
- return handler(method, params);
3873
- },
3874
- handleStream: async (method, params, handler) => {
3875
- const error = await readySignal.wait({
3876
- timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
3877
- });
3878
- if (error) {
3879
- throw error;
3880
- }
3881
- return handler(method, params);
3882
- }
3883
- };
3884
- this._clientRpc = new ClientRpcServer({
3885
- serviceRegistry: this._serviceHost.serviceRegistry,
3886
- port: appPort,
3887
- ...middleware
3888
- });
3889
- this._shellClientRpc = new ClientRpcServer({
3890
- serviceRegistry: this._serviceHost.serviceRegistry,
3891
- port: shellPort,
3892
- ...middleware
3893
- });
3894
- this._iframeRpc = (0, import_rpc4.createProtoRpcPeer)({
3895
- requested: import_client_protocol8.iframeServiceBundle,
3896
- exposed: import_client_protocol8.workerServiceBundle,
3897
- handlers: {
3898
- WorkerService: {
3899
- start: async (request) => {
3900
- this.origin = request.origin;
3901
- this.lockKey = request.lockKey;
3902
- this._startTrigger.wake();
3903
- },
3904
- stop: async () => {
3905
- setTimeout(async () => {
3906
- try {
3907
- await this.close();
3908
- } catch (err) {
3909
- import_log16.log.catch(err, {}, {
3910
- file: "worker-session.ts",
3911
- line: 100,
3912
- scope: this,
3913
- callSite: (f, a) => f(...a)
3914
- });
3915
- }
3916
- });
3917
- }
3918
- }
3919
- },
3920
- port: systemPort,
3921
- timeout: 1e3
3865
+ async reset() {
3866
+ var _a;
3867
+ const traceId = import_keys11.PublicKey.random().toHex();
3868
+ import_log15.log.trace("dxos.sdk.client-services-host.reset", import_protocols9.trace.begin({
3869
+ id: traceId
3870
+ }), {
3871
+ file: "service-host.ts",
3872
+ line: 271,
3873
+ scope: this,
3874
+ callSite: (f, a) => f(...a)
3922
3875
  });
3923
- this.bridgeService = this._iframeRpc.rpc.BridgeService;
3924
- }
3925
- async open() {
3926
- import_log16.log.info("opening..", {}, {
3927
- file: "worker-session.ts",
3928
- line: 114,
3876
+ (0, import_log15.log)("resetting...", {}, {
3877
+ file: "service-host.ts",
3878
+ line: 273,
3929
3879
  scope: this,
3930
3880
  callSite: (f, a) => f(...a)
3931
3881
  });
3932
- await Promise.all([
3933
- this._clientRpc.open(),
3934
- this._iframeRpc.open(),
3935
- this._maybeOpenShell()
3936
- ]);
3937
- await this._startTrigger.wait({
3938
- timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
3882
+ await ((_a = this._serviceContext) == null ? void 0 : _a.close());
3883
+ await this._storage.reset();
3884
+ (0, import_log15.log)("reset", {}, {
3885
+ file: "service-host.ts",
3886
+ line: 276,
3887
+ scope: this,
3888
+ callSite: (f, a) => f(...a)
3939
3889
  });
3940
- if (this.lockKey) {
3941
- void this._afterLockReleases(this.lockKey, () => this.close());
3942
- }
3943
- }
3944
- async close() {
3945
- import_log16.log.info("closing..", {}, {
3946
- file: "worker-session.ts",
3947
- line: 124,
3890
+ import_log15.log.trace("dxos.sdk.client-services-host.reset", import_protocols9.trace.end({
3891
+ id: traceId
3892
+ }), {
3893
+ file: "service-host.ts",
3894
+ line: 277,
3948
3895
  scope: this,
3949
3896
  callSite: (f, a) => f(...a)
3950
3897
  });
3951
- try {
3952
- await this.onClose.callIfSet();
3953
- } catch (err) {
3954
- import_log16.log.catch(err, {}, {
3955
- file: "worker-session.ts",
3956
- line: 128,
3957
- scope: this,
3958
- callSite: (f, a) => f(...a)
3959
- });
3960
- }
3961
- await Promise.all([
3962
- this._clientRpc.close(),
3963
- this._iframeRpc.close()
3964
- ]);
3965
- }
3966
- async _maybeOpenShell() {
3967
- try {
3968
- await (0, import_async20.asyncTimeout)(this._shellClientRpc.open(), 1e3);
3969
- } catch (e) {
3970
- import_log16.log.info("No shell connected.", {}, {
3971
- file: "worker-session.ts",
3972
- line: 138,
3973
- scope: this,
3974
- callSite: (f, a) => f(...a)
3975
- });
3976
- }
3977
- }
3978
- _afterLockReleases(lockKey, callback) {
3979
- return navigator.locks.request(lockKey, () => {
3980
- }).then(callback);
3981
3898
  }
3982
3899
  };
3983
- __decorate5([
3984
- import_log16.logInfo
3985
- ], WorkerSession.prototype, "origin", void 0);
3986
- __decorate5([
3987
- import_log16.logInfo
3988
- ], WorkerSession.prototype, "lockKey", void 0);
3989
3900
 
3990
- // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
3991
- var WorkerRuntime = class {
3992
- // prettier-ignore
3993
- constructor(_configProvider) {
3994
- this._configProvider = _configProvider;
3995
- this._transportFactory = new import_network_manager4.WebRTCTransportProxyFactory();
3996
- this._ready = new import_async21.Trigger();
3997
- this.sessions = /* @__PURE__ */ new Set();
3998
- this._clientServices = new ClientServicesHost();
3901
+ // packages/sdk/client-services/src/packlets/services/local-client-services.ts
3902
+ var LocalClientServices = class {
3903
+ constructor(params) {
3904
+ this._host = new ClientServicesHost(params);
3999
3905
  }
4000
- get host() {
4001
- return this._clientServices;
3906
+ get descriptors() {
3907
+ return this._host.descriptors;
4002
3908
  }
4003
- async start() {
4004
- (0, import_log17.log)("starting...", {}, {
4005
- file: "worker-runtime.ts",
4006
- line: 48,
4007
- scope: this,
4008
- callSite: (f, a) => f(...a)
4009
- });
4010
- try {
4011
- this._config = await this._configProvider();
4012
- const signals = this._config.get("runtime.services.signaling");
4013
- this._clientServices.initialize({
4014
- config: this._config,
4015
- signalManager: signals ? new import_messaging2.WebsocketSignalManager(signals) : new import_messaging2.MemorySignalManager(new import_messaging2.MemorySignalManagerContext()),
4016
- transportFactory: this._transportFactory
4017
- });
4018
- await this._clientServices.open();
4019
- this._ready.wake(void 0);
4020
- (0, import_log17.log)("started", {}, {
4021
- file: "worker-runtime.ts",
4022
- line: 62,
4023
- scope: this,
4024
- callSite: (f, a) => f(...a)
4025
- });
4026
- } catch (err) {
4027
- this._ready.wake(err);
4028
- import_log17.log.catch(err, {}, {
4029
- file: "worker-runtime.ts",
4030
- line: 65,
4031
- scope: this,
4032
- callSite: (f, a) => f(...a)
4033
- });
4034
- }
3909
+ get services() {
3910
+ return this._host.services;
4035
3911
  }
4036
- async stop() {
4037
- await this._clientServices.close();
3912
+ get host() {
3913
+ return this._host;
4038
3914
  }
4039
- /**
4040
- * Create a new session.
4041
- */
4042
- async createSession({ appPort, systemPort, shellPort }) {
4043
- const session = new WorkerSession({
4044
- serviceHost: this._clientServices,
4045
- appPort,
4046
- systemPort,
4047
- shellPort,
4048
- readySignal: this._ready
4049
- });
4050
- session.onClose.set(async () => {
4051
- this.sessions.delete(session);
4052
- this._reconnectWebrtc();
4053
- });
4054
- await session.open();
4055
- this.sessions.add(session);
4056
- this._reconnectWebrtc();
3915
+ async open() {
3916
+ await this._host.open();
4057
3917
  }
4058
- /**
4059
- * Selects one of the existing session fro WebRTC networking.
4060
- */
4061
- _reconnectWebrtc() {
4062
- (0, import_log17.log)("reconnecting webrtc...", {}, {
4063
- file: "worker-runtime.ts",
4064
- line: 102,
4065
- scope: this,
4066
- callSite: (f, a) => f(...a)
4067
- });
4068
- if (this._sessionForNetworking) {
4069
- if (!this.sessions.has(this._sessionForNetworking)) {
4070
- this._sessionForNetworking = void 0;
4071
- }
4072
- }
4073
- if (!this._sessionForNetworking) {
4074
- const selected = Array.from(this.sessions).find((session) => session.bridgeService);
4075
- if (selected) {
4076
- this._sessionForNetworking = selected;
4077
- this._transportFactory.setBridgeService(selected.bridgeService);
4078
- } else {
4079
- this._transportFactory.setBridgeService(void 0);
4080
- }
4081
- }
3918
+ async close() {
3919
+ await this._host.close();
4082
3920
  }
4083
3921
  };
4084
3922
 
4085
- // packages/sdk/client-services/src/packlets/services/service-context.ts
4086
- var import_node_assert13 = __toESM(require("node:assert"));
4087
- var import_async22 = require("@dxos/async");
4088
- var import_credentials13 = require("@dxos/credentials");
3923
+ // packages/sdk/client-services/src/packlets/vault/iframe-host-runtime.ts
3924
+ var import_async20 = require("@dxos/async");
3925
+ var import_client_protocol6 = require("@dxos/client-protocol");
3926
+ var import_log16 = require("@dxos/log");
3927
+ var import_messaging2 = require("@dxos/messaging");
3928
+ var import_network_manager3 = require("@dxos/network-manager");
3929
+ var import_util8 = require("@dxos/util");
3930
+
3931
+ // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
3932
+ var import_codec_protobuf14 = require("@dxos/codec-protobuf");
4089
3933
  var import_debug7 = require("@dxos/debug");
4090
- var import_echo_pipeline3 = require("@dxos/echo-pipeline");
4091
- var import_feed_store4 = require("@dxos/feed-store");
4092
- var import_keyring = require("@dxos/keyring");
4093
- var import_keys10 = require("@dxos/keys");
4094
- var import_log18 = require("@dxos/log");
4095
- var import_protocols8 = require("@dxos/protocols");
4096
- var import_services12 = require("@dxos/protocols/proto/dxos/client/services");
4097
- var ServiceContext = class {
4098
- // prettier-ignore
4099
- constructor(storage, networkManager, signalManager, modelFactory) {
4100
- this.storage = storage;
4101
- this.networkManager = networkManager;
4102
- this.signalManager = signalManager;
4103
- this.modelFactory = modelFactory;
4104
- this.initialized = new import_async22.Trigger();
4105
- this.dataServiceSubscriptions = new import_echo_pipeline3.DataServiceSubscriptions();
4106
- this._handlerFactories = /* @__PURE__ */ new Map();
4107
- this._instanceId = import_keys10.PublicKey.random().toHex();
4108
- this.metadataStore = new import_echo_pipeline3.MetadataStore(storage.createDirectory("metadata"));
4109
- this.snapshotStore = new import_echo_pipeline3.SnapshotStore(storage.createDirectory("snapshots"));
4110
- this.keyring = new import_keyring.Keyring(storage.createDirectory("keyring"));
4111
- this.feedStore = new import_feed_store4.FeedStore({
4112
- factory: new import_feed_store4.FeedFactory({
4113
- root: storage.createDirectory("feeds"),
4114
- signer: this.keyring,
4115
- hypercore: {
4116
- valueEncoding: import_echo_pipeline3.valueEncoding
3934
+ var import_rpc = require("@dxos/rpc");
3935
+ var ClientRpcServer = class {
3936
+ constructor(params) {
3937
+ this._handlerCache = /* @__PURE__ */ new Map();
3938
+ const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
3939
+ this._handleCall = handleCall;
3940
+ this._handleStream = handleStream;
3941
+ this._serviceRegistry = serviceRegistry;
3942
+ this._rpcPeer = new import_rpc.RpcPeer({
3943
+ ...rpcOptions,
3944
+ callHandler: (method, params2) => {
3945
+ const [serviceName, methodName] = (0, import_rpc.parseMethodName)(method);
3946
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
3947
+ if (this._handleCall) {
3948
+ return this._handleCall(methodName, params2, handler);
3949
+ } else {
3950
+ return handler(methodName, params2);
4117
3951
  }
4118
- })
4119
- });
4120
- this.spaceManager = new import_echo_pipeline3.SpaceManager({
4121
- feedStore: this.feedStore,
4122
- networkManager: this.networkManager,
4123
- metadataStore: this.metadataStore,
4124
- modelFactory: this.modelFactory,
4125
- snapshotStore: this.snapshotStore
3952
+ },
3953
+ streamHandler: (method, params2) => {
3954
+ const [serviceName, methodName] = (0, import_rpc.parseMethodName)(method);
3955
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
3956
+ if (this._handleStream) {
3957
+ return import_codec_protobuf14.Stream.unwrapPromise(this._handleStream(methodName, params2, handler));
3958
+ } else {
3959
+ return handler(methodName, params2);
3960
+ }
3961
+ }
4126
3962
  });
4127
- this.identityManager = new IdentityManager(this.metadataStore, this.keyring, this.feedStore, this.spaceManager);
4128
- this.invitations = new InvitationsHandler(this.networkManager);
4129
- this._handlerFactories.set(import_services12.Invitation.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => {
4130
- var _a;
4131
- return (_a = this.identityManager.identity) != null ? _a : (0, import_debug7.failUndefined)();
4132
- }, this._acceptIdentity.bind(this)));
4133
3963
  }
4134
3964
  async open() {
4135
- import_log18.log.trace("dxos.sdk.service-context.open", import_protocols8.trace.begin({
4136
- id: this._instanceId
4137
- }), {
4138
- file: "service-context.ts",
4139
- line: 119,
4140
- scope: this,
4141
- callSite: (f, a) => f(...a)
4142
- });
4143
- await this._checkStorageVersion();
4144
- (0, import_log18.log)("opening...", {}, {
4145
- file: "service-context.ts",
4146
- line: 123,
4147
- scope: this,
4148
- callSite: (f, a) => f(...a)
4149
- });
4150
- await this.signalManager.open();
4151
- await this.networkManager.open();
4152
- await this.spaceManager.open();
4153
- await this.identityManager.open();
4154
- if (this.identityManager.identity) {
4155
- await this._initialize();
3965
+ await this._rpcPeer.open();
3966
+ }
3967
+ async close() {
3968
+ await this._rpcPeer.close();
3969
+ }
3970
+ _getServiceHandler(serviceName) {
3971
+ var _a;
3972
+ if (!this._handlerCache.has(serviceName)) {
3973
+ const [key, descriptor] = (_a = Object.entries(this._serviceRegistry.descriptors).find(([key2, descriptor2]) => descriptor2.name === serviceName)) != null ? _a : (0, import_debug7.raise)(new Error(`Service not available: ${serviceName}`));
3974
+ const service = this._serviceRegistry.services[key];
3975
+ if (!service) {
3976
+ throw new Error(`Service not available: ${serviceName}`);
3977
+ }
3978
+ this._handlerCache.set(serviceName, descriptor.createServer(service));
4156
3979
  }
4157
- (0, import_log18.log)("opened", {}, {
4158
- file: "service-context.ts",
4159
- line: 131,
4160
- scope: this,
4161
- callSite: (f, a) => f(...a)
3980
+ return this._handlerCache.get(serviceName);
3981
+ }
3982
+ };
3983
+
3984
+ // packages/sdk/client-services/src/packlets/vault/shell-runtime.ts
3985
+ var import_node_assert13 = __toESM(require("node:assert"));
3986
+ var import_async19 = require("@dxos/async");
3987
+ var import_client_protocol5 = require("@dxos/client-protocol");
3988
+ var import_iframe = require("@dxos/protocols/proto/dxos/iframe");
3989
+ var import_rpc2 = require("@dxos/rpc");
3990
+ var ShellRuntimeImpl = class {
3991
+ constructor(_port) {
3992
+ this._port = _port;
3993
+ this.layoutUpdate = new import_async19.Event();
3994
+ this._layout = import_iframe.ShellLayout.DEFAULT;
3995
+ }
3996
+ get layout() {
3997
+ return this._layout;
3998
+ }
3999
+ get invitationCode() {
4000
+ return this._invitationCode;
4001
+ }
4002
+ get spaceKey() {
4003
+ return this._spaceKey;
4004
+ }
4005
+ setLayout(layout, options = {}) {
4006
+ this._layout = layout;
4007
+ this._invitationCode = options.invitationCode;
4008
+ this._spaceKey = options.spaceKey;
4009
+ this.layoutUpdate.emit({
4010
+ layout,
4011
+ ...options
4162
4012
  });
4163
- import_log18.log.trace("dxos.sdk.service-context.open", import_protocols8.trace.end({
4164
- id: this._instanceId
4165
- }), {
4166
- file: "service-context.ts",
4167
- line: 132,
4168
- scope: this,
4169
- callSite: (f, a) => f(...a)
4013
+ }
4014
+ async setAppContext(context) {
4015
+ (0, import_node_assert13.default)(this._appRpc, "runtime not open");
4016
+ await this._appRpc.rpc.AppService.setContext(context);
4017
+ }
4018
+ async open() {
4019
+ this._appRpc = (0, import_rpc2.createProtoRpcPeer)({
4020
+ requested: import_client_protocol5.appServiceBundle,
4021
+ exposed: import_client_protocol5.shellServiceBundle,
4022
+ handlers: {
4023
+ ShellService: {
4024
+ setLayout: async (request) => {
4025
+ this._layout = request.layout;
4026
+ this._invitationCode = request.invitationCode;
4027
+ this._spaceKey = request.spaceKey;
4028
+ this.layoutUpdate.emit(request);
4029
+ }
4030
+ }
4031
+ },
4032
+ port: this._port
4170
4033
  });
4034
+ await this._appRpc.open();
4171
4035
  }
4172
4036
  async close() {
4173
- var _a, _b;
4174
- (0, import_log18.log)("closing...", {}, {
4175
- file: "service-context.ts",
4176
- line: 136,
4177
- scope: this,
4178
- callSite: (f, a) => f(...a)
4179
- });
4180
- await ((_a = this._deviceSpaceSync) == null ? void 0 : _a.close());
4181
- await ((_b = this.dataSpaceManager) == null ? void 0 : _b.close());
4182
- await this.identityManager.close();
4183
- await this.spaceManager.close();
4184
- await this.feedStore.close();
4185
- await this.networkManager.close();
4186
- await this.signalManager.close();
4187
- this.dataServiceSubscriptions.clear();
4188
- (0, import_log18.log)("closed", {}, {
4189
- file: "service-context.ts",
4190
- line: 145,
4191
- scope: this,
4192
- callSite: (f, a) => f(...a)
4193
- });
4037
+ var _a;
4038
+ await ((_a = this._appRpc) == null ? void 0 : _a.close());
4039
+ this._appRpc = void 0;
4194
4040
  }
4195
- async createIdentity(params = {}) {
4196
- const identity = await this.identityManager.createIdentity(params);
4197
- await this._initialize();
4198
- return identity;
4041
+ };
4042
+ var MemoryShellRuntime = class {
4043
+ constructor({ layout, invitationCode, spaceKey } = {}) {
4044
+ this.layoutUpdate = new import_async19.Event();
4045
+ this.contextUpdate = new import_async19.Event();
4046
+ this._layout = layout != null ? layout : import_iframe.ShellLayout.DEFAULT;
4047
+ this._invitationCode = invitationCode;
4048
+ this._spaceKey = spaceKey;
4199
4049
  }
4200
- getInvitationHandler(invitation) {
4201
- const factory = this._handlerFactories.get(invitation.kind);
4202
- (0, import_node_assert13.default)(factory, `Unknown invitation kind: ${invitation.kind}`);
4203
- return factory(invitation);
4050
+ get layout() {
4051
+ return this._layout;
4204
4052
  }
4205
- async _acceptIdentity(params) {
4206
- const identity = await this.identityManager.acceptIdentity(params);
4207
- await this._initialize();
4208
- return identity;
4053
+ get invitationCode() {
4054
+ return this._invitationCode;
4209
4055
  }
4210
- async _checkStorageVersion() {
4211
- await this.metadataStore.load();
4212
- if (this.metadataStore.version !== import_protocols8.STORAGE_VERSION) {
4213
- throw new Error(`Invalid storage version: current=${this.metadataStore.version}, expected=${import_protocols8.STORAGE_VERSION}`);
4056
+ get spaceKey() {
4057
+ return this._spaceKey;
4058
+ }
4059
+ setLayout(layout, options = {}) {
4060
+ this._layout = layout;
4061
+ this._invitationCode = options.invitationCode;
4062
+ this._spaceKey = options.spaceKey;
4063
+ this.layoutUpdate.emit({
4064
+ layout,
4065
+ ...options
4066
+ });
4067
+ }
4068
+ async setAppContext(context) {
4069
+ this.contextUpdate.emit(context);
4070
+ }
4071
+ };
4072
+
4073
+ // packages/sdk/client-services/src/packlets/vault/iframe-host-runtime.ts
4074
+ var __decorate4 = function(decorators, target, key, desc) {
4075
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4076
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
4077
+ r = Reflect.decorate(decorators, target, key, desc);
4078
+ else
4079
+ for (var i = decorators.length - 1; i >= 0; i--)
4080
+ if (d = decorators[i])
4081
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4082
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
4083
+ };
4084
+ var LOCK_KEY = "DXOS_RESOURCE_LOCK";
4085
+ var IFrameHostRuntime = class {
4086
+ constructor({ config, origin, appPort, shellPort }) {
4087
+ this._ready = new import_async20.Trigger();
4088
+ this._configProvider = config;
4089
+ this.origin = origin;
4090
+ this._appPort = appPort;
4091
+ this._shellPort = shellPort;
4092
+ if (this._shellPort) {
4093
+ this._shellRuntime = new ShellRuntimeImpl(this._shellPort);
4214
4094
  }
4215
4095
  }
4216
- // Called when identity is created.
4217
- async _initialize() {
4096
+ get services() {
4097
+ return this._clientServices;
4098
+ }
4099
+ get shell() {
4100
+ return this._shellRuntime;
4101
+ }
4102
+ async start() {
4218
4103
  var _a;
4219
- (0, import_log18.log)("initializing spaces...", {}, {
4220
- file: "service-context.ts",
4221
- line: 178,
4104
+ (0, import_log16.log)("starting...", {}, {
4105
+ file: "iframe-host-runtime.ts",
4106
+ line: 70,
4222
4107
  scope: this,
4223
4108
  callSite: (f, a) => f(...a)
4224
4109
  });
4225
- const identity = (_a = this.identityManager.identity) != null ? _a : (0, import_debug7.failUndefined)();
4226
- const signingContext = {
4227
- credentialSigner: identity.getIdentityCredentialSigner(),
4228
- identityKey: identity.identityKey,
4229
- deviceKey: identity.deviceKey,
4230
- profile: identity.profileDocument,
4231
- recordCredential: async (credential) => {
4232
- await identity.controlPipeline.writer.write({
4233
- credential: {
4234
- credential
4235
- }
4236
- });
4237
- }
4238
- };
4239
- this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.dataServiceSubscriptions, this.keyring, signingContext, this.feedStore);
4240
- await this.dataSpaceManager.open();
4241
- this._handlerFactories.set(import_services12.Invitation.Kind.SPACE, (invitation) => {
4242
- (0, import_node_assert13.default)(this.dataSpaceManager, "dataSpaceManager not initialized yet");
4243
- return new SpaceInvitationProtocol(this.dataSpaceManager, signingContext, this.keyring, invitation.spaceKey);
4244
- });
4245
- this.initialized.wake();
4246
- this._deviceSpaceSync = identity.space.spaceState.registerProcessor({
4247
- process: async (credential) => {
4248
- const assertion = (0, import_credentials13.getCredentialAssertion)(credential);
4249
- if (assertion["@type"] !== "dxos.halo.credentials.SpaceMember") {
4250
- return;
4251
- }
4252
- if (assertion.spaceKey.equals(identity.space.key)) {
4253
- return;
4254
- }
4255
- if (!this.dataSpaceManager) {
4256
- (0, import_log18.log)("dataSpaceManager not initialized yet, ignoring space admission", {
4257
- details: assertion
4258
- }, {
4259
- file: "service-context.ts",
4260
- line: 217,
4261
- scope: this,
4262
- callSite: (f, a) => f(...a)
4263
- });
4264
- return;
4265
- }
4266
- if (this.dataSpaceManager.spaces.has(assertion.spaceKey)) {
4267
- (0, import_log18.log)("space already exists, ignoring space admission", {
4268
- details: assertion
4269
- }, {
4270
- file: "service-context.ts",
4271
- line: 221,
4272
- scope: this,
4273
- callSite: (f, a) => f(...a)
4274
- });
4275
- return;
4276
- }
4277
- try {
4278
- (0, import_log18.log)("accepting space recorded in halo", {
4279
- details: assertion
4280
- }, {
4281
- file: "service-context.ts",
4282
- line: 226,
4283
- scope: this,
4284
- callSite: (f, a) => f(...a)
4285
- });
4286
- await this.dataSpaceManager.acceptSpace({
4287
- spaceKey: assertion.spaceKey,
4288
- genesisFeedKey: assertion.genesisFeedKey
4110
+ try {
4111
+ this._config = await (0, import_util8.getAsyncValue)(this._configProvider);
4112
+ this._transportFactory = (0, import_network_manager3.createWebRTCTransportFactory)({
4113
+ iceServers: this._config.get("runtime.services.ice")
4114
+ });
4115
+ const signals = this._config.get("runtime.services.signaling");
4116
+ this._clientServices = new LocalClientServices({
4117
+ lockKey: LOCK_KEY,
4118
+ config: this._config,
4119
+ signalManager: signals ? new import_messaging2.WebsocketSignalManager(signals) : new import_messaging2.MemorySignalManager(new import_messaging2.MemorySignalManagerContext()),
4120
+ transportFactory: this._transportFactory
4121
+ });
4122
+ const middleware = {
4123
+ handleCall: async (method, params, handler) => {
4124
+ const error = await this._ready.wait({
4125
+ timeout: import_client_protocol6.PROXY_CONNECTION_TIMEOUT
4289
4126
  });
4290
- } catch (err) {
4291
- import_log18.log.catch(err, {}, {
4292
- file: "service-context.ts",
4293
- line: 232,
4294
- scope: this,
4295
- callSite: (f, a) => f(...a)
4127
+ if (error) {
4128
+ throw error;
4129
+ }
4130
+ return handler(method, params);
4131
+ },
4132
+ handleStream: async (method, params, handler) => {
4133
+ const error = await this._ready.wait({
4134
+ timeout: import_client_protocol6.PROXY_CONNECTION_TIMEOUT
4296
4135
  });
4136
+ if (error) {
4137
+ throw error;
4138
+ }
4139
+ return handler(method, params);
4297
4140
  }
4298
- }
4141
+ };
4142
+ this._clientRpc = new ClientRpcServer({
4143
+ serviceRegistry: this._clientServices.host.serviceRegistry,
4144
+ port: this._appPort,
4145
+ ...middleware
4146
+ });
4147
+ await Promise.all([
4148
+ this._clientServices.open(),
4149
+ this._clientRpc.open(),
4150
+ (_a = this._shellRuntime) == null ? void 0 : _a.open()
4151
+ ]);
4152
+ this._ready.wake(void 0);
4153
+ (0, import_log16.log)("started", {}, {
4154
+ file: "iframe-host-runtime.ts",
4155
+ line: 113,
4156
+ scope: this,
4157
+ callSite: (f, a) => f(...a)
4158
+ });
4159
+ } catch (err) {
4160
+ this._ready.wake(err);
4161
+ import_log16.log.catch(err, {}, {
4162
+ file: "iframe-host-runtime.ts",
4163
+ line: 116,
4164
+ scope: this,
4165
+ callSite: (f, a) => f(...a)
4166
+ });
4167
+ }
4168
+ }
4169
+ async stop() {
4170
+ var _a;
4171
+ (0, import_log16.log)("stopping...", {}, {
4172
+ file: "iframe-host-runtime.ts",
4173
+ line: 121,
4174
+ scope: this,
4175
+ callSite: (f, a) => f(...a)
4176
+ });
4177
+ await this._clientRpc.close();
4178
+ await this._clientServices.close();
4179
+ await ((_a = this._shellRuntime) == null ? void 0 : _a.close());
4180
+ (0, import_log16.log)("stopped", {}, {
4181
+ file: "iframe-host-runtime.ts",
4182
+ line: 125,
4183
+ scope: this,
4184
+ callSite: (f, a) => f(...a)
4299
4185
  });
4300
- await this._deviceSpaceSync.open();
4301
4186
  }
4302
4187
  };
4188
+ __decorate4([
4189
+ import_log16.logInfo
4190
+ ], IFrameHostRuntime.prototype, "origin", void 0);
4303
4191
 
4304
- // packages/sdk/client-services/src/packlets/services/service-registry.ts
4305
- var ServiceRegistry = class {
4306
- // prettier-ignore
4307
- constructor(_serviceBundle, _handlers = {}) {
4308
- this._serviceBundle = _serviceBundle;
4309
- this._handlers = _handlers;
4310
- }
4311
- get descriptors() {
4312
- return this._serviceBundle;
4192
+ // packages/sdk/client-services/src/packlets/vault/iframe-proxy-runtime.ts
4193
+ var import_async21 = require("@dxos/async");
4194
+ var import_client_protocol7 = require("@dxos/client-protocol");
4195
+ var import_errors5 = require("@dxos/errors");
4196
+ var import_log17 = require("@dxos/log");
4197
+ var import_network_manager4 = require("@dxos/network-manager");
4198
+ var import_rpc3 = require("@dxos/rpc");
4199
+ var import_util9 = require("@dxos/util");
4200
+ var IFrameProxyRuntime = class {
4201
+ constructor({ config, systemPort, shellPort }) {
4202
+ this._id = String(Math.floor(Math.random() * 1e6));
4203
+ this._release = new import_async21.Trigger();
4204
+ this._configProvider = config;
4205
+ this._systemPort = systemPort;
4206
+ this._shellPort = shellPort;
4207
+ if (this._shellPort) {
4208
+ this._shellRuntime = new ShellRuntimeImpl(this._shellPort);
4209
+ }
4313
4210
  }
4314
- get services() {
4315
- return this._handlers;
4211
+ get shell() {
4212
+ return this._shellRuntime;
4316
4213
  }
4317
- setServices(services) {
4318
- this._handlers = services;
4214
+ async open(origin) {
4215
+ var _a;
4216
+ this._config = await (0, import_util9.getAsyncValue)(this._configProvider);
4217
+ this._transportService = new import_network_manager4.WebRTCTransportService({
4218
+ iceServers: this._config.get("runtime.services.ice")
4219
+ });
4220
+ this._systemRpc = (0, import_rpc3.createProtoRpcPeer)({
4221
+ requested: import_client_protocol7.workerServiceBundle,
4222
+ exposed: import_client_protocol7.iframeServiceBundle,
4223
+ handlers: {
4224
+ BridgeService: this._transportService
4225
+ },
4226
+ port: this._systemPort,
4227
+ timeout: 200
4228
+ });
4229
+ let lockKey;
4230
+ if (typeof navigator !== "undefined") {
4231
+ lockKey = this._lockKey(origin);
4232
+ this._release = new import_async21.Trigger();
4233
+ const ready = new import_async21.Trigger();
4234
+ void navigator.locks.request(lockKey, async () => {
4235
+ ready.wake();
4236
+ await this._release.wait();
4237
+ });
4238
+ await ready.wait();
4239
+ }
4240
+ try {
4241
+ await this._systemRpc.open();
4242
+ await this._systemRpc.rpc.WorkerService.start({
4243
+ origin,
4244
+ lockKey
4245
+ });
4246
+ } catch (err) {
4247
+ import_log17.log.catch(err, {}, {
4248
+ file: "iframe-proxy-runtime.ts",
4249
+ line: 85,
4250
+ scope: this,
4251
+ callSite: (f, a) => f(...a)
4252
+ });
4253
+ throw new import_errors5.RemoteServiceConnectionError("Failed to connect to worker");
4254
+ }
4255
+ await ((_a = this._shellRuntime) == null ? void 0 : _a.open());
4319
4256
  }
4320
- addService(name, service) {
4321
- this._handlers[name] = service;
4257
+ async close() {
4258
+ var _a;
4259
+ this._release.wake();
4260
+ await ((_a = this._shellRuntime) == null ? void 0 : _a.close());
4261
+ await this._systemRpc.rpc.WorkerService.stop();
4262
+ await this._systemRpc.close();
4322
4263
  }
4323
- removeService(name) {
4324
- delete this._handlers[name];
4264
+ _lockKey(origin) {
4265
+ return `${origin}-${this._id}`;
4325
4266
  }
4326
4267
  };
4327
4268
 
4328
- // packages/sdk/client-services/src/packlets/services/service-host.ts
4329
- var ClientServicesHost = class {
4330
- constructor({
4331
- config,
4332
- modelFactory = (0, import_client_protocol9.createDefaultModelFactory)(),
4333
- // TODO(burdon): Create ApolloLink abstraction (see Client).
4334
- transportFactory,
4335
- signalManager,
4336
- connectionLog,
4337
- storage,
4338
- // TODO(wittjosiah): Turn this on by default.
4339
- lockKey
4340
- } = {}) {
4341
- this._statusUpdate = new import_async23.Event();
4342
- this._opening = false;
4343
- this._open = false;
4344
- this._storage = storage;
4345
- this._modelFactory = modelFactory;
4346
- if (config) {
4347
- this.initialize({
4348
- config,
4349
- transportFactory,
4350
- signalManager
4351
- });
4352
- }
4353
- this._resourceLock = lockKey ? new VaultResourceLock({
4354
- lockKey,
4355
- onAcquire: () => {
4356
- if (!this._opening) {
4357
- void this.open();
4269
+ // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
4270
+ var import_async23 = require("@dxos/async");
4271
+ var import_log19 = require("@dxos/log");
4272
+ var import_messaging3 = require("@dxos/messaging");
4273
+ var import_network_manager5 = require("@dxos/network-manager");
4274
+
4275
+ // packages/sdk/client-services/src/packlets/vault/worker-session.ts
4276
+ var import_node_assert14 = __toESM(require("node:assert"));
4277
+ var import_async22 = require("@dxos/async");
4278
+ var import_client_protocol8 = require("@dxos/client-protocol");
4279
+ var import_log18 = require("@dxos/log");
4280
+ var import_rpc4 = require("@dxos/rpc");
4281
+ var import_util10 = require("@dxos/util");
4282
+ var __decorate5 = function(decorators, target, key, desc) {
4283
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4284
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
4285
+ r = Reflect.decorate(decorators, target, key, desc);
4286
+ else
4287
+ for (var i = decorators.length - 1; i >= 0; i--)
4288
+ if (d = decorators[i])
4289
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4290
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
4291
+ };
4292
+ var WorkerSession = class {
4293
+ constructor({ serviceHost, systemPort, appPort, shellPort, readySignal }) {
4294
+ this._startTrigger = new import_async22.Trigger();
4295
+ this.onClose = new import_util10.Callback();
4296
+ (0, import_node_assert14.default)(serviceHost);
4297
+ this._serviceHost = serviceHost;
4298
+ const middleware = {
4299
+ handleCall: async (method, params, handler) => {
4300
+ const error = await readySignal.wait({
4301
+ timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
4302
+ });
4303
+ if (error) {
4304
+ throw error;
4358
4305
  }
4306
+ return handler(method, params);
4359
4307
  },
4360
- onRelease: () => this.close()
4361
- }) : void 0;
4362
- this._systemService = new SystemServiceImpl({
4363
- config: this._config,
4364
- statusUpdate: this._statusUpdate,
4365
- getCurrentStatus: () => this.isOpen ? import_services13.SystemStatus.ACTIVE : import_services13.SystemStatus.INACTIVE,
4366
- onUpdateStatus: async (status) => {
4367
- var _a, _b;
4368
- if (!this.isOpen && status === import_services13.SystemStatus.ACTIVE) {
4369
- await ((_a = this._resourceLock) == null ? void 0 : _a.acquire());
4370
- } else if (this.isOpen && status === import_services13.SystemStatus.INACTIVE) {
4371
- await ((_b = this._resourceLock) == null ? void 0 : _b.release());
4308
+ handleStream: async (method, params, handler) => {
4309
+ const error = await readySignal.wait({
4310
+ timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
4311
+ });
4312
+ if (error) {
4313
+ throw error;
4372
4314
  }
4373
- },
4374
- onReset: async () => {
4375
- await this.reset();
4315
+ return handler(method, params);
4376
4316
  }
4317
+ };
4318
+ this._clientRpc = new ClientRpcServer({
4319
+ serviceRegistry: this._serviceHost.serviceRegistry,
4320
+ port: appPort,
4321
+ ...middleware
4377
4322
  });
4378
- this._loggingService = new LoggingServiceImpl();
4379
- this._serviceRegistry = new ServiceRegistry(import_client_protocol9.clientServiceBundle, {
4380
- SystemService: this._systemService
4323
+ this._shellClientRpc = new ClientRpcServer({
4324
+ serviceRegistry: this._serviceHost.serviceRegistry,
4325
+ port: shellPort,
4326
+ ...middleware
4381
4327
  });
4382
- }
4383
- get isOpen() {
4384
- return this._open;
4385
- }
4386
- get serviceRegistry() {
4387
- return this._serviceRegistry;
4388
- }
4389
- get descriptors() {
4390
- return this._serviceRegistry.descriptors;
4391
- }
4392
- get services() {
4393
- return this._serviceRegistry.services;
4394
- }
4395
- /**
4396
- * Initialize the service host with the config.
4397
- * Config can also be provided in the constructor.
4398
- * Can only be called once.
4399
- */
4400
- initialize({ config, ...options }) {
4401
- var _a, _b, _c;
4402
- (0, import_node_assert14.default)(!this._open, "service host is open");
4403
- if (config) {
4404
- (0, import_node_assert14.default)(!this._config, "config already set");
4405
- this._config = config;
4406
- if (!this._storage) {
4407
- this._storage = createStorageObjects(config.get("runtime.client.storage", {})).storage;
4408
- }
4409
- }
4410
- const { connectionLog = true, transportFactory = (0, import_network_manager5.createWebRTCTransportFactory)({
4411
- iceServers: (_a = this._config) == null ? void 0 : _a.get("runtime.services.ice")
4412
- }), signalManager = new import_messaging3.WebsocketSignalManager((_c = (_b = this._config) == null ? void 0 : _b.get("runtime.services.signaling")) != null ? _c : []) } = options;
4413
- this._signalManager = signalManager;
4414
- (0, import_node_assert14.default)(!this._networkManager, "network manager already set");
4415
- this._networkManager = new import_network_manager5.NetworkManager({
4416
- log: connectionLog,
4417
- transportFactory,
4418
- signalManager
4328
+ this._iframeRpc = (0, import_rpc4.createProtoRpcPeer)({
4329
+ requested: import_client_protocol8.iframeServiceBundle,
4330
+ exposed: import_client_protocol8.workerServiceBundle,
4331
+ handlers: {
4332
+ WorkerService: {
4333
+ start: async (request) => {
4334
+ this.origin = request.origin;
4335
+ this.lockKey = request.lockKey;
4336
+ this._startTrigger.wake();
4337
+ },
4338
+ stop: async () => {
4339
+ setTimeout(async () => {
4340
+ try {
4341
+ await this.close();
4342
+ } catch (err) {
4343
+ import_log18.log.catch(err, {}, {
4344
+ file: "worker-session.ts",
4345
+ line: 100,
4346
+ scope: this,
4347
+ callSite: (f, a) => f(...a)
4348
+ });
4349
+ }
4350
+ });
4351
+ }
4352
+ }
4353
+ },
4354
+ port: systemPort,
4355
+ timeout: 1e3
4419
4356
  });
4357
+ this.bridgeService = this._iframeRpc.rpc.BridgeService;
4420
4358
  }
4421
4359
  async open() {
4422
- var _a, _b, _c;
4423
- if (this._open) {
4424
- return;
4425
- }
4426
- const traceId = import_keys11.PublicKey.random().toHex();
4427
- import_log19.log.trace("dxos.sdk.client-services-host.open", import_protocols9.trace.begin({
4428
- id: traceId
4429
- }), {
4430
- file: "service-host.ts",
4431
- line: 187,
4432
- scope: this,
4433
- callSite: (f, a) => f(...a)
4434
- });
4435
- (0, import_node_assert14.default)(this._config, "config not set");
4436
- (0, import_node_assert14.default)(this._storage, "storage not set");
4437
- (0, import_node_assert14.default)(this._signalManager, "signal manager not set");
4438
- (0, import_node_assert14.default)(this._networkManager, "network manager not set");
4439
- this._opening = true;
4440
- (0, import_log19.log)("opening...", {
4441
- lockKey: (_a = this._resourceLock) == null ? void 0 : _a.lockKey
4442
- }, {
4443
- file: "service-host.ts",
4444
- line: 195,
4445
- scope: this,
4446
- callSite: (f, a) => f(...a)
4447
- });
4448
- await ((_b = this._resourceLock) == null ? void 0 : _b.acquire());
4449
- await this._loggingService.open();
4450
- this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._signalManager, this._modelFactory);
4451
- this._serviceRegistry.setServices({
4452
- SystemService: this._systemService,
4453
- IdentityService: new IdentityServiceImpl(this._serviceContext),
4454
- InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitations, (invitation) => this._serviceContext.getInvitationHandler(invitation)),
4455
- DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),
4456
- SpacesService: new SpacesServiceImpl(this._serviceContext.identityManager, this._serviceContext.spaceManager, this._serviceContext.dataServiceSubscriptions, async () => {
4457
- await this._serviceContext.initialized.wait();
4458
- return this._serviceContext.dataSpaceManager;
4459
- }),
4460
- DataService: new import_echo_pipeline4.DataServiceImpl(this._serviceContext.dataServiceSubscriptions),
4461
- NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager, this._serviceContext.signalManager),
4462
- LoggingService: this._loggingService,
4463
- // TODO(burdon): Move to new protobuf definitions.
4464
- DevtoolsHost: new DevtoolsServiceImpl({
4465
- events: new DevtoolsHostEvents(),
4466
- config: this._config,
4467
- context: this._serviceContext
4468
- })
4469
- });
4470
- await this._serviceContext.open();
4471
- this._opening = false;
4472
- this._open = true;
4473
- this._statusUpdate.emit();
4474
- const deviceKey = (_c = this._serviceContext.identityManager.identity) == null ? void 0 : _c.deviceKey;
4475
- (0, import_log19.log)("opened", {
4476
- deviceKey
4477
- }, {
4478
- file: "service-host.ts",
4479
- line: 250,
4360
+ import_log18.log.info("opening..", {}, {
4361
+ file: "worker-session.ts",
4362
+ line: 114,
4480
4363
  scope: this,
4481
4364
  callSite: (f, a) => f(...a)
4482
4365
  });
4483
- import_log19.log.trace("dxos.sdk.client-services-host.open", import_protocols9.trace.end({
4484
- id: traceId
4485
- }), {
4486
- file: "service-host.ts",
4487
- line: 251,
4488
- scope: this,
4489
- callSite: (f, a) => f(...a)
4366
+ await Promise.all([
4367
+ this._clientRpc.open(),
4368
+ this._iframeRpc.open(),
4369
+ this._maybeOpenShell()
4370
+ ]);
4371
+ await this._startTrigger.wait({
4372
+ timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
4490
4373
  });
4374
+ if (this.lockKey) {
4375
+ void this._afterLockReleases(this.lockKey, () => this.close());
4376
+ }
4491
4377
  }
4492
4378
  async close() {
4493
- var _a;
4494
- if (!this._open) {
4495
- return;
4496
- }
4497
- const deviceKey = (_a = this._serviceContext.identityManager.identity) == null ? void 0 : _a.deviceKey;
4498
- (0, import_log19.log)("closing...", {
4499
- deviceKey
4500
- }, {
4501
- file: "service-host.ts",
4502
- line: 260,
4503
- scope: this,
4504
- callSite: (f, a) => f(...a)
4505
- });
4506
- this._serviceRegistry.setServices({
4507
- SystemService: this._systemService
4508
- });
4509
- await this._loggingService.close();
4510
- await this._serviceContext.close();
4511
- this._open = false;
4512
- this._statusUpdate.emit();
4513
- (0, import_log19.log)("closed", {
4514
- deviceKey
4515
- }, {
4516
- file: "service-host.ts",
4517
- line: 266,
4379
+ import_log18.log.info("closing..", {}, {
4380
+ file: "worker-session.ts",
4381
+ line: 124,
4518
4382
  scope: this,
4519
4383
  callSite: (f, a) => f(...a)
4520
4384
  });
4385
+ try {
4386
+ await this.onClose.callIfSet();
4387
+ } catch (err) {
4388
+ import_log18.log.catch(err, {}, {
4389
+ file: "worker-session.ts",
4390
+ line: 128,
4391
+ scope: this,
4392
+ callSite: (f, a) => f(...a)
4393
+ });
4394
+ }
4395
+ await Promise.all([
4396
+ this._clientRpc.close(),
4397
+ this._iframeRpc.close()
4398
+ ]);
4521
4399
  }
4522
- async reset() {
4523
- var _a;
4524
- const traceId = import_keys11.PublicKey.random().toHex();
4525
- import_log19.log.trace("dxos.sdk.client-services-host.reset", import_protocols9.trace.begin({
4526
- id: traceId
4527
- }), {
4528
- file: "service-host.ts",
4529
- line: 271,
4530
- scope: this,
4531
- callSite: (f, a) => f(...a)
4532
- });
4533
- (0, import_log19.log)("resetting...", {}, {
4534
- file: "service-host.ts",
4535
- line: 273,
4536
- scope: this,
4537
- callSite: (f, a) => f(...a)
4538
- });
4539
- await ((_a = this._serviceContext) == null ? void 0 : _a.close());
4540
- await this._storage.reset();
4541
- (0, import_log19.log)("reset", {}, {
4542
- file: "service-host.ts",
4543
- line: 276,
4544
- scope: this,
4545
- callSite: (f, a) => f(...a)
4546
- });
4547
- import_log19.log.trace("dxos.sdk.client-services-host.reset", import_protocols9.trace.end({
4548
- id: traceId
4549
- }), {
4550
- file: "service-host.ts",
4551
- line: 277,
4552
- scope: this,
4553
- callSite: (f, a) => f(...a)
4554
- });
4400
+ async _maybeOpenShell() {
4401
+ try {
4402
+ await (0, import_async22.asyncTimeout)(this._shellClientRpc.open(), 1e3);
4403
+ } catch (e) {
4404
+ import_log18.log.info("No shell connected.", {}, {
4405
+ file: "worker-session.ts",
4406
+ line: 138,
4407
+ scope: this,
4408
+ callSite: (f, a) => f(...a)
4409
+ });
4410
+ }
4411
+ }
4412
+ _afterLockReleases(lockKey, callback) {
4413
+ return navigator.locks.request(lockKey, () => {
4414
+ }).then(callback);
4555
4415
  }
4556
4416
  };
4417
+ __decorate5([
4418
+ import_log18.logInfo
4419
+ ], WorkerSession.prototype, "origin", void 0);
4420
+ __decorate5([
4421
+ import_log18.logInfo
4422
+ ], WorkerSession.prototype, "lockKey", void 0);
4557
4423
 
4558
- // packages/sdk/client-services/src/packlets/services/local-client-services.ts
4559
- var LocalClientServices = class {
4560
- constructor(params) {
4561
- this._host = new ClientServicesHost(params);
4424
+ // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
4425
+ var WorkerRuntime = class {
4426
+ // prettier-ignore
4427
+ constructor(_configProvider) {
4428
+ this._configProvider = _configProvider;
4429
+ this._transportFactory = new import_network_manager5.WebRTCTransportProxyFactory();
4430
+ this._ready = new import_async23.Trigger();
4431
+ this.sessions = /* @__PURE__ */ new Set();
4432
+ this._clientServices = new ClientServicesHost();
4562
4433
  }
4563
- get descriptors() {
4564
- return this._host.descriptors;
4434
+ get host() {
4435
+ return this._clientServices;
4565
4436
  }
4566
- get services() {
4567
- return this._host.services;
4437
+ async start() {
4438
+ (0, import_log19.log)("starting...", {}, {
4439
+ file: "worker-runtime.ts",
4440
+ line: 48,
4441
+ scope: this,
4442
+ callSite: (f, a) => f(...a)
4443
+ });
4444
+ try {
4445
+ this._config = await this._configProvider();
4446
+ const signals = this._config.get("runtime.services.signaling");
4447
+ this._clientServices.initialize({
4448
+ config: this._config,
4449
+ signalManager: signals ? new import_messaging3.WebsocketSignalManager(signals) : new import_messaging3.MemorySignalManager(new import_messaging3.MemorySignalManagerContext()),
4450
+ transportFactory: this._transportFactory
4451
+ });
4452
+ await this._clientServices.open();
4453
+ this._ready.wake(void 0);
4454
+ (0, import_log19.log)("started", {}, {
4455
+ file: "worker-runtime.ts",
4456
+ line: 62,
4457
+ scope: this,
4458
+ callSite: (f, a) => f(...a)
4459
+ });
4460
+ } catch (err) {
4461
+ this._ready.wake(err);
4462
+ import_log19.log.catch(err, {}, {
4463
+ file: "worker-runtime.ts",
4464
+ line: 65,
4465
+ scope: this,
4466
+ callSite: (f, a) => f(...a)
4467
+ });
4468
+ }
4568
4469
  }
4569
- get host() {
4570
- return this._host;
4470
+ async stop() {
4471
+ await this._clientServices.close();
4571
4472
  }
4572
- async open() {
4573
- await this._host.open();
4473
+ /**
4474
+ * Create a new session.
4475
+ */
4476
+ async createSession({ appPort, systemPort, shellPort }) {
4477
+ const session = new WorkerSession({
4478
+ serviceHost: this._clientServices,
4479
+ appPort,
4480
+ systemPort,
4481
+ shellPort,
4482
+ readySignal: this._ready
4483
+ });
4484
+ session.onClose.set(async () => {
4485
+ this.sessions.delete(session);
4486
+ this._reconnectWebrtc();
4487
+ });
4488
+ await session.open();
4489
+ this.sessions.add(session);
4490
+ this._reconnectWebrtc();
4574
4491
  }
4575
- async close() {
4576
- await this._host.close();
4492
+ /**
4493
+ * Selects one of the existing session fro WebRTC networking.
4494
+ */
4495
+ _reconnectWebrtc() {
4496
+ (0, import_log19.log)("reconnecting webrtc...", {}, {
4497
+ file: "worker-runtime.ts",
4498
+ line: 102,
4499
+ scope: this,
4500
+ callSite: (f, a) => f(...a)
4501
+ });
4502
+ if (this._sessionForNetworking) {
4503
+ if (!this.sessions.has(this._sessionForNetworking)) {
4504
+ this._sessionForNetworking = void 0;
4505
+ }
4506
+ }
4507
+ if (!this._sessionForNetworking) {
4508
+ const selected = Array.from(this.sessions).find((session) => session.bridgeService);
4509
+ if (selected) {
4510
+ this._sessionForNetworking = selected;
4511
+ this._transportFactory.setBridgeService(selected.bridgeService);
4512
+ } else {
4513
+ this._transportFactory.setBridgeService(void 0);
4514
+ }
4515
+ }
4577
4516
  }
4578
4517
  };
4579
4518
  // Annotate the CommonJS export names for ESM import in node:
@@ -4592,6 +4531,7 @@ var LocalClientServices = class {
4592
4531
  InvitationsHandler,
4593
4532
  InvitationsServiceImpl,
4594
4533
  LocalClientServices,
4534
+ Lock,
4595
4535
  MemoryShellRuntime,
4596
4536
  ServiceContext,
4597
4537
  ServiceRegistry,
@@ -4599,12 +4539,12 @@ var LocalClientServices = class {
4599
4539
  SpaceInvitationProtocol,
4600
4540
  SpacesServiceImpl,
4601
4541
  TrustedKeySetAuthVerifier,
4602
- VaultResourceLock,
4603
4542
  WorkerRuntime,
4604
4543
  WorkerSession,
4605
4544
  createAuthProvider,
4606
4545
  createStorageObjects,
4607
4546
  getNetworkPeers,
4547
+ isLocked,
4608
4548
  subscribeToFeedBlocks,
4609
4549
  subscribeToFeeds,
4610
4550
  subscribeToNetworkStatus,