@dxos/client-services 0.1.49-next.fdd6c88 → 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 (49) hide show
  1. package/dist/lib/browser/{chunk-KMQOZOUZ.mjs → chunk-UL74TKNZ.mjs} +543 -1131
  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 +1164 -1214
  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 +302 -780
  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/devtools/devtools.d.ts +2 -1
  15. package/dist/types/src/packlets/devtools/devtools.d.ts.map +1 -1
  16. package/dist/types/src/packlets/devtools/metadata.d.ts +7 -0
  17. package/dist/types/src/packlets/devtools/metadata.d.ts.map +1 -0
  18. package/dist/types/src/packlets/locks/browser.d.ts +16 -0
  19. package/dist/types/src/packlets/locks/browser.d.ts.map +1 -0
  20. package/dist/types/src/packlets/locks/index.d.ts +3 -0
  21. package/dist/types/src/packlets/locks/index.d.ts.map +1 -0
  22. package/dist/types/src/packlets/locks/node.d.ts +13 -0
  23. package/dist/types/src/packlets/locks/node.d.ts.map +1 -0
  24. package/dist/types/src/packlets/locks/resource-lock.d.ts +16 -0
  25. package/dist/types/src/packlets/locks/resource-lock.d.ts.map +1 -0
  26. package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
  27. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  28. package/dist/types/src/packlets/spaces/data-space.d.ts +1 -1
  29. package/dist/types/src/packlets/spaces/notarization-plugin.d.ts.map +1 -1
  30. package/dist/types/src/packlets/spaces/spaces-service.d.ts +0 -3
  31. package/dist/types/src/packlets/spaces/spaces-service.d.ts.map +1 -1
  32. package/dist/types/src/packlets/vault/index.d.ts +0 -1
  33. package/dist/types/src/packlets/vault/index.d.ts.map +1 -1
  34. package/package.json +33 -30
  35. package/src/index.ts +1 -0
  36. package/src/packlets/devtools/devtools.ts +6 -0
  37. package/src/packlets/devtools/metadata.ts +14 -0
  38. package/src/packlets/{vault/vault-resource-lock.ts → locks/browser.ts} +13 -11
  39. package/src/packlets/locks/index.ts +6 -0
  40. package/src/packlets/locks/node.ts +52 -0
  41. package/src/packlets/locks/resource-lock.ts +24 -0
  42. package/src/packlets/services/service-context.ts +1 -2
  43. package/src/packlets/services/service-host.ts +13 -13
  44. package/src/packlets/spaces/notarization-plugin.ts +7 -3
  45. package/src/packlets/spaces/spaces-service.ts +0 -3
  46. package/src/packlets/vault/index.ts +0 -1
  47. package/dist/lib/browser/chunk-KMQOZOUZ.mjs.map +0 -7
  48. package/dist/types/src/packlets/vault/vault-resource-lock.d.ts +0 -20
  49. 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,
@@ -69,7 +70,7 @@ module.exports = __toCommonJS(src_exports);
69
70
 
70
71
  // packages/sdk/client-services/src/packlets/devtools/devtools.ts
71
72
  var import_async3 = require("@dxos/async");
72
- var import_codec_protobuf5 = require("@dxos/codec-protobuf");
73
+ var import_codec_protobuf6 = require("@dxos/codec-protobuf");
73
74
 
74
75
  // packages/sdk/client-services/src/packlets/devtools/feeds.ts
75
76
  var import_async = require("@dxos/async");
@@ -157,11 +158,22 @@ var subscribeToKeyringKeys = ({ keyring }) => new import_codec_protobuf2.Stream(
157
158
  (0, import_async2.scheduleTask)(ctx, update);
158
159
  });
159
160
 
160
- // packages/sdk/client-services/src/packlets/devtools/network.ts
161
+ // packages/sdk/client-services/src/packlets/devtools/metadata.ts
161
162
  var import_codec_protobuf3 = require("@dxos/codec-protobuf");
163
+ var subscribeToMetadata = ({ context }) => new import_codec_protobuf3.Stream(({ next, ctx }) => {
164
+ context.metadataStore.update.on(ctx, (data) => next({
165
+ metadata: data
166
+ }));
167
+ next({
168
+ metadata: context.metadataStore.metadata
169
+ });
170
+ });
171
+
172
+ // packages/sdk/client-services/src/packlets/devtools/network.ts
173
+ var import_codec_protobuf4 = require("@dxos/codec-protobuf");
162
174
  var import_context = require("@dxos/context");
163
175
  var import_keys2 = require("@dxos/keys");
164
- var subscribeToNetworkStatus = ({ signalManager }) => new import_codec_protobuf3.Stream(({ next, close }) => {
176
+ var subscribeToNetworkStatus = ({ signalManager }) => new import_codec_protobuf4.Stream(({ next, close }) => {
165
177
  const update = () => {
166
178
  try {
167
179
  const status = signalManager.getStatus();
@@ -175,7 +187,7 @@ var subscribeToNetworkStatus = ({ signalManager }) => new import_codec_protobuf3
175
187
  signalManager.statusChanged.on(() => update());
176
188
  update();
177
189
  });
178
- var subscribeToSignal = ({ signalManager }) => new import_codec_protobuf3.Stream(({ next }) => {
190
+ var subscribeToSignal = ({ signalManager }) => new import_codec_protobuf4.Stream(({ next }) => {
179
191
  const ctx = new import_context.Context();
180
192
  signalManager.onMessage.on(ctx, (message) => {
181
193
  next({
@@ -197,7 +209,7 @@ var subscribeToSignal = ({ signalManager }) => new import_codec_protobuf3.Stream
197
209
  return ctx.dispose();
198
210
  };
199
211
  });
200
- var subscribeToNetworkTopics = ({ networkManager }) => new import_codec_protobuf3.Stream(({ next, close }) => {
212
+ var subscribeToNetworkTopics = ({ networkManager }) => new import_codec_protobuf4.Stream(({ next, close }) => {
201
213
  const update = () => {
202
214
  try {
203
215
  const topics = networkManager.topics;
@@ -218,7 +230,7 @@ var subscribeToNetworkTopics = ({ networkManager }) => new import_codec_protobuf
218
230
  networkManager.topicsUpdated.on(update);
219
231
  update();
220
232
  });
221
- var subscribeToSwarmInfo = ({ networkManager }) => new import_codec_protobuf3.Stream(({ next }) => {
233
+ var subscribeToSwarmInfo = ({ networkManager }) => new import_codec_protobuf4.Stream(({ next }) => {
222
234
  var _a;
223
235
  const update = () => {
224
236
  var _a2;
@@ -246,9 +258,9 @@ var getNetworkPeers = ({ networkManager }, request) => {
246
258
  };
247
259
 
248
260
  // packages/sdk/client-services/src/packlets/devtools/spaces.ts
249
- var import_codec_protobuf4 = require("@dxos/codec-protobuf");
261
+ var import_codec_protobuf5 = require("@dxos/codec-protobuf");
250
262
  var subscribeToSpaces = (context, { spaceKeys = [] }) => {
251
- return new import_codec_protobuf4.Stream(({ next }) => {
263
+ return new import_codec_protobuf5.Stream(({ next }) => {
252
264
  let unsubscribe;
253
265
  const update = async () => {
254
266
  const spaces = [
@@ -292,7 +304,7 @@ var DevtoolsServiceImpl = class {
292
304
  this.params = params;
293
305
  }
294
306
  events(request) {
295
- return new import_codec_protobuf5.Stream(({ next }) => {
307
+ return new import_codec_protobuf6.Stream(({ next }) => {
296
308
  this.params.events.ready.on(() => {
297
309
  next({
298
310
  ready: {}
@@ -384,6 +396,11 @@ var DevtoolsServiceImpl = class {
384
396
  networkManager: this.params.context.networkManager
385
397
  });
386
398
  }
399
+ subscribeToMetadata() {
400
+ return subscribeToMetadata({
401
+ context: this.params.context
402
+ });
403
+ }
387
404
  };
388
405
 
389
406
  // packages/sdk/client-services/src/packlets/identity/authenticator.ts
@@ -907,7 +924,7 @@ var IdentityManager = class {
907
924
 
908
925
  // packages/sdk/client-services/src/packlets/identity/identity-service.ts
909
926
  var import_node_assert3 = __toESM(require("node:assert"));
910
- var import_codec_protobuf6 = require("@dxos/codec-protobuf");
927
+ var import_codec_protobuf7 = require("@dxos/codec-protobuf");
911
928
  var import_credentials6 = require("@dxos/credentials");
912
929
  var import_debug2 = require("@dxos/debug");
913
930
  var IdentityServiceImpl = class {
@@ -923,7 +940,7 @@ var IdentityServiceImpl = class {
923
940
  return (0, import_debug2.todo)();
924
941
  }
925
942
  queryIdentity() {
926
- return new import_codec_protobuf6.Stream(({ next }) => {
943
+ return new import_codec_protobuf7.Stream(({ next }) => {
927
944
  const emitNext = () => next({
928
945
  identity: this._getIdentity()
929
946
  });
@@ -1855,7 +1872,7 @@ var InvitationsHandler = class {
1855
1872
  // packages/sdk/client-services/src/packlets/invitations/invitations-service.ts
1856
1873
  var import_node_assert7 = __toESM(require("node:assert"));
1857
1874
  var import_async9 = require("@dxos/async");
1858
- var import_codec_protobuf7 = require("@dxos/codec-protobuf");
1875
+ var import_codec_protobuf8 = require("@dxos/codec-protobuf");
1859
1876
  var import_log6 = require("@dxos/log");
1860
1877
  var import_services4 = require("@dxos/protocols/proto/dxos/client/services");
1861
1878
  var InvitationsServiceImpl = class {
@@ -1884,7 +1901,7 @@ var InvitationsServiceImpl = class {
1884
1901
  this._createInvitations.set(invitation.get().invitationId, invitation);
1885
1902
  this._invitationCreated.emit(invitation.get());
1886
1903
  }
1887
- return new import_codec_protobuf7.Stream(({ next, close }) => {
1904
+ return new import_codec_protobuf8.Stream(({ next, close }) => {
1888
1905
  invitation.subscribe((invitation2) => {
1889
1906
  next(invitation2);
1890
1907
  }, (err) => {
@@ -1906,7 +1923,7 @@ var InvitationsServiceImpl = class {
1906
1923
  this._acceptInvitations.set(invitation.get().invitationId, invitation);
1907
1924
  this._invitationAccepted.emit(invitation.get());
1908
1925
  }
1909
- return new import_codec_protobuf7.Stream(({ next, close }) => {
1926
+ return new import_codec_protobuf8.Stream(({ next, close }) => {
1910
1927
  invitation.subscribe((invitation2) => {
1911
1928
  next(invitation2);
1912
1929
  }, (err) => {
@@ -1969,7 +1986,7 @@ var InvitationsServiceImpl = class {
1969
1986
  }
1970
1987
  }
1971
1988
  queryInvitations() {
1972
- return new import_codec_protobuf7.Stream(({ next, ctx }) => {
1989
+ return new import_codec_protobuf8.Stream(({ next, ctx }) => {
1973
1990
  this._invitationCreated.on(ctx, (invitation) => {
1974
1991
  next({
1975
1992
  action: import_services4.QueryInvitationsResponse.Action.ADDED,
@@ -2111,20 +2128,20 @@ var SpaceInvitationProtocol = class {
2111
2128
  };
2112
2129
 
2113
2130
  // packages/sdk/client-services/src/packlets/services/service-host.ts
2114
- var import_node_assert14 = __toESM(require("node:assert"));
2115
- var import_async23 = require("@dxos/async");
2116
- 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");
2117
2134
  var import_echo_pipeline4 = require("@dxos/echo-pipeline");
2118
2135
  var import_keys11 = require("@dxos/keys");
2119
- var import_log19 = require("@dxos/log");
2120
- var import_messaging3 = require("@dxos/messaging");
2121
- 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");
2122
2139
  var import_protocols9 = require("@dxos/protocols");
2123
- var import_services13 = require("@dxos/protocols/proto/dxos/client/services");
2140
+ var import_services11 = require("@dxos/protocols/proto/dxos/client/services");
2124
2141
 
2125
2142
  // packages/sdk/client-services/src/packlets/devices/devices-service.ts
2126
2143
  var import_async10 = require("@dxos/async");
2127
- var import_codec_protobuf8 = require("@dxos/codec-protobuf");
2144
+ var import_codec_protobuf9 = require("@dxos/codec-protobuf");
2128
2145
  var import_services6 = require("@dxos/protocols/proto/dxos/client/services");
2129
2146
  var DevicesServiceImpl = class {
2130
2147
  constructor(_identityManager) {
@@ -2134,7 +2151,7 @@ var DevicesServiceImpl = class {
2134
2151
  throw new Error("Method not implemented.");
2135
2152
  }
2136
2153
  queryDevices() {
2137
- return new import_codec_protobuf8.Stream(({ next }) => {
2154
+ return new import_codec_protobuf9.Stream(({ next }) => {
2138
2155
  const update = () => {
2139
2156
  var _a;
2140
2157
  const deviceKeys = (_a = this._identityManager.identity) == null ? void 0 : _a.authorizedDeviceKeys;
@@ -2169,38 +2186,96 @@ var DevicesServiceImpl = class {
2169
2186
  }
2170
2187
  };
2171
2188
 
2172
- // 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"));
2173
2191
  var import_async11 = require("@dxos/async");
2174
- var import_codec_protobuf9 = require("@dxos/codec-protobuf");
2175
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");
2176
2251
  var import_util3 = require("@dxos/util");
2177
2252
  var LoggingServiceImpl = class {
2178
2253
  constructor() {
2179
- this._logs = new import_async11.Event();
2254
+ this._logs = new import_async12.Event();
2180
2255
  this._logProcessor = (_config, entry2) => {
2181
2256
  this._logs.emit(entry2);
2182
2257
  };
2183
2258
  }
2184
2259
  async open() {
2185
- import_log8.log.runtimeConfig.processors.push(this._logProcessor);
2260
+ import_log9.log.runtimeConfig.processors.push(this._logProcessor);
2186
2261
  }
2187
2262
  async close() {
2188
- const index = import_log8.log.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
2189
- 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);
2190
2265
  }
2191
2266
  queryLogs(request) {
2192
2267
  var _a;
2193
2268
  const filters = ((_a = request.filters) == null ? void 0 : _a.length) ? request.filters : void 0;
2194
- return new import_codec_protobuf9.Stream(({ ctx, next }) => {
2269
+ return new import_codec_protobuf10.Stream(({ ctx, next }) => {
2195
2270
  const handler = (entry2) => {
2196
2271
  var _a2, _b, _c;
2197
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"))) {
2198
2273
  return;
2199
2274
  }
2200
- if ((0, import_log8.shouldLog)(entry2, filters)) {
2275
+ if ((0, import_log9.shouldLog)(entry2, filters)) {
2201
2276
  const record = {
2202
2277
  ...entry2,
2203
- context: (0, import_util3.jsonify)((0, import_log8.getContextFromEntry)(entry2))
2278
+ context: (0, import_util3.jsonify)((0, import_log9.getContextFromEntry)(entry2))
2204
2279
  };
2205
2280
  (_b = record.meta) == null ? true : delete _b.bugcheck;
2206
2281
  (_c = record.meta) == null ? true : delete _c.scope;
@@ -2216,14 +2291,14 @@ var LoggingServiceImpl = class {
2216
2291
  };
2217
2292
 
2218
2293
  // packages/sdk/client-services/src/packlets/network/network-service.ts
2219
- var import_codec_protobuf10 = require("@dxos/codec-protobuf");
2294
+ var import_codec_protobuf11 = require("@dxos/codec-protobuf");
2220
2295
  var NetworkServiceImpl = class {
2221
2296
  constructor(networkManager, signalManager) {
2222
2297
  this.networkManager = networkManager;
2223
2298
  this.signalManager = signalManager;
2224
2299
  }
2225
2300
  queryStatus() {
2226
- return new import_codec_protobuf10.Stream(({ next }) => {
2301
+ return new import_codec_protobuf11.Stream(({ next }) => {
2227
2302
  const update = () => {
2228
2303
  next({
2229
2304
  swarm: this.networkManager.connectionState,
@@ -2249,45 +2324,46 @@ var NetworkServiceImpl = class {
2249
2324
 
2250
2325
  // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
2251
2326
  var import_node_assert10 = __toESM(require("node:assert"));
2252
- var import_async14 = require("@dxos/async");
2327
+ var import_async15 = require("@dxos/async");
2253
2328
  var import_context7 = require("@dxos/context");
2254
2329
  var import_credentials12 = require("@dxos/credentials");
2255
2330
  var import_keys9 = require("@dxos/keys");
2256
- var import_log11 = require("@dxos/log");
2331
+ var import_log12 = require("@dxos/log");
2257
2332
  var import_protocols6 = require("@dxos/protocols");
2258
2333
  var import_services8 = require("@dxos/protocols/proto/dxos/client/services");
2259
2334
  var import_teleport_extension_gossip = require("@dxos/teleport-extension-gossip");
2260
2335
  var import_util6 = require("@dxos/util");
2261
2336
 
2262
2337
  // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2263
- var import_async13 = require("@dxos/async");
2338
+ var import_async14 = require("@dxos/async");
2264
2339
  var import_client_protocol3 = require("@dxos/client-protocol");
2265
2340
  var import_context6 = require("@dxos/context");
2266
2341
  var import_debug3 = require("@dxos/debug");
2267
2342
  var import_echo_pipeline = require("@dxos/echo-pipeline");
2268
2343
  var import_errors3 = require("@dxos/errors");
2269
2344
  var import_keys8 = require("@dxos/keys");
2270
- var import_log10 = require("@dxos/log");
2345
+ var import_log11 = require("@dxos/log");
2271
2346
  var import_services7 = require("@dxos/protocols/proto/dxos/client/services");
2272
2347
  var import_credentials9 = require("@dxos/protocols/proto/dxos/halo/credentials");
2273
2348
  var import_util5 = require("@dxos/util");
2274
2349
 
2275
2350
  // packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts
2276
2351
  var import_node_assert9 = __toESM(require("node:assert"));
2277
- var import_async12 = require("@dxos/async");
2352
+ var import_async13 = require("@dxos/async");
2278
2353
  var import_context5 = require("@dxos/context");
2279
2354
  var import_keys7 = require("@dxos/keys");
2280
- var import_log9 = require("@dxos/log");
2355
+ var import_log10 = require("@dxos/log");
2281
2356
  var import_protocols5 = require("@dxos/protocols");
2282
2357
  var import_teleport2 = require("@dxos/teleport");
2283
2358
  var import_util4 = require("@dxos/util");
2284
2359
  var DEFAULT_RETRY_TIMEOUT = 1e3;
2285
2360
  var DEFAULT_SUCCESS_DELAY = 1e3;
2286
2361
  var DEFAULT_NOTARIZE_TIMEOUT = 1e4;
2362
+ var WRITER_NOT_SET_ERROR_CODE = "WRITER_NOT_SET";
2287
2363
  var NotarizationPlugin = class {
2288
2364
  constructor() {
2289
2365
  this._ctx = new import_context5.Context();
2290
- this._extensionOpened = new import_async12.Event();
2366
+ this._extensionOpened = new import_async13.Event();
2291
2367
  this._extensions = /* @__PURE__ */ new Set();
2292
2368
  this._processedCredentials = new import_util4.ComplexSet(import_keys7.PublicKey.hash);
2293
2369
  this._processCredentialsTriggers = new import_util4.ComplexMap(import_keys7.PublicKey.hash);
@@ -2301,23 +2377,23 @@ var NotarizationPlugin = class {
2301
2377
  * Request credentials to be notarized.
2302
2378
  */
2303
2379
  async notarize({ ctx: opCtx, credentials, timeout = DEFAULT_NOTARIZE_TIMEOUT, retryTimeout = DEFAULT_RETRY_TIMEOUT, successDelay = DEFAULT_SUCCESS_DELAY }) {
2304
- (0, import_log9.log)("notarize", {
2380
+ (0, import_log10.log)("notarize", {
2305
2381
  credentials
2306
2382
  }, {
2307
2383
  file: "notarization-plugin.ts",
2308
- line: 85,
2384
+ line: 87,
2309
2385
  scope: this,
2310
2386
  callSite: (f, a) => f(...a)
2311
2387
  });
2312
2388
  (0, import_node_assert9.default)(credentials.every((credential) => credential.id), "Credentials must have an id");
2313
- const errors = new import_async12.Trigger();
2389
+ const errors = new import_async13.Trigger();
2314
2390
  const ctx = this._ctx.derive({
2315
2391
  onError: (err) => {
2316
- import_log9.log.warn("Notarization error", {
2392
+ import_log10.log.warn("Notarization error", {
2317
2393
  err
2318
2394
  }, {
2319
2395
  file: "notarization-plugin.ts",
2320
- line: 94,
2396
+ line: 96,
2321
2397
  scope: this,
2322
2398
  callSite: (f, a) => f(...a)
2323
2399
  });
@@ -2327,23 +2403,23 @@ var NotarizationPlugin = class {
2327
2403
  });
2328
2404
  opCtx == null ? void 0 : opCtx.onDispose(() => ctx.dispose());
2329
2405
  if (timeout !== 0) {
2330
- (0, import_async12.scheduleTask)(ctx, () => {
2331
- import_log9.log.warn("Notarization timeout", {
2406
+ (0, import_async13.scheduleTask)(ctx, () => {
2407
+ import_log10.log.warn("Notarization timeout", {
2332
2408
  timeout,
2333
2409
  peers: Array.from(this._extensions).map((extension) => extension.remotePeerId)
2334
2410
  }, {
2335
2411
  file: "notarization-plugin.ts",
2336
- line: 106,
2412
+ line: 108,
2337
2413
  scope: this,
2338
2414
  callSite: (f, a) => f(...a)
2339
2415
  });
2340
2416
  void ctx.dispose();
2341
- errors.throw(new import_async12.TimeoutError(timeout, "Notarization timed out"));
2417
+ errors.throw(new import_async13.TimeoutError(timeout, "Notarization timed out"));
2342
2418
  }, timeout);
2343
2419
  }
2344
2420
  const allNotarized = Promise.all(credentials.map((credential) => this._waitUntilProcessed(credential.id)));
2345
2421
  const peersTried = /* @__PURE__ */ new Set();
2346
- const notarizeTask = new import_async12.DeferredTask(ctx, async () => {
2422
+ const notarizeTask = new import_async13.DeferredTask(ctx, async () => {
2347
2423
  try {
2348
2424
  if (this._extensions.size === 0) {
2349
2425
  return;
@@ -2352,45 +2428,47 @@ var NotarizationPlugin = class {
2352
2428
  ...this._extensions
2353
2429
  ].find((peer2) => !peersTried.has(peer2));
2354
2430
  if (!peer) {
2355
- import_log9.log.warn("Exhausted all peers to notarize with", {
2431
+ import_log10.log.warn("Exhausted all peers to notarize with", {
2356
2432
  retryIn: retryTimeout
2357
2433
  }, {
2358
2434
  file: "notarization-plugin.ts",
2359
- line: 131,
2435
+ line: 133,
2360
2436
  scope: this,
2361
2437
  callSite: (f, a) => f(...a)
2362
2438
  });
2363
2439
  peersTried.clear();
2364
- (0, import_async12.scheduleTask)(ctx, () => notarizeTask.schedule(), retryTimeout);
2440
+ (0, import_async13.scheduleTask)(ctx, () => notarizeTask.schedule(), retryTimeout);
2365
2441
  return;
2366
2442
  }
2367
2443
  peersTried.add(peer);
2368
- (0, import_log9.log)("try notarizing", {
2444
+ (0, import_log10.log)("try notarizing", {
2369
2445
  peer: peer.localPeerId,
2370
2446
  credentialId: credentials.map((credential) => credential.id)
2371
2447
  }, {
2372
2448
  file: "notarization-plugin.ts",
2373
- line: 138,
2449
+ line: 140,
2374
2450
  scope: this,
2375
2451
  callSite: (f, a) => f(...a)
2376
2452
  });
2377
2453
  await peer.rpc.NotarizationService.notarize({
2378
2454
  credentials: credentials.filter((credential) => !this._processedCredentials.has(credential.id))
2379
2455
  });
2380
- (0, import_log9.log)("success", {}, {
2456
+ (0, import_log10.log)("success", {}, {
2381
2457
  file: "notarization-plugin.ts",
2382
- line: 142,
2458
+ line: 144,
2383
2459
  scope: this,
2384
2460
  callSite: (f, a) => f(...a)
2385
2461
  });
2386
- await (0, import_async12.sleep)(successDelay);
2462
+ await (0, import_async13.sleep)(successDelay);
2387
2463
  } catch (err) {
2388
- import_log9.log.warn("error notarizing (recoverable)", err, {
2389
- file: "notarization-plugin.ts",
2390
- line: 145,
2391
- scope: this,
2392
- callSite: (f, a) => f(...a)
2393
- });
2464
+ if (!ctx.disposed && !err.message.includes(WRITER_NOT_SET_ERROR_CODE)) {
2465
+ import_log10.log.warn("error notarizing (recoverable)", err, {
2466
+ file: "notarization-plugin.ts",
2467
+ line: 148,
2468
+ scope: this,
2469
+ callSite: (f, a) => f(...a)
2470
+ });
2471
+ }
2394
2472
  notarizeTask.schedule();
2395
2473
  }
2396
2474
  });
@@ -2402,9 +2480,9 @@ var NotarizationPlugin = class {
2402
2480
  allNotarized,
2403
2481
  errors.wait()
2404
2482
  ]);
2405
- (0, import_log9.log)("done", {}, {
2483
+ (0, import_log10.log)("done", {}, {
2406
2484
  file: "notarization-plugin.ts",
2407
- line: 155,
2485
+ line: 159,
2408
2486
  scope: this,
2409
2487
  callSite: (f, a) => f(...a)
2410
2488
  });
@@ -2432,7 +2510,7 @@ var NotarizationPlugin = class {
2432
2510
  if (this._processedCredentials.has(id)) {
2433
2511
  return;
2434
2512
  }
2435
- 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();
2436
2514
  }
2437
2515
  /**
2438
2516
  * Requests from other peers to notarize credentials.
@@ -2440,7 +2518,7 @@ var NotarizationPlugin = class {
2440
2518
  async _onNotarize(request) {
2441
2519
  var _a;
2442
2520
  if (!this._writer) {
2443
- throw new Error("Writer not set");
2521
+ throw new Error(WRITER_NOT_SET_ERROR_CODE);
2444
2522
  }
2445
2523
  for (const credential of (_a = request.credentials) != null ? _a : []) {
2446
2524
  (0, import_node_assert9.default)(credential.id, "Credential must have an id");
@@ -2453,11 +2531,11 @@ var NotarizationPlugin = class {
2453
2531
  createExtension() {
2454
2532
  const extension = new NotarizationTeleportExtension({
2455
2533
  onOpen: async () => {
2456
- (0, import_log9.log)("extension opened", {
2534
+ (0, import_log10.log)("extension opened", {
2457
2535
  peer: extension.localPeerId
2458
2536
  }, {
2459
2537
  file: "notarization-plugin.ts",
2460
- line: 204,
2538
+ line: 208,
2461
2539
  scope: this,
2462
2540
  callSite: (f, a) => f(...a)
2463
2541
  });
@@ -2465,11 +2543,11 @@ var NotarizationPlugin = class {
2465
2543
  this._extensionOpened.emit();
2466
2544
  },
2467
2545
  onClose: async () => {
2468
- (0, import_log9.log)("extension closed", {
2546
+ (0, import_log10.log)("extension closed", {
2469
2547
  peer: extension.localPeerId
2470
2548
  }, {
2471
2549
  file: "notarization-plugin.ts",
2472
- line: 209,
2550
+ line: 213,
2473
2551
  scope: this,
2474
2552
  callSite: (f, a) => f(...a)
2475
2553
  });
@@ -2512,7 +2590,7 @@ var NotarizationTeleportExtension = class extends import_teleport2.RpcExtension
2512
2590
  };
2513
2591
 
2514
2592
  // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2515
- var __decorate = function(decorators, target, key, desc) {
2593
+ var __decorate2 = function(decorators, target, key, desc) {
2516
2594
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2517
2595
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2518
2596
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2530,7 +2608,7 @@ var DataSpace = class DataSpace2 {
2530
2608
  * Error for _state === SpaceState.ERROR.
2531
2609
  */
2532
2610
  this.error = void 0;
2533
- this.stateUpdate = new import_async13.Event();
2611
+ this.stateUpdate = new import_async14.Event();
2534
2612
  this.metrics = {};
2535
2613
  var _a;
2536
2614
  this._inner = params.inner;
@@ -2601,13 +2679,13 @@ var DataSpace = class DataSpace2 {
2601
2679
  * Initialize the data pipeline in a separate task.
2602
2680
  */
2603
2681
  initializeDataPipelineAsync() {
2604
- (0, import_async13.scheduleTask)(this._ctx, async () => {
2682
+ (0, import_async14.scheduleTask)(this._ctx, async () => {
2605
2683
  try {
2606
2684
  this.metrics.pipelineInitBegin = new Date();
2607
2685
  await this.initializeDataPipeline();
2608
2686
  } catch (err) {
2609
2687
  if (err instanceof import_errors3.CancelledError) {
2610
- (0, import_log10.log)("Data pipeline initialization cancelled", err, {
2688
+ (0, import_log11.log)("Data pipeline initialization cancelled", err, {
2611
2689
  file: "data-space.ts",
2612
2690
  line: 172,
2613
2691
  scope: this,
@@ -2615,7 +2693,7 @@ var DataSpace = class DataSpace2 {
2615
2693
  });
2616
2694
  return;
2617
2695
  }
2618
- import_log10.log.error("Error initializing data pipeline", err, {
2696
+ import_log11.log.error("Error initializing data pipeline", err, {
2619
2697
  file: "data-space.ts",
2620
2698
  line: 176,
2621
2699
  scope: this,
@@ -2641,7 +2719,7 @@ var DataSpace = class DataSpace2 {
2641
2719
  });
2642
2720
  this.metrics.controlPipelineReady = new Date();
2643
2721
  await this._createWritableFeeds();
2644
- (0, import_log10.log)("Writable feeds created", {}, {
2722
+ (0, import_log11.log)("Writable feeds created", {}, {
2645
2723
  file: "data-space.ts",
2646
2724
  line: 201,
2647
2725
  scope: this,
@@ -2656,7 +2734,7 @@ var DataSpace = class DataSpace2 {
2656
2734
  await this._inner.initializeDataPipeline();
2657
2735
  this.metrics.dataPipelineOpen = new Date();
2658
2736
  await (0, import_context6.cancelWithContext)(this._ctx, this._inner.dataPipeline.ensureEpochInitialized());
2659
- (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", {}, {
2660
2738
  file: "data-space.ts",
2661
2739
  line: 220,
2662
2740
  scope: this,
@@ -2667,7 +2745,7 @@ var DataSpace = class DataSpace2 {
2667
2745
  breakOnStall: false
2668
2746
  });
2669
2747
  this.metrics.dataPipelineReady = new Date();
2670
- (0, import_log10.log)("data pipeline ready", {}, {
2748
+ (0, import_log11.log)("data pipeline ready", {}, {
2671
2749
  file: "data-space.ts",
2672
2750
  line: 229,
2673
2751
  scope: this,
@@ -2743,11 +2821,11 @@ var DataSpace = class DataSpace2 {
2743
2821
  }
2744
2822
  }
2745
2823
  };
2746
- __decorate([
2824
+ __decorate2([
2747
2825
  (0, import_debug3.timed)(1e4)
2748
2826
  ], DataSpace.prototype, "_createWritableFeeds", null);
2749
- DataSpace = __decorate([
2750
- (0, import_async13.trackLeaks)("open", "close")
2827
+ DataSpace = __decorate2([
2828
+ (0, import_async14.trackLeaks)("open", "close")
2751
2829
  ], DataSpace);
2752
2830
 
2753
2831
  // packages/sdk/client-services/src/packlets/spaces/genesis.ts
@@ -2821,7 +2899,7 @@ var spaceGenesis = async (keyring, signingContext, space) => {
2821
2899
  };
2822
2900
 
2823
2901
  // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
2824
- var __decorate2 = function(decorators, target, key, desc) {
2902
+ var __decorate3 = function(decorators, target, key, desc) {
2825
2903
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2826
2904
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2827
2905
  r = Reflect.decorate(decorators, target, key, desc);
@@ -2840,7 +2918,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2840
2918
  this._signingContext = _signingContext;
2841
2919
  this._feedStore = _feedStore;
2842
2920
  this._ctx = new import_context7.Context();
2843
- this.updated = new import_async14.Event();
2921
+ this.updated = new import_async15.Event();
2844
2922
  this._spaces = new import_util6.ComplexMap(import_keys9.PublicKey.hash);
2845
2923
  this._isOpen = false;
2846
2924
  this._instanceId = import_keys9.PublicKey.random().toHex();
@@ -2850,13 +2928,13 @@ var DataSpaceManager = class DataSpaceManager2 {
2850
2928
  return this._spaces;
2851
2929
  }
2852
2930
  async open() {
2853
- (0, import_log11.log)("open", {}, {
2931
+ (0, import_log12.log)("open", {}, {
2854
2932
  file: "data-space-manager.ts",
2855
2933
  line: 80,
2856
2934
  scope: this,
2857
2935
  callSite: (f, a) => f(...a)
2858
2936
  });
2859
- 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({
2860
2938
  id: this._instanceId
2861
2939
  }), {
2862
2940
  file: "data-space-manager.ts",
@@ -2865,7 +2943,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2865
2943
  callSite: (f, a) => f(...a)
2866
2944
  });
2867
2945
  await this._metadataStore.load();
2868
- (0, import_log11.log)("metadata loaded", {
2946
+ (0, import_log12.log)("metadata loaded", {
2869
2947
  spaces: this._metadataStore.spaces.length
2870
2948
  }, {
2871
2949
  file: "data-space-manager.ts",
@@ -2875,7 +2953,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2875
2953
  });
2876
2954
  for (const spaceMetadata of this._metadataStore.spaces) {
2877
2955
  try {
2878
- (0, import_log11.log)("load space", {
2956
+ (0, import_log12.log)("load space", {
2879
2957
  spaceMetadata
2880
2958
  }, {
2881
2959
  file: "data-space-manager.ts",
@@ -2886,7 +2964,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2886
2964
  const space = await this._constructSpace(spaceMetadata);
2887
2965
  space.initializeDataPipelineAsync();
2888
2966
  } catch (err) {
2889
- import_log11.log.error("Error loading space", {
2967
+ import_log12.log.error("Error loading space", {
2890
2968
  spaceMetadata,
2891
2969
  err
2892
2970
  }, {
@@ -2899,7 +2977,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2899
2977
  }
2900
2978
  this._isOpen = true;
2901
2979
  this.updated.emit();
2902
- 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({
2903
2981
  id: this._instanceId
2904
2982
  }), {
2905
2983
  file: "data-space-manager.ts",
@@ -2909,7 +2987,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2909
2987
  });
2910
2988
  }
2911
2989
  async close() {
2912
- (0, import_log11.log)("close", {}, {
2990
+ (0, import_log12.log)("close", {}, {
2913
2991
  file: "data-space-manager.ts",
2914
2992
  line: 102,
2915
2993
  scope: this,
@@ -2935,7 +3013,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2935
3013
  controlFeedKey,
2936
3014
  dataFeedKey
2937
3015
  };
2938
- (0, import_log11.log)("creating space...", {
3016
+ (0, import_log12.log)("creating space...", {
2939
3017
  spaceKey
2940
3018
  }, {
2941
3019
  file: "data-space-manager.ts",
@@ -2955,7 +3033,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2955
3033
  }
2956
3034
  // TODO(burdon): Rename join space.
2957
3035
  async acceptSpace(opts) {
2958
- (0, import_log11.log)("accept space", {
3036
+ (0, import_log12.log)("accept space", {
2959
3037
  opts
2960
3038
  }, {
2961
3039
  file: "data-space-manager.ts",
@@ -2989,7 +3067,7 @@ var DataSpaceManager = class DataSpaceManager2 {
2989
3067
  }));
2990
3068
  }
2991
3069
  async _constructSpace(metadata) {
2992
- (0, import_log11.log)("construct space", {
3070
+ (0, import_log12.log)("construct space", {
2993
3071
  metadata
2994
3072
  }, {
2995
3073
  file: "data-space-manager.ts",
@@ -3027,7 +3105,7 @@ var DataSpaceManager = class DataSpaceManager2 {
3027
3105
  session.addExtension("dxos.mesh.teleport.notarization", dataSpace.notarizationPlugin.createExtension());
3028
3106
  },
3029
3107
  onAuthFailure: () => {
3030
- import_log11.log.warn("auth failure", {}, {
3108
+ import_log12.log.warn("auth failure", {}, {
3031
3109
  file: "data-space-manager.ts",
3032
3110
  line: 212,
3033
3111
  scope: this,
@@ -3048,7 +3126,7 @@ var DataSpaceManager = class DataSpaceManager2 {
3048
3126
  signingContext: this._signingContext,
3049
3127
  callbacks: {
3050
3128
  beforeReady: async () => {
3051
- (0, import_log11.log)("before space ready", {
3129
+ (0, import_log12.log)("before space ready", {
3052
3130
  space: space.key
3053
3131
  }, {
3054
3132
  file: "data-space-manager.ts",
@@ -3059,7 +3137,7 @@ var DataSpaceManager = class DataSpaceManager2 {
3059
3137
  this._dataServiceSubscriptions.registerSpace(space.key, dataSpace.dataPipeline.databaseHost.createDataServiceHost());
3060
3138
  },
3061
3139
  afterReady: async () => {
3062
- (0, import_log11.log)("after space ready", {
3140
+ (0, import_log12.log)("after space ready", {
3063
3141
  space: space.key,
3064
3142
  open: this._isOpen
3065
3143
  }, {
@@ -3086,28 +3164,28 @@ var DataSpaceManager = class DataSpaceManager2 {
3086
3164
  return dataSpace;
3087
3165
  }
3088
3166
  };
3089
- __decorate2([
3090
- import_async14.synchronized
3167
+ __decorate3([
3168
+ import_async15.synchronized
3091
3169
  ], DataSpaceManager.prototype, "open", null);
3092
- __decorate2([
3093
- import_async14.synchronized
3170
+ __decorate3([
3171
+ import_async15.synchronized
3094
3172
  ], DataSpaceManager.prototype, "close", null);
3095
- __decorate2([
3096
- import_async14.synchronized
3173
+ __decorate3([
3174
+ import_async15.synchronized
3097
3175
  ], DataSpaceManager.prototype, "createSpace", null);
3098
- __decorate2([
3099
- import_async14.synchronized
3176
+ __decorate3([
3177
+ import_async15.synchronized
3100
3178
  ], DataSpaceManager.prototype, "acceptSpace", null);
3101
- DataSpaceManager = __decorate2([
3102
- (0, import_async14.trackLeaks)("open", "close")
3179
+ DataSpaceManager = __decorate3([
3180
+ (0, import_async15.trackLeaks)("open", "close")
3103
3181
  ], DataSpaceManager);
3104
3182
 
3105
3183
  // packages/sdk/client-services/src/packlets/spaces/spaces-service.ts
3106
- var import_async15 = require("@dxos/async");
3107
- var import_codec_protobuf11 = require("@dxos/codec-protobuf");
3184
+ var import_async16 = require("@dxos/async");
3185
+ var import_codec_protobuf12 = require("@dxos/codec-protobuf");
3108
3186
  var import_debug5 = require("@dxos/debug");
3109
3187
  var import_echo_pipeline2 = require("@dxos/echo-pipeline");
3110
- var import_log12 = require("@dxos/log");
3188
+ var import_log13 = require("@dxos/log");
3111
3189
  var import_protocols7 = require("@dxos/protocols");
3112
3190
  var import_services9 = require("@dxos/protocols/proto/dxos/client/services");
3113
3191
  var import_util7 = require("@dxos/util");
@@ -3131,15 +3209,15 @@ var SpacesServiceImpl = class {
3131
3209
  (0, import_debug5.todo)();
3132
3210
  }
3133
3211
  querySpaces() {
3134
- return new import_codec_protobuf11.Stream(({ next, ctx }) => {
3212
+ return new import_codec_protobuf12.Stream(({ next, ctx }) => {
3135
3213
  const onUpdate = async () => {
3136
3214
  const dataSpaceManager = await this._getDataSpaceManager();
3137
3215
  const spaces = Array.from(dataSpaceManager.spaces.values()).map((space) => this._transformSpace(space));
3138
- (0, import_log12.log)("update", {
3216
+ (0, import_log13.log)("update", {
3139
3217
  spaces
3140
3218
  }, {
3141
3219
  file: "spaces-service.ts",
3142
- line: 62,
3220
+ line: 59,
3143
3221
  scope: this,
3144
3222
  callSite: (f, a) => f(...a)
3145
3223
  });
@@ -3147,9 +3225,9 @@ var SpacesServiceImpl = class {
3147
3225
  spaces
3148
3226
  });
3149
3227
  };
3150
- (0, import_async15.scheduleTask)(ctx, async () => {
3228
+ (0, import_async16.scheduleTask)(ctx, async () => {
3151
3229
  const dataSpaceManager = await this._getDataSpaceManager();
3152
- const subscriptions = new import_async15.EventSubscriptions();
3230
+ const subscriptions = new import_async16.EventSubscriptions();
3153
3231
  ctx.onDispose(() => subscriptions.clear());
3154
3232
  const subscribeSpaces = () => {
3155
3233
  subscriptions.clear();
@@ -3183,8 +3261,8 @@ var SpacesServiceImpl = class {
3183
3261
  await space.postMessage(getChannelId(channel), message);
3184
3262
  }
3185
3263
  subscribeMessages({ spaceKey, channel }) {
3186
- return new import_codec_protobuf11.Stream(({ ctx, next }) => {
3187
- (0, import_async15.scheduleTask)(ctx, async () => {
3264
+ return new import_codec_protobuf12.Stream(({ ctx, next }) => {
3265
+ (0, import_async16.scheduleTask)(ctx, async () => {
3188
3266
  var _a;
3189
3267
  const dataSpaceManager = await this._getDataSpaceManager();
3190
3268
  const space = (_a = dataSpaceManager.spaces.get(spaceKey)) != null ? _a : (0, import_debug5.raise)(new import_echo_pipeline2.SpaceNotFoundError(spaceKey));
@@ -3196,7 +3274,7 @@ var SpacesServiceImpl = class {
3196
3274
  });
3197
3275
  }
3198
3276
  queryCredentials({ spaceKey }) {
3199
- return new import_codec_protobuf11.Stream(({ ctx, next }) => {
3277
+ return new import_codec_protobuf12.Stream(({ ctx, next }) => {
3200
3278
  var _a;
3201
3279
  const space = (_a = this._spaceManager.spaces.get(spaceKey)) != null ? _a : (0, import_debug5.raise)(new import_echo_pipeline2.SpaceNotFoundError(spaceKey));
3202
3280
  const processor = space.spaceState.registerProcessor({
@@ -3205,7 +3283,7 @@ var SpacesServiceImpl = class {
3205
3283
  }
3206
3284
  });
3207
3285
  ctx.onDispose(() => processor.close());
3208
- (0, import_async15.scheduleTask)(ctx, () => processor.open());
3286
+ (0, import_async16.scheduleTask)(ctx, () => processor.open());
3209
3287
  });
3210
3288
  }
3211
3289
  async writeCredentials({ spaceKey, credentials }) {
@@ -3308,7 +3386,7 @@ var toStorageType = (type) => {
3308
3386
  };
3309
3387
 
3310
3388
  // packages/sdk/client-services/src/packlets/system/system-service.ts
3311
- var import_codec_protobuf12 = require("@dxos/codec-protobuf");
3389
+ var import_codec_protobuf13 = require("@dxos/codec-protobuf");
3312
3390
  var SystemServiceImpl = class {
3313
3391
  constructor({ config, statusUpdate, onUpdateStatus, getCurrentStatus, onReset }) {
3314
3392
  this._config = config;
@@ -3325,7 +3403,7 @@ var SystemServiceImpl = class {
3325
3403
  await this._onUpdateStatus(status);
3326
3404
  }
3327
3405
  queryStatus() {
3328
- return new import_codec_protobuf12.Stream(({ next }) => {
3406
+ return new import_codec_protobuf13.Stream(({ next }) => {
3329
3407
  const update = () => {
3330
3408
  next({
3331
3409
  status: this._getCurrentStatus()
@@ -3345,1225 +3423,1096 @@ var SystemServiceImpl = class {
3345
3423
  }
3346
3424
  };
3347
3425
 
3348
- // 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"));
3349
3428
  var import_async17 = require("@dxos/async");
3350
- var import_client_protocol5 = require("@dxos/client-protocol");
3351
- var import_log13 = require("@dxos/log");
3352
- var import_messaging = require("@dxos/messaging");
3353
- var import_network_manager2 = require("@dxos/network-manager");
3354
- var import_util8 = require("@dxos/util");
3355
-
3356
- // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
3357
- var import_codec_protobuf13 = require("@dxos/codec-protobuf");
3429
+ var import_credentials13 = require("@dxos/credentials");
3358
3430
  var import_debug6 = require("@dxos/debug");
3359
- var import_rpc = require("@dxos/rpc");
3360
- var ClientRpcServer = class {
3361
- constructor(params) {
3362
- this._handlerCache = /* @__PURE__ */ new Map();
3363
- const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
3364
- this._handleCall = handleCall;
3365
- this._handleStream = handleStream;
3366
- this._serviceRegistry = serviceRegistry;
3367
- this._rpcPeer = new import_rpc.RpcPeer({
3368
- ...rpcOptions,
3369
- callHandler: (method, params2) => {
3370
- const [serviceName, methodName] = (0, import_rpc.parseMethodName)(method);
3371
- const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
3372
- if (this._handleCall) {
3373
- return this._handleCall(methodName, params2, handler);
3374
- } else {
3375
- return handler(methodName, params2);
3376
- }
3377
- },
3378
- streamHandler: (method, params2) => {
3379
- const [serviceName, methodName] = (0, import_rpc.parseMethodName)(method);
3380
- const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
3381
- if (this._handleStream) {
3382
- return import_codec_protobuf13.Stream.unwrapPromise(this._handleStream(methodName, params2, handler));
3383
- } else {
3384
- 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
3385
3458
  }
3386
- }
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
3387
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)));
3388
3474
  }
3389
3475
  async open() {
3390
- 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
+ });
3391
3512
  }
3392
3513
  async close() {
3393
- await this._rpcPeer.close();
3394
- }
3395
- _getServiceHandler(serviceName) {
3396
- var _a;
3397
- if (!this._handlerCache.has(serviceName)) {
3398
- 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}`));
3399
- const service = this._serviceRegistry.services[key];
3400
- if (!service) {
3401
- throw new Error(`Service not available: ${serviceName}`);
3402
- }
3403
- this._handlerCache.set(serviceName, descriptor.createServer(service));
3404
- }
3405
- 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
+ });
3406
3535
  }
3407
- };
3408
-
3409
- // packages/sdk/client-services/src/packlets/vault/shell-runtime.ts
3410
- var import_node_assert11 = __toESM(require("node:assert"));
3411
- var import_async16 = require("@dxos/async");
3412
- var import_client_protocol4 = require("@dxos/client-protocol");
3413
- var import_iframe = require("@dxos/protocols/proto/dxos/iframe");
3414
- var import_rpc2 = require("@dxos/rpc");
3415
- var ShellRuntimeImpl = class {
3416
- constructor(_port) {
3417
- this._port = _port;
3418
- this.layoutUpdate = new import_async16.Event();
3419
- 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;
3420
3540
  }
3421
- get layout() {
3422
- 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);
3423
3545
  }
3424
- get invitationCode() {
3425
- return this._invitationCode;
3546
+ async _acceptIdentity(params) {
3547
+ const identity = await this.identityManager.acceptIdentity(params);
3548
+ await this._initialize();
3549
+ return identity;
3426
3550
  }
3427
- get spaceKey() {
3428
- 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
+ }
3429
3556
  }
3430
- setLayout(layout, options = {}) {
3431
- this._layout = layout;
3432
- this._invitationCode = options.invitationCode;
3433
- this._spaceKey = options.spaceKey;
3434
- this.layoutUpdate.emit({
3435
- layout,
3436
- ...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)
3437
3565
  });
3438
- }
3439
- async setAppContext(context) {
3440
- (0, import_node_assert11.default)(this._appRpc, "runtime not open");
3441
- await this._appRpc.rpc.AppService.setContext(context);
3442
- }
3443
- async open() {
3444
- this._appRpc = (0, import_rpc2.createProtoRpcPeer)({
3445
- requested: import_client_protocol4.appServiceBundle,
3446
- exposed: import_client_protocol4.shellServiceBundle,
3447
- handlers: {
3448
- ShellService: {
3449
- setLayout: async (request) => {
3450
- this._layout = request.layout;
3451
- this._invitationCode = request.invitationCode;
3452
- this._spaceKey = request.spaceKey;
3453
- 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
3454
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;
3455
3592
  }
3456
- },
3457
- 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
+ }
3458
3640
  });
3459
- await this._appRpc.open();
3460
- }
3461
- async close() {
3462
- var _a;
3463
- await ((_a = this._appRpc) == null ? void 0 : _a.close());
3464
- this._appRpc = void 0;
3641
+ await this._deviceSpaceSync.open();
3465
3642
  }
3466
3643
  };
3467
- var MemoryShellRuntime = class {
3468
- constructor({ layout, invitationCode, spaceKey } = {}) {
3469
- this.layoutUpdate = new import_async16.Event();
3470
- this.contextUpdate = new import_async16.Event();
3471
- this._layout = layout != null ? layout : import_iframe.ShellLayout.DEFAULT;
3472
- this._invitationCode = invitationCode;
3473
- 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;
3474
3651
  }
3475
- get layout() {
3476
- return this._layout;
3652
+ get descriptors() {
3653
+ return this._serviceBundle;
3477
3654
  }
3478
- get invitationCode() {
3479
- return this._invitationCode;
3655
+ get services() {
3656
+ return this._handlers;
3480
3657
  }
3481
- get spaceKey() {
3482
- return this._spaceKey;
3658
+ setServices(services) {
3659
+ this._handlers = services;
3483
3660
  }
3484
- setLayout(layout, options = {}) {
3485
- this._layout = layout;
3486
- this._invitationCode = options.invitationCode;
3487
- this._spaceKey = options.spaceKey;
3488
- this.layoutUpdate.emit({
3489
- layout,
3490
- ...options
3491
- });
3661
+ addService(name, service) {
3662
+ this._handlers[name] = service;
3492
3663
  }
3493
- async setAppContext(context) {
3494
- this.contextUpdate.emit(context);
3664
+ removeService(name) {
3665
+ delete this._handlers[name];
3495
3666
  }
3496
3667
  };
3497
3668
 
3498
- // packages/sdk/client-services/src/packlets/vault/iframe-host-runtime.ts
3499
- var __decorate3 = function(decorators, target, key, desc) {
3500
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3501
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3502
- r = Reflect.decorate(decorators, target, key, desc);
3503
- else
3504
- for (var i = decorators.length - 1; i >= 0; i--)
3505
- if (d = decorators[i])
3506
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3507
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3508
- };
3509
- var LOCK_KEY = "DXOS_RESOURCE_LOCK";
3510
- var IFrameHostRuntime = class {
3511
- constructor({ config, origin, appPort, shellPort }) {
3512
- this._ready = new import_async17.Trigger();
3513
- this._configProvider = config;
3514
- this.origin = origin;
3515
- this._appPort = appPort;
3516
- this._shellPort = shellPort;
3517
- if (this._shellPort) {
3518
- this._shellRuntime = new ShellRuntimeImpl(this._shellPort);
3519
- }
3520
- }
3521
- get services() {
3522
- return this._clientServices;
3523
- }
3524
- get shell() {
3525
- return this._shellRuntime;
3526
- }
3527
- async start() {
3528
- var _a;
3529
- (0, import_log13.log)("starting...", {}, {
3530
- file: "iframe-host-runtime.ts",
3531
- line: 70,
3532
- scope: this,
3533
- callSite: (f, a) => f(...a)
3534
- });
3535
- try {
3536
- this._config = await (0, import_util8.getAsyncValue)(this._configProvider);
3537
- this._transportFactory = (0, import_network_manager2.createWebRTCTransportFactory)({
3538
- iceServers: this._config.get("runtime.services.ice")
3539
- });
3540
- const signals = this._config.get("runtime.services.signaling");
3541
- this._clientServices = new LocalClientServices({
3542
- lockKey: LOCK_KEY,
3543
- config: this._config,
3544
- signalManager: signals ? new import_messaging.WebsocketSignalManager(signals) : new import_messaging.MemorySignalManager(new import_messaging.MemorySignalManagerContext()),
3545
- transportFactory: this._transportFactory
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
3546
3692
  });
3547
- const middleware = {
3548
- handleCall: async (method, params, handler) => {
3549
- const error = await this._ready.wait({
3550
- timeout: import_client_protocol5.PROXY_CONNECTION_TIMEOUT
3551
- });
3552
- if (error) {
3553
- throw error;
3693
+ }
3694
+ if (lockKey) {
3695
+ this._resourceLock = new Lock({
3696
+ lockKey,
3697
+ onAcquire: () => {
3698
+ if (!this._opening) {
3699
+ void this.open();
3554
3700
  }
3555
- return handler(method, params);
3556
3701
  },
3557
- handleStream: async (method, params, handler) => {
3558
- const error = await this._ready.wait({
3559
- timeout: import_client_protocol5.PROXY_CONNECTION_TIMEOUT
3560
- });
3561
- if (error) {
3562
- throw error;
3563
- }
3564
- return handler(method, params);
3565
- }
3566
- };
3567
- this._clientRpc = new ClientRpcServer({
3568
- serviceRegistry: this._clientServices.host.serviceRegistry,
3569
- port: this._appPort,
3570
- ...middleware
3702
+ onRelease: () => this.close()
3571
3703
  });
3572
- await Promise.all([
3573
- this._clientServices.open(),
3574
- this._clientRpc.open(),
3575
- (_a = this._shellRuntime) == null ? void 0 : _a.open()
3576
- ]);
3577
- this._ready.wake(void 0);
3578
- (0, import_log13.log)("started", {}, {
3579
- file: "iframe-host-runtime.ts",
3580
- line: 113,
3581
- scope: this,
3582
- callSite: (f, a) => f(...a)
3583
- });
3584
- } catch (err) {
3585
- this._ready.wake(err);
3586
- import_log13.log.catch(err, {}, {
3587
- file: "iframe-host-runtime.ts",
3588
- line: 116,
3589
- scope: this,
3590
- callSite: (f, a) => f(...a)
3591
- });
3592
- }
3593
- }
3594
- async stop() {
3595
- var _a;
3596
- (0, import_log13.log)("stopping...", {}, {
3597
- file: "iframe-host-runtime.ts",
3598
- line: 121,
3599
- scope: this,
3600
- callSite: (f, a) => f(...a)
3601
- });
3602
- await this._clientRpc.close();
3603
- await this._clientServices.close();
3604
- await ((_a = this._shellRuntime) == null ? void 0 : _a.close());
3605
- (0, import_log13.log)("stopped", {}, {
3606
- file: "iframe-host-runtime.ts",
3607
- line: 125,
3608
- scope: this,
3609
- callSite: (f, a) => f(...a)
3610
- });
3611
- }
3612
- };
3613
- __decorate3([
3614
- import_log13.logInfo
3615
- ], IFrameHostRuntime.prototype, "origin", void 0);
3616
-
3617
- // packages/sdk/client-services/src/packlets/vault/iframe-proxy-runtime.ts
3618
- var import_async18 = require("@dxos/async");
3619
- var import_client_protocol6 = require("@dxos/client-protocol");
3620
- var import_errors5 = require("@dxos/errors");
3621
- var import_log14 = require("@dxos/log");
3622
- var import_network_manager3 = require("@dxos/network-manager");
3623
- var import_rpc3 = require("@dxos/rpc");
3624
- var import_util9 = require("@dxos/util");
3625
- var IFrameProxyRuntime = class {
3626
- constructor({ config, systemPort, shellPort }) {
3627
- this._id = String(Math.floor(Math.random() * 1e6));
3628
- this._release = new import_async18.Trigger();
3629
- this._configProvider = config;
3630
- this._systemPort = systemPort;
3631
- this._shellPort = shellPort;
3632
- if (this._shellPort) {
3633
- this._shellRuntime = new ShellRuntimeImpl(this._shellPort);
3634
3704
  }
3635
- }
3636
- get shell() {
3637
- return this._shellRuntime;
3638
- }
3639
- async open(origin) {
3640
- var _a;
3641
- this._config = await (0, import_util9.getAsyncValue)(this._configProvider);
3642
- this._transportService = new import_network_manager3.WebRTCTransportService({
3643
- iceServers: this._config.get("runtime.services.ice")
3644
- });
3645
- this._systemRpc = (0, import_rpc3.createProtoRpcPeer)({
3646
- requested: import_client_protocol6.workerServiceBundle,
3647
- exposed: import_client_protocol6.iframeServiceBundle,
3648
- handlers: {
3649
- BridgeService: this._transportService
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
+ }
3650
3716
  },
3651
- port: this._systemPort,
3652
- timeout: 200
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
3653
3724
  });
3654
- let lockKey;
3655
- if (typeof navigator !== "undefined") {
3656
- lockKey = this._lockKey(origin);
3657
- this._release = new import_async18.Trigger();
3658
- const ready = new import_async18.Trigger();
3659
- void navigator.locks.request(lockKey, async () => {
3660
- ready.wake();
3661
- await this._release.wait();
3662
- });
3663
- await ready.wait();
3664
- }
3665
- try {
3666
- await this._systemRpc.open();
3667
- await this._systemRpc.rpc.WorkerService.start({
3668
- origin,
3669
- lockKey
3670
- });
3671
- } catch (err) {
3672
- import_log14.log.catch(err, {}, {
3673
- file: "iframe-proxy-runtime.ts",
3674
- line: 85,
3675
- scope: this,
3676
- callSite: (f, a) => f(...a)
3677
- });
3678
- throw new import_errors5.RemoteServiceConnectionError("Failed to connect to worker");
3679
- }
3680
- await ((_a = this._shellRuntime) == null ? void 0 : _a.open());
3681
3725
  }
3682
- async close() {
3683
- var _a;
3684
- this._release.wake();
3685
- await ((_a = this._shellRuntime) == null ? void 0 : _a.close());
3686
- await this._systemRpc.rpc.WorkerService.stop();
3687
- await this._systemRpc.close();
3726
+ get isOpen() {
3727
+ return this._open;
3688
3728
  }
3689
- _lockKey(origin) {
3690
- return `${origin}-${this._id}`;
3729
+ get serviceRegistry() {
3730
+ return this._serviceRegistry;
3691
3731
  }
3692
- };
3693
-
3694
- // packages/sdk/client-services/src/packlets/vault/vault-resource-lock.ts
3695
- var import_async19 = require("@dxos/async");
3696
- var import_client_protocol7 = require("@dxos/client-protocol");
3697
- var import_log15 = require("@dxos/log");
3698
- var __decorate4 = function(decorators, target, key, desc) {
3699
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3700
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3701
- r = Reflect.decorate(decorators, target, key, desc);
3702
- else
3703
- for (var i = decorators.length - 1; i >= 0; i--)
3704
- if (d = decorators[i])
3705
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3706
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3707
- };
3708
- var Message;
3709
- (function(Message2) {
3710
- Message2["ACQUIRING"] = "acquiring";
3711
- })(Message || (Message = {}));
3712
- var VaultResourceLock = class {
3713
- constructor({ lockKey, onAcquire, onRelease }) {
3714
- this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
3715
- this._releaseTrigger = new import_async19.Trigger();
3716
- this._lockKey = lockKey;
3717
- this._onAcquire = onAcquire;
3718
- this._onRelease = onRelease;
3719
- this._broadcastChannel.onmessage = this._onMessage.bind(this);
3732
+ get descriptors() {
3733
+ return this._serviceRegistry.descriptors;
3720
3734
  }
3721
- get lockKey() {
3722
- return this._lockKey;
3735
+ get services() {
3736
+ return this._serviceRegistry.services;
3723
3737
  }
3724
- async acquire() {
3725
- this._broadcastChannel.postMessage({
3726
- message: Message.ACQUIRING
3727
- });
3728
- try {
3729
- (0, import_log15.log)("aquiring lock...", {}, {
3730
- file: "vault-resource-lock.ts",
3731
- line: 45,
3732
- scope: this,
3733
- callSite: (f, a) => f(...a)
3734
- });
3735
- await (0, import_async19.asyncTimeout)(this._requestLock(), import_client_protocol7.RESOURCE_LOCK_TIMEOUT);
3736
- (0, import_log15.log)("acquired lock", {}, {
3737
- file: "vault-resource-lock.ts",
3738
- line: 47,
3739
- scope: this,
3740
- callSite: (f, a) => f(...a)
3741
- });
3742
- } catch (e) {
3743
- (0, import_log15.log)("stealing lock...", {}, {
3744
- file: "vault-resource-lock.ts",
3745
- line: 49,
3746
- scope: this,
3747
- callSite: (f, a) => f(...a)
3748
- });
3749
- await this._requestLock(true);
3750
- (0, import_log15.log)("stolen lock", {}, {
3751
- file: "vault-resource-lock.ts",
3752
- line: 51,
3753
- scope: this,
3754
- callSite: (f, a) => f(...a)
3755
- });
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
+ }
3756
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
+ });
3757
3763
  }
3758
- async release() {
3759
- this._releaseTrigger.wake();
3760
- }
3761
- _onMessage(event) {
3762
- if (event.data.message === Message.ACQUIRING) {
3763
- this._releaseTrigger.wake();
3764
+ async open() {
3765
+ var _a, _b, _c;
3766
+ if (this._open) {
3767
+ return;
3764
3768
  }
3765
- }
3766
- async _requestLock(steal = false) {
3767
- (0, import_log15.log)("requesting lock...", {
3768
- steal
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,
3775
+ scope: this,
3776
+ callSite: (f, a) => f(...a)
3777
+ });
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
3769
3785
  }, {
3770
- file: "vault-resource-lock.ts",
3771
- line: 66,
3786
+ file: "service-host.ts",
3787
+ line: 195,
3772
3788
  scope: this,
3773
3789
  callSite: (f, a) => f(...a)
3774
3790
  });
3775
- const acquired = new import_async19.Trigger();
3776
- void navigator.locks.request(this._lockKey, {
3777
- steal
3778
- }, async () => {
3779
- var _a, _b;
3780
- await ((_a = this._onAcquire) == null ? void 0 : _a.call(this));
3781
- acquired.wake();
3782
- this._releaseTrigger = new import_async19.Trigger();
3783
- await this._releaseTrigger.wait();
3784
- (0, import_log15.log)("releasing lock...", {}, {
3785
- file: "vault-resource-lock.ts",
3786
- line: 75,
3787
- scope: this,
3788
- callSite: (f, a) => f(...a)
3789
- });
3790
- await ((_b = this._onRelease) == null ? void 0 : _b.call(this));
3791
- (0, import_log15.log)("released lock", {}, {
3792
- file: "vault-resource-lock.ts",
3793
- line: 77,
3794
- scope: this,
3795
- callSite: (f, a) => f(...a)
3796
- });
3797
- }).catch(async () => {
3798
- var _a;
3799
- await ((_a = this._onRelease) == null ? void 0 : _a.call(this));
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
+ })
3800
3812
  });
3801
- await acquired.wait();
3802
- (0, import_log15.log)("recieved lock", {
3803
- steal
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
3804
3820
  }, {
3805
- file: "vault-resource-lock.ts",
3806
- line: 84,
3821
+ file: "service-host.ts",
3822
+ line: 250,
3823
+ scope: this,
3824
+ callSite: (f, a) => f(...a)
3825
+ });
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,
3807
3831
  scope: this,
3808
3832
  callSite: (f, a) => f(...a)
3809
3833
  });
3810
3834
  }
3811
- };
3812
- __decorate4([
3813
- import_log15.logInfo
3814
- ], VaultResourceLock.prototype, "lockKey", null);
3815
-
3816
- // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
3817
- var import_async21 = require("@dxos/async");
3818
- var import_log17 = require("@dxos/log");
3819
- var import_messaging2 = require("@dxos/messaging");
3820
- var import_network_manager4 = require("@dxos/network-manager");
3821
-
3822
- // packages/sdk/client-services/src/packlets/vault/worker-session.ts
3823
- var import_node_assert12 = __toESM(require("node:assert"));
3824
- var import_async20 = require("@dxos/async");
3825
- var import_client_protocol8 = require("@dxos/client-protocol");
3826
- var import_log16 = require("@dxos/log");
3827
- var import_rpc4 = require("@dxos/rpc");
3828
- var import_util10 = require("@dxos/util");
3829
- var __decorate5 = function(decorators, target, key, desc) {
3830
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3831
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3832
- r = Reflect.decorate(decorators, target, key, desc);
3833
- else
3834
- for (var i = decorators.length - 1; i >= 0; i--)
3835
- if (d = decorators[i])
3836
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3837
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3838
- };
3839
- var WorkerSession = class {
3840
- constructor({ serviceHost, systemPort, appPort, shellPort, readySignal }) {
3841
- this._startTrigger = new import_async20.Trigger();
3842
- this.onClose = new import_util10.Callback();
3843
- (0, import_node_assert12.default)(serviceHost);
3844
- this._serviceHost = serviceHost;
3845
- const middleware = {
3846
- handleCall: async (method, params, handler) => {
3847
- const error = await readySignal.wait({
3848
- timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
3849
- });
3850
- if (error) {
3851
- throw error;
3852
- }
3853
- return handler(method, params);
3854
- },
3855
- handleStream: async (method, params, handler) => {
3856
- const error = await readySignal.wait({
3857
- timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
3858
- });
3859
- if (error) {
3860
- throw error;
3861
- }
3862
- return handler(method, params);
3863
- }
3864
- };
3865
- this._clientRpc = new ClientRpcServer({
3866
- serviceRegistry: this._serviceHost.serviceRegistry,
3867
- port: appPort,
3868
- ...middleware
3869
- });
3870
- this._shellClientRpc = new ClientRpcServer({
3871
- serviceRegistry: this._serviceHost.serviceRegistry,
3872
- port: shellPort,
3873
- ...middleware
3874
- });
3875
- this._iframeRpc = (0, import_rpc4.createProtoRpcPeer)({
3876
- requested: import_client_protocol8.iframeServiceBundle,
3877
- exposed: import_client_protocol8.workerServiceBundle,
3878
- handlers: {
3879
- WorkerService: {
3880
- start: async (request) => {
3881
- this.origin = request.origin;
3882
- this.lockKey = request.lockKey;
3883
- this._startTrigger.wake();
3884
- },
3885
- stop: async () => {
3886
- setTimeout(async () => {
3887
- try {
3888
- await this.close();
3889
- } catch (err) {
3890
- import_log16.log.catch(err, {}, {
3891
- file: "worker-session.ts",
3892
- line: 100,
3893
- scope: this,
3894
- callSite: (f, a) => f(...a)
3895
- });
3896
- }
3897
- });
3898
- }
3899
- }
3900
- },
3901
- port: systemPort,
3902
- timeout: 1e3
3903
- });
3904
- this.bridgeService = this._iframeRpc.rpc.BridgeService;
3905
- }
3906
- async open() {
3907
- import_log16.log.info("opening..", {}, {
3908
- file: "worker-session.ts",
3909
- line: 114,
3835
+ async close() {
3836
+ var _a;
3837
+ if (!this._open) {
3838
+ return;
3839
+ }
3840
+ const deviceKey = (_a = this._serviceContext.identityManager.identity) == null ? void 0 : _a.deviceKey;
3841
+ (0, import_log15.log)("closing...", {
3842
+ deviceKey
3843
+ }, {
3844
+ file: "service-host.ts",
3845
+ line: 260,
3910
3846
  scope: this,
3911
3847
  callSite: (f, a) => f(...a)
3912
3848
  });
3913
- await Promise.all([
3914
- this._clientRpc.open(),
3915
- this._iframeRpc.open(),
3916
- this._maybeOpenShell()
3917
- ]);
3918
- await this._startTrigger.wait({
3919
- timeout: import_client_protocol8.PROXY_CONNECTION_TIMEOUT
3849
+ this._serviceRegistry.setServices({
3850
+ SystemService: this._systemService
3920
3851
  });
3921
- if (this.lockKey) {
3922
- void this._afterLockReleases(this.lockKey, () => this.close());
3923
- }
3924
- }
3925
- async close() {
3926
- import_log16.log.info("closing..", {}, {
3927
- file: "worker-session.ts",
3928
- line: 124,
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
3858
+ }, {
3859
+ file: "service-host.ts",
3860
+ line: 266,
3929
3861
  scope: this,
3930
3862
  callSite: (f, a) => f(...a)
3931
3863
  });
3932
- try {
3933
- await this.onClose.callIfSet();
3934
- } catch (err) {
3935
- import_log16.log.catch(err, {}, {
3936
- file: "worker-session.ts",
3937
- line: 128,
3938
- scope: this,
3939
- callSite: (f, a) => f(...a)
3940
- });
3941
- }
3942
- await Promise.all([
3943
- this._clientRpc.close(),
3944
- this._iframeRpc.close()
3945
- ]);
3946
- }
3947
- async _maybeOpenShell() {
3948
- try {
3949
- await (0, import_async20.asyncTimeout)(this._shellClientRpc.open(), 1e3);
3950
- } catch (e) {
3951
- import_log16.log.info("No shell connected.", {}, {
3952
- file: "worker-session.ts",
3953
- line: 138,
3954
- scope: this,
3955
- callSite: (f, a) => f(...a)
3956
- });
3957
- }
3958
- }
3959
- _afterLockReleases(lockKey, callback) {
3960
- return navigator.locks.request(lockKey, () => {
3961
- }).then(callback);
3962
- }
3963
- };
3964
- __decorate5([
3965
- import_log16.logInfo
3966
- ], WorkerSession.prototype, "origin", void 0);
3967
- __decorate5([
3968
- import_log16.logInfo
3969
- ], WorkerSession.prototype, "lockKey", void 0);
3970
-
3971
- // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
3972
- var WorkerRuntime = class {
3973
- // prettier-ignore
3974
- constructor(_configProvider) {
3975
- this._configProvider = _configProvider;
3976
- this._transportFactory = new import_network_manager4.WebRTCTransportProxyFactory();
3977
- this._ready = new import_async21.Trigger();
3978
- this.sessions = /* @__PURE__ */ new Set();
3979
- this._clientServices = new ClientServicesHost();
3980
- }
3981
- get host() {
3982
- return this._clientServices;
3983
3864
  }
3984
- async start() {
3985
- (0, import_log17.log)("starting...", {}, {
3986
- file: "worker-runtime.ts",
3987
- line: 48,
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,
3988
3873
  scope: this,
3989
3874
  callSite: (f, a) => f(...a)
3990
3875
  });
3991
- try {
3992
- this._config = await this._configProvider();
3993
- const signals = this._config.get("runtime.services.signaling");
3994
- this._clientServices.initialize({
3995
- config: this._config,
3996
- signalManager: signals ? new import_messaging2.WebsocketSignalManager(signals) : new import_messaging2.MemorySignalManager(new import_messaging2.MemorySignalManagerContext()),
3997
- transportFactory: this._transportFactory
3998
- });
3999
- await this._clientServices.open();
4000
- this._ready.wake(void 0);
4001
- (0, import_log17.log)("started", {}, {
4002
- file: "worker-runtime.ts",
4003
- line: 62,
4004
- scope: this,
4005
- callSite: (f, a) => f(...a)
4006
- });
4007
- } catch (err) {
4008
- this._ready.wake(err);
4009
- import_log17.log.catch(err, {}, {
4010
- file: "worker-runtime.ts",
4011
- line: 65,
4012
- scope: this,
4013
- callSite: (f, a) => f(...a)
4014
- });
4015
- }
4016
- }
4017
- async stop() {
4018
- await this._clientServices.close();
4019
- }
4020
- /**
4021
- * Create a new session.
4022
- */
4023
- async createSession({ appPort, systemPort, shellPort }) {
4024
- const session = new WorkerSession({
4025
- serviceHost: this._clientServices,
4026
- appPort,
4027
- systemPort,
4028
- shellPort,
4029
- readySignal: this._ready
3876
+ (0, import_log15.log)("resetting...", {}, {
3877
+ file: "service-host.ts",
3878
+ line: 273,
3879
+ scope: this,
3880
+ callSite: (f, a) => f(...a)
4030
3881
  });
4031
- session.onClose.set(async () => {
4032
- this.sessions.delete(session);
4033
- this._reconnectWebrtc();
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)
4034
3889
  });
4035
- await session.open();
4036
- this.sessions.add(session);
4037
- this._reconnectWebrtc();
4038
- }
4039
- /**
4040
- * Selects one of the existing session fro WebRTC networking.
4041
- */
4042
- _reconnectWebrtc() {
4043
- (0, import_log17.log)("reconnecting webrtc...", {}, {
4044
- file: "worker-runtime.ts",
4045
- line: 102,
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,
4046
3895
  scope: this,
4047
3896
  callSite: (f, a) => f(...a)
4048
3897
  });
4049
- if (this._sessionForNetworking) {
4050
- if (!this.sessions.has(this._sessionForNetworking)) {
4051
- this._sessionForNetworking = void 0;
4052
- }
4053
- }
4054
- if (!this._sessionForNetworking) {
4055
- const selected = Array.from(this.sessions).find((session) => session.bridgeService);
4056
- if (selected) {
4057
- this._sessionForNetworking = selected;
4058
- this._transportFactory.setBridgeService(selected.bridgeService);
4059
- } else {
4060
- this._transportFactory.setBridgeService(void 0);
4061
- }
4062
- }
4063
3898
  }
4064
3899
  };
4065
3900
 
4066
- // packages/sdk/client-services/src/packlets/services/service-context.ts
4067
- var import_node_assert13 = __toESM(require("node:assert"));
4068
- var import_async22 = require("@dxos/async");
4069
- var import_credentials13 = require("@dxos/credentials");
4070
- var import_debug7 = require("@dxos/debug");
4071
- var import_echo_pipeline3 = require("@dxos/echo-pipeline");
4072
- var import_feed_store4 = require("@dxos/feed-store");
4073
- var import_keyring = require("@dxos/keyring");
4074
- var import_keys10 = require("@dxos/keys");
4075
- var import_log18 = require("@dxos/log");
4076
- var import_protocols8 = require("@dxos/protocols");
4077
- var import_services12 = require("@dxos/protocols/proto/dxos/client/services");
4078
- var ServiceContext = class {
4079
- // prettier-ignore
4080
- constructor(storage, networkManager, signalManager, modelFactory) {
4081
- this.storage = storage;
4082
- this.networkManager = networkManager;
4083
- this.signalManager = signalManager;
4084
- this.modelFactory = modelFactory;
4085
- this.initialized = new import_async22.Trigger();
4086
- this.dataServiceSubscriptions = new import_echo_pipeline3.DataServiceSubscriptions();
4087
- this._handlerFactories = /* @__PURE__ */ new Map();
4088
- this._instanceId = import_keys10.PublicKey.random().toHex();
4089
- this.metadataStore = new import_echo_pipeline3.MetadataStore(storage.createDirectory("metadata"));
4090
- this.snapshotStore = new import_echo_pipeline3.SnapshotStore(storage.createDirectory("snapshots"));
4091
- this.keyring = new import_keyring.Keyring(storage.createDirectory("keyring"));
4092
- this.feedStore = new import_feed_store4.FeedStore({
4093
- factory: new import_feed_store4.FeedFactory({
4094
- root: storage.createDirectory("feeds"),
4095
- signer: this.keyring,
4096
- hypercore: {
4097
- valueEncoding: import_echo_pipeline3.valueEncoding
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);
3905
+ }
3906
+ get descriptors() {
3907
+ return this._host.descriptors;
3908
+ }
3909
+ get services() {
3910
+ return this._host.services;
3911
+ }
3912
+ get host() {
3913
+ return this._host;
3914
+ }
3915
+ async open() {
3916
+ await this._host.open();
3917
+ }
3918
+ async close() {
3919
+ await this._host.close();
3920
+ }
3921
+ };
3922
+
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");
3933
+ var import_debug7 = require("@dxos/debug");
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);
4098
3951
  }
4099
- })
4100
- });
4101
- this.spaceManager = new import_echo_pipeline3.SpaceManager({
4102
- feedStore: this.feedStore,
4103
- networkManager: this.networkManager,
4104
- metadataStore: this.metadataStore,
4105
- modelFactory: this.modelFactory,
4106
- 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
+ }
4107
3962
  });
4108
- this.identityManager = new IdentityManager(this.metadataStore, this.keyring, this.feedStore, this.spaceManager);
4109
- this.invitations = new InvitationsHandler(this.networkManager);
4110
- this._handlerFactories.set(import_services12.Invitation.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => {
4111
- var _a;
4112
- return (_a = this.identityManager.identity) != null ? _a : (0, import_debug7.failUndefined)();
4113
- }, this._acceptIdentity.bind(this)));
4114
3963
  }
4115
3964
  async open() {
4116
- import_log18.log.trace("dxos.sdk.service-context.open", import_protocols8.trace.begin({
4117
- id: this._instanceId
4118
- }), {
4119
- file: "service-context.ts",
4120
- line: 119,
4121
- scope: this,
4122
- callSite: (f, a) => f(...a)
4123
- });
4124
- await this._checkStorageVersion();
4125
- (0, import_log18.log)("opening...", {}, {
4126
- file: "service-context.ts",
4127
- line: 123,
4128
- scope: this,
4129
- callSite: (f, a) => f(...a)
4130
- });
4131
- await this.signalManager.open();
4132
- await this.networkManager.open();
4133
- await this.spaceManager.open();
4134
- await this.identityManager.open();
4135
- if (this.identityManager.identity) {
4136
- 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));
4137
3979
  }
4138
- (0, import_log18.log)("opened", {}, {
4139
- file: "service-context.ts",
4140
- line: 131,
4141
- scope: this,
4142
- 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
4143
4012
  });
4144
- import_log18.log.trace("dxos.sdk.service-context.open", import_protocols8.trace.end({
4145
- id: this._instanceId
4146
- }), {
4147
- file: "service-context.ts",
4148
- line: 132,
4149
- scope: this,
4150
- 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
4151
4033
  });
4034
+ await this._appRpc.open();
4152
4035
  }
4153
4036
  async close() {
4154
- var _a, _b;
4155
- (0, import_log18.log)("closing...", {}, {
4156
- file: "service-context.ts",
4157
- line: 136,
4158
- scope: this,
4159
- callSite: (f, a) => f(...a)
4160
- });
4161
- await ((_a = this._deviceSpaceSync) == null ? void 0 : _a.close());
4162
- await ((_b = this.dataSpaceManager) == null ? void 0 : _b.close());
4163
- await this.identityManager.close();
4164
- await this.spaceManager.close();
4165
- await this.feedStore.close();
4166
- await this.networkManager.close();
4167
- await this.signalManager.close();
4168
- this.dataServiceSubscriptions.clear();
4169
- (0, import_log18.log)("closed", {}, {
4170
- file: "service-context.ts",
4171
- line: 145,
4172
- scope: this,
4173
- callSite: (f, a) => f(...a)
4174
- });
4037
+ var _a;
4038
+ await ((_a = this._appRpc) == null ? void 0 : _a.close());
4039
+ this._appRpc = void 0;
4175
4040
  }
4176
- async createIdentity(params = {}) {
4177
- const identity = await this.identityManager.createIdentity(params);
4178
- await this._initialize();
4179
- 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;
4180
4049
  }
4181
- getInvitationHandler(invitation) {
4182
- const factory = this._handlerFactories.get(invitation.kind);
4183
- (0, import_node_assert13.default)(factory, `Unknown invitation kind: ${invitation.kind}`);
4184
- return factory(invitation);
4050
+ get layout() {
4051
+ return this._layout;
4185
4052
  }
4186
- async _acceptIdentity(params) {
4187
- const identity = await this.identityManager.acceptIdentity(params);
4188
- await this._initialize();
4189
- return identity;
4053
+ get invitationCode() {
4054
+ return this._invitationCode;
4190
4055
  }
4191
- async _checkStorageVersion() {
4192
- await this.metadataStore.load();
4193
- if (this.metadataStore.version !== import_protocols8.STORAGE_VERSION) {
4194
- import_log18.log.error("Invalid storage version", {
4195
- current: this.metadataStore.version,
4196
- expected: import_protocols8.STORAGE_VERSION
4197
- }, {
4198
- file: "service-context.ts",
4199
- line: 171,
4200
- scope: this,
4201
- callSite: (f, a) => f(...a)
4202
- });
4203
- await this.metadataStore.clear();
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);
4204
4094
  }
4205
4095
  }
4206
- // Called when identity is created.
4207
- async _initialize() {
4096
+ get services() {
4097
+ return this._clientServices;
4098
+ }
4099
+ get shell() {
4100
+ return this._shellRuntime;
4101
+ }
4102
+ async start() {
4208
4103
  var _a;
4209
- (0, import_log18.log)("initializing spaces...", {}, {
4210
- file: "service-context.ts",
4211
- line: 179,
4104
+ (0, import_log16.log)("starting...", {}, {
4105
+ file: "iframe-host-runtime.ts",
4106
+ line: 70,
4212
4107
  scope: this,
4213
4108
  callSite: (f, a) => f(...a)
4214
4109
  });
4215
- const identity = (_a = this.identityManager.identity) != null ? _a : (0, import_debug7.failUndefined)();
4216
- const signingContext = {
4217
- credentialSigner: identity.getIdentityCredentialSigner(),
4218
- identityKey: identity.identityKey,
4219
- deviceKey: identity.deviceKey,
4220
- profile: identity.profileDocument,
4221
- recordCredential: async (credential) => {
4222
- await identity.controlPipeline.writer.write({
4223
- credential: {
4224
- credential
4225
- }
4226
- });
4227
- }
4228
- };
4229
- this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.dataServiceSubscriptions, this.keyring, signingContext, this.feedStore);
4230
- await this.dataSpaceManager.open();
4231
- this._handlerFactories.set(import_services12.Invitation.Kind.SPACE, (invitation) => {
4232
- (0, import_node_assert13.default)(this.dataSpaceManager, "dataSpaceManager not initialized yet");
4233
- return new SpaceInvitationProtocol(this.dataSpaceManager, signingContext, this.keyring, invitation.spaceKey);
4234
- });
4235
- this.initialized.wake();
4236
- this._deviceSpaceSync = identity.space.spaceState.registerProcessor({
4237
- process: async (credential) => {
4238
- const assertion = (0, import_credentials13.getCredentialAssertion)(credential);
4239
- if (assertion["@type"] !== "dxos.halo.credentials.SpaceMember") {
4240
- return;
4241
- }
4242
- if (assertion.spaceKey.equals(identity.space.key)) {
4243
- return;
4244
- }
4245
- if (!this.dataSpaceManager) {
4246
- (0, import_log18.log)("dataSpaceManager not initialized yet, ignoring space admission", {
4247
- details: assertion
4248
- }, {
4249
- file: "service-context.ts",
4250
- line: 218,
4251
- scope: this,
4252
- callSite: (f, a) => f(...a)
4253
- });
4254
- return;
4255
- }
4256
- if (this.dataSpaceManager.spaces.has(assertion.spaceKey)) {
4257
- (0, import_log18.log)("space already exists, ignoring space admission", {
4258
- details: assertion
4259
- }, {
4260
- file: "service-context.ts",
4261
- line: 222,
4262
- scope: this,
4263
- callSite: (f, a) => f(...a)
4264
- });
4265
- return;
4266
- }
4267
- try {
4268
- (0, import_log18.log)("accepting space recorded in halo", {
4269
- details: assertion
4270
- }, {
4271
- file: "service-context.ts",
4272
- line: 227,
4273
- scope: this,
4274
- callSite: (f, a) => f(...a)
4275
- });
4276
- await this.dataSpaceManager.acceptSpace({
4277
- spaceKey: assertion.spaceKey,
4278
- 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
4279
4126
  });
4280
- } catch (err) {
4281
- import_log18.log.catch(err, {}, {
4282
- file: "service-context.ts",
4283
- line: 233,
4284
- scope: this,
4285
- 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
4286
4135
  });
4136
+ if (error) {
4137
+ throw error;
4138
+ }
4139
+ return handler(method, params);
4287
4140
  }
4288
- }
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)
4289
4185
  });
4290
- await this._deviceSpaceSync.open();
4291
4186
  }
4292
4187
  };
4188
+ __decorate4([
4189
+ import_log16.logInfo
4190
+ ], IFrameHostRuntime.prototype, "origin", void 0);
4293
4191
 
4294
- // packages/sdk/client-services/src/packlets/services/service-registry.ts
4295
- var ServiceRegistry = class {
4296
- // prettier-ignore
4297
- constructor(_serviceBundle, _handlers = {}) {
4298
- this._serviceBundle = _serviceBundle;
4299
- this._handlers = _handlers;
4300
- }
4301
- get descriptors() {
4302
- 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
+ }
4303
4210
  }
4304
- get services() {
4305
- return this._handlers;
4211
+ get shell() {
4212
+ return this._shellRuntime;
4306
4213
  }
4307
- setServices(services) {
4308
- 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());
4309
4256
  }
4310
- addService(name, service) {
4311
- 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();
4312
4263
  }
4313
- removeService(name) {
4314
- delete this._handlers[name];
4264
+ _lockKey(origin) {
4265
+ return `${origin}-${this._id}`;
4315
4266
  }
4316
4267
  };
4317
4268
 
4318
- // packages/sdk/client-services/src/packlets/services/service-host.ts
4319
- var ClientServicesHost = class {
4320
- constructor({
4321
- config,
4322
- modelFactory = (0, import_client_protocol9.createDefaultModelFactory)(),
4323
- // TODO(burdon): Create ApolloLink abstraction (see Client).
4324
- transportFactory,
4325
- signalManager,
4326
- connectionLog,
4327
- storage,
4328
- // TODO(wittjosiah): Turn this on by default.
4329
- lockKey
4330
- } = {}) {
4331
- this._statusUpdate = new import_async23.Event();
4332
- this._opening = false;
4333
- this._open = false;
4334
- this._storage = storage;
4335
- this._modelFactory = modelFactory;
4336
- if (config) {
4337
- this.initialize({
4338
- config,
4339
- transportFactory,
4340
- signalManager
4341
- });
4342
- }
4343
- this._resourceLock = lockKey ? new VaultResourceLock({
4344
- lockKey,
4345
- onAcquire: () => {
4346
- if (!this._opening) {
4347
- 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;
4348
4305
  }
4306
+ return handler(method, params);
4349
4307
  },
4350
- onRelease: () => this.close()
4351
- }) : void 0;
4352
- this._systemService = new SystemServiceImpl({
4353
- config: this._config,
4354
- statusUpdate: this._statusUpdate,
4355
- getCurrentStatus: () => this.isOpen ? import_services13.SystemStatus.ACTIVE : import_services13.SystemStatus.INACTIVE,
4356
- onUpdateStatus: async (status) => {
4357
- var _a, _b;
4358
- if (!this.isOpen && status === import_services13.SystemStatus.ACTIVE) {
4359
- await ((_a = this._resourceLock) == null ? void 0 : _a.acquire());
4360
- } else if (this.isOpen && status === import_services13.SystemStatus.INACTIVE) {
4361
- 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;
4362
4314
  }
4363
- },
4364
- onReset: async () => {
4365
- await this.reset();
4315
+ return handler(method, params);
4366
4316
  }
4317
+ };
4318
+ this._clientRpc = new ClientRpcServer({
4319
+ serviceRegistry: this._serviceHost.serviceRegistry,
4320
+ port: appPort,
4321
+ ...middleware
4367
4322
  });
4368
- this._loggingService = new LoggingServiceImpl();
4369
- this._serviceRegistry = new ServiceRegistry(import_client_protocol9.clientServiceBundle, {
4370
- SystemService: this._systemService
4323
+ this._shellClientRpc = new ClientRpcServer({
4324
+ serviceRegistry: this._serviceHost.serviceRegistry,
4325
+ port: shellPort,
4326
+ ...middleware
4371
4327
  });
4372
- }
4373
- get isOpen() {
4374
- return this._open;
4375
- }
4376
- get serviceRegistry() {
4377
- return this._serviceRegistry;
4378
- }
4379
- get descriptors() {
4380
- return this._serviceRegistry.descriptors;
4381
- }
4382
- get services() {
4383
- return this._serviceRegistry.services;
4384
- }
4385
- /**
4386
- * Initialize the service host with the config.
4387
- * Config can also be provided in the constructor.
4388
- * Can only be called once.
4389
- */
4390
- initialize({ config, ...options }) {
4391
- var _a, _b, _c;
4392
- (0, import_node_assert14.default)(!this._open, "service host is open");
4393
- if (config) {
4394
- (0, import_node_assert14.default)(!this._config, "config already set");
4395
- this._config = config;
4396
- if (!this._storage) {
4397
- this._storage = createStorageObjects(config.get("runtime.client.storage", {})).storage;
4398
- }
4399
- }
4400
- const { connectionLog = true, transportFactory = (0, import_network_manager5.createWebRTCTransportFactory)({
4401
- iceServers: (_a = this._config) == null ? void 0 : _a.get("runtime.services.ice")
4402
- }), signalManager = new import_messaging3.WebsocketSignalManager((_c = (_b = this._config) == null ? void 0 : _b.get("runtime.services.signaling")) != null ? _c : []) } = options;
4403
- this._signalManager = signalManager;
4404
- (0, import_node_assert14.default)(!this._networkManager, "network manager already set");
4405
- this._networkManager = new import_network_manager5.NetworkManager({
4406
- log: connectionLog,
4407
- transportFactory,
4408
- 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
4409
4356
  });
4357
+ this.bridgeService = this._iframeRpc.rpc.BridgeService;
4410
4358
  }
4411
4359
  async open() {
4412
- var _a, _b, _c;
4413
- if (this._open) {
4414
- return;
4415
- }
4416
- const traceId = import_keys11.PublicKey.random().toHex();
4417
- import_log19.log.trace("dxos.sdk.client-services-host.open", import_protocols9.trace.begin({
4418
- id: traceId
4419
- }), {
4420
- file: "service-host.ts",
4421
- line: 187,
4422
- scope: this,
4423
- callSite: (f, a) => f(...a)
4424
- });
4425
- (0, import_node_assert14.default)(this._config, "config not set");
4426
- (0, import_node_assert14.default)(this._storage, "storage not set");
4427
- (0, import_node_assert14.default)(this._signalManager, "signal manager not set");
4428
- (0, import_node_assert14.default)(this._networkManager, "network manager not set");
4429
- this._opening = true;
4430
- (0, import_log19.log)("opening...", {
4431
- lockKey: (_a = this._resourceLock) == null ? void 0 : _a.lockKey
4432
- }, {
4433
- file: "service-host.ts",
4434
- line: 195,
4435
- scope: this,
4436
- callSite: (f, a) => f(...a)
4437
- });
4438
- await ((_b = this._resourceLock) == null ? void 0 : _b.acquire());
4439
- await this._loggingService.open();
4440
- this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._signalManager, this._modelFactory);
4441
- this._serviceRegistry.setServices({
4442
- SystemService: this._systemService,
4443
- IdentityService: new IdentityServiceImpl(this._serviceContext),
4444
- InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitations, (invitation) => this._serviceContext.getInvitationHandler(invitation)),
4445
- DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),
4446
- SpacesService: new SpacesServiceImpl(this._serviceContext.identityManager, this._serviceContext.spaceManager, this._serviceContext.dataServiceSubscriptions, async () => {
4447
- await this._serviceContext.initialized.wait();
4448
- return this._serviceContext.dataSpaceManager;
4449
- }),
4450
- DataService: new import_echo_pipeline4.DataServiceImpl(this._serviceContext.dataServiceSubscriptions),
4451
- NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager, this._serviceContext.signalManager),
4452
- LoggingService: this._loggingService,
4453
- // TODO(burdon): Move to new protobuf definitions.
4454
- DevtoolsHost: new DevtoolsServiceImpl({
4455
- events: new DevtoolsHostEvents(),
4456
- config: this._config,
4457
- context: this._serviceContext
4458
- })
4459
- });
4460
- await this._serviceContext.open();
4461
- this._opening = false;
4462
- this._open = true;
4463
- this._statusUpdate.emit();
4464
- const deviceKey = (_c = this._serviceContext.identityManager.identity) == null ? void 0 : _c.deviceKey;
4465
- (0, import_log19.log)("opened", {
4466
- deviceKey
4467
- }, {
4468
- file: "service-host.ts",
4469
- line: 250,
4360
+ import_log18.log.info("opening..", {}, {
4361
+ file: "worker-session.ts",
4362
+ line: 114,
4470
4363
  scope: this,
4471
4364
  callSite: (f, a) => f(...a)
4472
4365
  });
4473
- import_log19.log.trace("dxos.sdk.client-services-host.open", import_protocols9.trace.end({
4474
- id: traceId
4475
- }), {
4476
- file: "service-host.ts",
4477
- line: 251,
4478
- scope: this,
4479
- 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
4480
4373
  });
4374
+ if (this.lockKey) {
4375
+ void this._afterLockReleases(this.lockKey, () => this.close());
4376
+ }
4481
4377
  }
4482
4378
  async close() {
4483
- var _a;
4484
- if (!this._open) {
4485
- return;
4486
- }
4487
- const deviceKey = (_a = this._serviceContext.identityManager.identity) == null ? void 0 : _a.deviceKey;
4488
- (0, import_log19.log)("closing...", {
4489
- deviceKey
4490
- }, {
4491
- file: "service-host.ts",
4492
- line: 260,
4493
- scope: this,
4494
- callSite: (f, a) => f(...a)
4495
- });
4496
- this._serviceRegistry.setServices({
4497
- SystemService: this._systemService
4498
- });
4499
- await this._loggingService.close();
4500
- await this._serviceContext.close();
4501
- this._open = false;
4502
- this._statusUpdate.emit();
4503
- (0, import_log19.log)("closed", {
4504
- deviceKey
4505
- }, {
4506
- file: "service-host.ts",
4507
- line: 266,
4379
+ import_log18.log.info("closing..", {}, {
4380
+ file: "worker-session.ts",
4381
+ line: 124,
4508
4382
  scope: this,
4509
4383
  callSite: (f, a) => f(...a)
4510
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
+ ]);
4511
4399
  }
4512
- async reset() {
4513
- var _a;
4514
- const traceId = import_keys11.PublicKey.random().toHex();
4515
- import_log19.log.trace("dxos.sdk.client-services-host.reset", import_protocols9.trace.begin({
4516
- id: traceId
4517
- }), {
4518
- file: "service-host.ts",
4519
- line: 271,
4520
- scope: this,
4521
- callSite: (f, a) => f(...a)
4522
- });
4523
- (0, import_log19.log)("resetting...", {}, {
4524
- file: "service-host.ts",
4525
- line: 273,
4526
- scope: this,
4527
- callSite: (f, a) => f(...a)
4528
- });
4529
- await ((_a = this._serviceContext) == null ? void 0 : _a.close());
4530
- await this._storage.reset();
4531
- (0, import_log19.log)("reset", {}, {
4532
- file: "service-host.ts",
4533
- line: 276,
4534
- scope: this,
4535
- callSite: (f, a) => f(...a)
4536
- });
4537
- import_log19.log.trace("dxos.sdk.client-services-host.reset", import_protocols9.trace.end({
4538
- id: traceId
4539
- }), {
4540
- file: "service-host.ts",
4541
- line: 277,
4542
- scope: this,
4543
- callSite: (f, a) => f(...a)
4544
- });
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);
4545
4415
  }
4546
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);
4547
4423
 
4548
- // packages/sdk/client-services/src/packlets/services/local-client-services.ts
4549
- var LocalClientServices = class {
4550
- constructor(params) {
4551
- 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();
4552
4433
  }
4553
- get descriptors() {
4554
- return this._host.descriptors;
4434
+ get host() {
4435
+ return this._clientServices;
4555
4436
  }
4556
- get services() {
4557
- 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
+ }
4558
4469
  }
4559
- get host() {
4560
- return this._host;
4470
+ async stop() {
4471
+ await this._clientServices.close();
4561
4472
  }
4562
- async open() {
4563
- 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();
4564
4491
  }
4565
- async close() {
4566
- 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
+ }
4567
4516
  }
4568
4517
  };
4569
4518
  // Annotate the CommonJS export names for ESM import in node:
@@ -4582,6 +4531,7 @@ var LocalClientServices = class {
4582
4531
  InvitationsHandler,
4583
4532
  InvitationsServiceImpl,
4584
4533
  LocalClientServices,
4534
+ Lock,
4585
4535
  MemoryShellRuntime,
4586
4536
  ServiceContext,
4587
4537
  ServiceRegistry,
@@ -4589,12 +4539,12 @@ var LocalClientServices = class {
4589
4539
  SpaceInvitationProtocol,
4590
4540
  SpacesServiceImpl,
4591
4541
  TrustedKeySetAuthVerifier,
4592
- VaultResourceLock,
4593
4542
  WorkerRuntime,
4594
4543
  WorkerSession,
4595
4544
  createAuthProvider,
4596
4545
  createStorageObjects,
4597
4546
  getNetworkPeers,
4547
+ isLocked,
4598
4548
  subscribeToFeedBlocks,
4599
4549
  subscribeToFeeds,
4600
4550
  subscribeToNetworkStatus,