@dxos/client-services 0.6.13 → 0.6.14-main.2b6a0f3

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 (138) hide show
  1. package/dist/lib/browser/{chunk-CRXXOI45.mjs → chunk-BBLK6AUB.mjs} +6301 -5383
  2. package/dist/lib/browser/chunk-BBLK6AUB.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +320 -45
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +12 -7
  7. package/dist/lib/browser/testing/index.mjs.map +3 -3
  8. package/dist/lib/node/{chunk-PZ3JJJ3K.cjs → chunk-SJEDBF7U.cjs} +6286 -5378
  9. package/dist/lib/node/chunk-SJEDBF7U.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +369 -94
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +18 -13
  14. package/dist/lib/node/testing/index.cjs.map +3 -3
  15. package/dist/lib/node-esm/chunk-A6GS6OOD.mjs +8634 -0
  16. package/dist/lib/node-esm/chunk-A6GS6OOD.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +691 -0
  18. package/dist/lib/node-esm/index.mjs.map +7 -0
  19. package/dist/lib/node-esm/meta.json +1 -0
  20. package/dist/lib/node-esm/testing/index.mjs +424 -0
  21. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  22. package/dist/types/src/index.d.ts +1 -0
  23. package/dist/types/src/index.d.ts.map +1 -1
  24. package/dist/types/src/packlets/agents/edge-agent-manager.d.ts +35 -0
  25. package/dist/types/src/packlets/agents/edge-agent-manager.d.ts.map +1 -0
  26. package/dist/types/src/packlets/agents/edge-agent-service.d.ts +10 -0
  27. package/dist/types/src/packlets/agents/edge-agent-service.d.ts.map +1 -0
  28. package/dist/types/src/packlets/agents/index.d.ts +3 -0
  29. package/dist/types/src/packlets/agents/index.d.ts.map +1 -0
  30. package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts.map +1 -1
  31. package/dist/types/src/packlets/identity/authenticator.d.ts.map +1 -1
  32. package/dist/types/src/packlets/identity/authenticator.node.test.d.ts +2 -0
  33. package/dist/types/src/packlets/identity/authenticator.node.test.d.ts.map +1 -0
  34. package/dist/types/src/packlets/identity/contacts-service.d.ts +1 -1
  35. package/dist/types/src/packlets/identity/contacts-service.d.ts.map +1 -1
  36. package/dist/types/src/packlets/identity/identity-manager.d.ts +28 -9
  37. package/dist/types/src/packlets/identity/identity-manager.d.ts.map +1 -1
  38. package/dist/types/src/packlets/identity/identity-recovery-manager.d.ts +18 -0
  39. package/dist/types/src/packlets/identity/identity-recovery-manager.d.ts.map +1 -0
  40. package/dist/types/src/packlets/identity/identity-service.d.ts +7 -2
  41. package/dist/types/src/packlets/identity/identity-service.d.ts.map +1 -1
  42. package/dist/types/src/packlets/identity/identity.d.ts +12 -3
  43. package/dist/types/src/packlets/identity/identity.d.ts.map +1 -1
  44. package/dist/types/src/packlets/invitations/device-invitation-protocol.d.ts.map +1 -1
  45. package/dist/types/src/packlets/invitations/edge-invitation-handler.d.ts +30 -0
  46. package/dist/types/src/packlets/invitations/edge-invitation-handler.d.ts.map +1 -0
  47. package/dist/types/src/packlets/invitations/invitation-guest-extenstion.d.ts +2 -1
  48. package/dist/types/src/packlets/invitations/invitation-guest-extenstion.d.ts.map +1 -1
  49. package/dist/types/src/packlets/invitations/invitation-host-extension.d.ts +2 -1
  50. package/dist/types/src/packlets/invitations/invitation-host-extension.d.ts.map +1 -1
  51. package/dist/types/src/packlets/invitations/invitation-state.d.ts +19 -0
  52. package/dist/types/src/packlets/invitations/invitation-state.d.ts.map +1 -0
  53. package/dist/types/src/packlets/invitations/invitations-handler.d.ts +8 -8
  54. package/dist/types/src/packlets/invitations/invitations-handler.d.ts.map +1 -1
  55. package/dist/types/src/packlets/invitations/space-invitation-protocol.d.ts.map +1 -1
  56. package/dist/types/src/packlets/services/service-context.d.ts +14 -9
  57. package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
  58. package/dist/types/src/packlets/services/service-host.d.ts +2 -0
  59. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  60. package/dist/types/src/packlets/spaces/data-space-manager.d.ts +7 -3
  61. package/dist/types/src/packlets/spaces/data-space-manager.d.ts.map +1 -1
  62. package/dist/types/src/packlets/spaces/data-space.d.ts +5 -3
  63. package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
  64. package/dist/types/src/packlets/spaces/edge-feed-replicator.d.ts +3 -0
  65. package/dist/types/src/packlets/spaces/edge-feed-replicator.d.ts.map +1 -1
  66. package/dist/types/src/packlets/spaces/edge-feed-replicator.test.d.ts +2 -0
  67. package/dist/types/src/packlets/spaces/edge-feed-replicator.test.d.ts.map +1 -0
  68. package/dist/types/src/packlets/spaces/epoch-migrations.d.ts +1 -1
  69. package/dist/types/src/packlets/spaces/epoch-migrations.d.ts.map +1 -1
  70. package/dist/types/src/packlets/spaces/notarization-plugin.d.ts +35 -6
  71. package/dist/types/src/packlets/spaces/notarization-plugin.d.ts.map +1 -1
  72. package/dist/types/src/packlets/spaces/spaces-service.d.ts +1 -1
  73. package/dist/types/src/packlets/spaces/spaces-service.d.ts.map +1 -1
  74. package/dist/types/src/packlets/storage/storage.d.ts.map +1 -1
  75. package/dist/types/src/packlets/testing/test-builder.d.ts +1 -2
  76. package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
  77. package/dist/types/src/packlets/worker/worker-runtime.d.ts.map +1 -1
  78. package/dist/types/src/testing/setup.d.ts +3 -0
  79. package/dist/types/src/testing/setup.d.ts.map +1 -0
  80. package/dist/types/src/version.d.ts +1 -1
  81. package/dist/types/src/version.d.ts.map +1 -1
  82. package/package.json +44 -39
  83. package/src/index.ts +1 -0
  84. package/src/packlets/agents/edge-agent-manager.ts +163 -0
  85. package/src/packlets/agents/edge-agent-service.ts +42 -0
  86. package/src/packlets/agents/index.ts +6 -0
  87. package/src/packlets/devices/devices-service.test.ts +4 -5
  88. package/src/packlets/diagnostics/diagnostics-broadcast.ts +1 -0
  89. package/src/packlets/identity/{authenticator.test.ts → authenticator.node.test.ts} +2 -3
  90. package/src/packlets/identity/authenticator.ts +5 -2
  91. package/src/packlets/identity/contacts-service.ts +1 -1
  92. package/src/packlets/identity/identity-manager.test.ts +31 -16
  93. package/src/packlets/identity/identity-manager.ts +76 -32
  94. package/src/packlets/identity/identity-recovery-manager.ts +95 -0
  95. package/src/packlets/identity/identity-service.test.ts +5 -8
  96. package/src/packlets/identity/identity-service.ts +11 -5
  97. package/src/packlets/identity/identity.test.ts +130 -239
  98. package/src/packlets/identity/identity.ts +60 -17
  99. package/src/packlets/invitations/device-invitation-protocol.test.ts +7 -4
  100. package/src/packlets/invitations/device-invitation-protocol.ts +5 -1
  101. package/src/packlets/invitations/edge-invitation-handler.ts +185 -0
  102. package/src/packlets/invitations/invitation-guest-extenstion.ts +8 -4
  103. package/src/packlets/invitations/invitation-host-extension.ts +8 -7
  104. package/src/packlets/invitations/invitation-state.ts +111 -0
  105. package/src/packlets/invitations/invitations-handler.test.ts +16 -9
  106. package/src/packlets/invitations/invitations-handler.ts +23 -93
  107. package/src/packlets/invitations/space-invitation-protocol.test.ts +4 -3
  108. package/src/packlets/invitations/space-invitation-protocol.ts +4 -0
  109. package/src/packlets/logging/logging.test.ts +1 -2
  110. package/src/packlets/network/network-service.test.ts +2 -3
  111. package/src/packlets/services/service-context.test.ts +3 -1
  112. package/src/packlets/services/service-context.ts +113 -35
  113. package/src/packlets/services/service-host.test.ts +8 -12
  114. package/src/packlets/services/service-host.ts +25 -7
  115. package/src/packlets/services/service-registry.test.ts +1 -2
  116. package/src/packlets/spaces/data-space-manager.test.ts +2 -2
  117. package/src/packlets/spaces/data-space-manager.ts +44 -7
  118. package/src/packlets/spaces/data-space.ts +37 -6
  119. package/src/packlets/spaces/edge-feed-replicator.test.ts +252 -0
  120. package/src/packlets/spaces/edge-feed-replicator.ts +80 -22
  121. package/src/packlets/spaces/epoch-migrations.ts +2 -2
  122. package/src/packlets/spaces/notarization-plugin.test.ts +10 -7
  123. package/src/packlets/spaces/notarization-plugin.ts +196 -29
  124. package/src/packlets/spaces/spaces-service.test.ts +5 -9
  125. package/src/packlets/spaces/spaces-service.ts +6 -1
  126. package/src/packlets/storage/storage.ts +0 -1
  127. package/src/packlets/system/system-service.test.ts +1 -2
  128. package/src/packlets/testing/test-builder.ts +7 -4
  129. package/src/packlets/worker/worker-runtime.ts +2 -2
  130. package/src/testing/setup.ts +11 -0
  131. package/src/version.ts +1 -5
  132. package/dist/lib/browser/chunk-CRXXOI45.mjs.map +0 -7
  133. package/dist/lib/node/chunk-PZ3JJJ3K.cjs.map +0 -7
  134. package/dist/types/src/packlets/identity/authenticator.test.d.ts +0 -2
  135. package/dist/types/src/packlets/identity/authenticator.test.d.ts.map +0 -1
  136. package/dist/types/src/packlets/services/automerge-host.test.d.ts +0 -2
  137. package/dist/types/src/packlets/services/automerge-host.test.d.ts.map +0 -1
  138. package/src/packlets/services/automerge-host.test.ts +0 -60
@@ -0,0 +1,691 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+ import {
3
+ ClientServicesHost,
4
+ DataSpace,
5
+ DataSpaceManager,
6
+ DeviceInvitationProtocol,
7
+ DevtoolsHostEvents,
8
+ DevtoolsServiceImpl,
9
+ EdgeAgentManager,
10
+ EdgeAgentServiceImpl,
11
+ EdgeFeedReplicator,
12
+ Identity,
13
+ IdentityManager,
14
+ IdentityServiceImpl,
15
+ InvitationsHandler,
16
+ InvitationsManager,
17
+ InvitationsServiceImpl,
18
+ Lock,
19
+ ServiceContext,
20
+ ServiceRegistry,
21
+ SpaceInvitationProtocol,
22
+ SpacesServiceImpl,
23
+ TrustedKeySetAuthVerifier,
24
+ createAdmissionKeypair,
25
+ createAuthProvider,
26
+ createCollectDiagnosticsBroadcastHandler,
27
+ createCollectDiagnosticsBroadcastSender,
28
+ createDiagnostics,
29
+ createLevel,
30
+ createStorageObjects,
31
+ getNetworkPeers,
32
+ isLocked,
33
+ subscribeToFeedBlocks,
34
+ subscribeToFeeds,
35
+ subscribeToNetworkStatus,
36
+ subscribeToNetworkTopics,
37
+ subscribeToSignal,
38
+ subscribeToSpaces,
39
+ subscribeToSwarmInfo
40
+ } from "./chunk-A6GS6OOD.mjs";
41
+
42
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics-collector.ts
43
+ import { ClientServicesProviderResource } from "@dxos/client-protocol";
44
+ import { ConfigResource } from "@dxos/config";
45
+ import { GetDiagnosticsRequest } from "@dxos/protocols/proto/dxos/client/services";
46
+ import { TRACE_PROCESSOR } from "@dxos/tracing";
47
+ import { jsonKeyReplacer, nonNullable } from "@dxos/util";
48
+ var GET_DIAGNOSTICS_RPC_TIMEOUT = 1e4;
49
+ var DiagnosticsCollector = class {
50
+ static {
51
+ this.broadcastSender = createCollectDiagnosticsBroadcastSender();
52
+ }
53
+ static async collect(config = findConfigs(), services = findSystemServiceProvider(), options = {}) {
54
+ const serviceDiagnostics = await services?.services?.SystemService?.getDiagnostics({
55
+ keys: options.humanize ? GetDiagnosticsRequest.KEY_OPTION.HUMANIZE : options.truncate ? GetDiagnosticsRequest.KEY_OPTION.TRUNCATE : void 0
56
+ }, {
57
+ timeout: GET_DIAGNOSTICS_RPC_TIMEOUT
58
+ });
59
+ const clientDiagnostics = {
60
+ config,
61
+ trace: TRACE_PROCESSOR.getDiagnostics()
62
+ };
63
+ const diagnostics = serviceDiagnostics != null ? {
64
+ client: clientDiagnostics,
65
+ services: serviceDiagnostics
66
+ } : {
67
+ client: clientDiagnostics,
68
+ broadcast: await this.broadcastSender.broadcastDiagnosticsRequest()
69
+ };
70
+ return JSON.parse(JSON.stringify(diagnostics, jsonKeyReplacer(options)));
71
+ }
72
+ };
73
+ var findSystemServiceProvider = () => {
74
+ const serviceProviders = TRACE_PROCESSOR.findResourcesByAnnotation(ClientServicesProviderResource);
75
+ const providerResource = serviceProviders.find((r) => r.instance.deref()?.services?.SystemService != null);
76
+ return providerResource?.instance?.deref() ?? null;
77
+ };
78
+ var findConfigs = () => {
79
+ const configs = TRACE_PROCESSOR.findResourcesByAnnotation(ConfigResource);
80
+ return configs.map((r) => r.instance.deref()).filter(nonNullable);
81
+ };
82
+
83
+ // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
84
+ import { Stream } from "@dxos/codec-protobuf";
85
+ import { raise } from "@dxos/debug";
86
+ import { parseMethodName, RpcPeer } from "@dxos/rpc";
87
+ import { MapCounter, trace } from "@dxos/tracing";
88
+ function _ts_decorate(decorators, target, key, desc) {
89
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
90
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
91
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
92
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
93
+ }
94
+ var ClientRpcServer = class {
95
+ constructor(params) {
96
+ this._handlerCache = /* @__PURE__ */ new Map();
97
+ this._callMetrics = new MapCounter();
98
+ const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
99
+ this._handleCall = handleCall;
100
+ this._handleStream = handleStream;
101
+ this._serviceRegistry = serviceRegistry;
102
+ this._rpcPeer = new RpcPeer({
103
+ ...rpcOptions,
104
+ callHandler: (method, params2) => {
105
+ const [serviceName, methodName] = parseMethodName(method);
106
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
107
+ this._callMetrics.inc(`${serviceName}.${methodName} request`);
108
+ if (this._handleCall) {
109
+ return this._handleCall(methodName, params2, handler);
110
+ } else {
111
+ return handler(methodName, params2);
112
+ }
113
+ },
114
+ streamHandler: (method, params2) => {
115
+ const [serviceName, methodName] = parseMethodName(method);
116
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
117
+ this._callMetrics.inc(`${serviceName}.${methodName} request stream`);
118
+ if (this._handleStream) {
119
+ return Stream.map(Stream.unwrapPromise(this._handleStream(methodName, params2, handler)), (data) => {
120
+ this._callMetrics.inc(`${serviceName}.${methodName} response stream`);
121
+ return data;
122
+ });
123
+ } else {
124
+ return handler(methodName, params2);
125
+ }
126
+ }
127
+ });
128
+ }
129
+ get _services() {
130
+ return Object.keys(this._serviceRegistry.services);
131
+ }
132
+ async open() {
133
+ await this._rpcPeer.open();
134
+ }
135
+ async close() {
136
+ await this._rpcPeer.close();
137
+ }
138
+ _getServiceHandler(serviceName) {
139
+ if (!this._handlerCache.has(serviceName)) {
140
+ const [key, descriptor] = Object.entries(this._serviceRegistry.descriptors).find(([key2, descriptor2]) => descriptor2.name === serviceName) ?? raise(new Error(`Service not available: ${serviceName}`));
141
+ const service = this._serviceRegistry.services[key];
142
+ if (!service) {
143
+ throw new Error(`Service not available: ${serviceName}`);
144
+ }
145
+ this._handlerCache.set(serviceName, descriptor.createServer(service));
146
+ }
147
+ return this._handlerCache.get(serviceName);
148
+ }
149
+ };
150
+ _ts_decorate([
151
+ trace.metricsCounter()
152
+ ], ClientRpcServer.prototype, "_callMetrics", void 0);
153
+ _ts_decorate([
154
+ trace.info()
155
+ ], ClientRpcServer.prototype, "_services", null);
156
+ ClientRpcServer = _ts_decorate([
157
+ trace.resource()
158
+ ], ClientRpcServer);
159
+
160
+ // packages/sdk/client-services/src/packlets/storage/profile-archive.ts
161
+ import { cbor } from "@dxos/automerge/automerge-repo";
162
+ import { invariant } from "@dxos/invariant";
163
+ import { log } from "@dxos/log";
164
+ import { ProfileArchiveEntryType } from "@dxos/protocols";
165
+ import { arrayToBuffer } from "@dxos/util";
166
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/storage/profile-archive.ts";
167
+ var encodeProfileArchive = (profile) => cbor.encode(profile);
168
+ var decodeProfileArchive = (data) => cbor.decode(data);
169
+ var exportProfileData = async ({ storage, level }) => {
170
+ const archive = {
171
+ storage: [],
172
+ meta: {
173
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
174
+ }
175
+ };
176
+ {
177
+ const directory = await storage.createDirectory();
178
+ const files = await directory.list();
179
+ log.info("begin exporting files", {
180
+ count: files.length
181
+ }, {
182
+ F: __dxlog_file,
183
+ L: 30,
184
+ S: void 0,
185
+ C: (f, a) => f(...a)
186
+ });
187
+ for (const filename of files) {
188
+ const file = await directory.getOrCreateFile(filename);
189
+ const { size } = await file.stat();
190
+ const data = await file.read(0, size);
191
+ archive.storage.push({
192
+ type: ProfileArchiveEntryType.FILE,
193
+ key: filename,
194
+ value: data
195
+ });
196
+ }
197
+ log.info("done exporting files", {
198
+ count: files.length
199
+ }, {
200
+ F: __dxlog_file,
201
+ L: 41,
202
+ S: void 0,
203
+ C: (f, a) => f(...a)
204
+ });
205
+ }
206
+ {
207
+ log.info("begin exporting kv pairs", void 0, {
208
+ F: __dxlog_file,
209
+ L: 45,
210
+ S: void 0,
211
+ C: (f, a) => f(...a)
212
+ });
213
+ const iter = await level.iterator({
214
+ keyEncoding: "binary",
215
+ valueEncoding: "binary"
216
+ });
217
+ let count = 0;
218
+ for await (const [key, value] of iter) {
219
+ archive.storage.push({
220
+ type: ProfileArchiveEntryType.KEY_VALUE,
221
+ key,
222
+ value
223
+ });
224
+ count++;
225
+ }
226
+ log.info("done exporting kv pairs", {
227
+ count
228
+ }, {
229
+ F: __dxlog_file,
230
+ L: 56,
231
+ S: void 0,
232
+ C: (f, a) => f(...a)
233
+ });
234
+ }
235
+ return archive;
236
+ };
237
+ var importProfileData = async ({ storage, level }, archive) => {
238
+ let batch = level.batch();
239
+ let count = 0;
240
+ for (const entry of archive.storage) {
241
+ switch (entry.type) {
242
+ case ProfileArchiveEntryType.FILE: {
243
+ const directory = await storage.createDirectory();
244
+ invariant(typeof entry.key === "string", "Invalid key type", {
245
+ F: __dxlog_file,
246
+ L: 79,
247
+ S: void 0,
248
+ A: [
249
+ "typeof entry.key === 'string'",
250
+ "'Invalid key type'"
251
+ ]
252
+ });
253
+ const file = await directory.getOrCreateFile(entry.key);
254
+ invariant(entry.value instanceof Uint8Array, "Invalid value type", {
255
+ F: __dxlog_file,
256
+ L: 81,
257
+ S: void 0,
258
+ A: [
259
+ "entry.value instanceof Uint8Array",
260
+ "'Invalid value type'"
261
+ ]
262
+ });
263
+ await file.write(0, arrayToBuffer(entry.value));
264
+ await file.close();
265
+ break;
266
+ }
267
+ case ProfileArchiveEntryType.KEY_VALUE: {
268
+ invariant(entry.key instanceof Uint8Array, "Invalid key type", {
269
+ F: __dxlog_file,
270
+ L: 87,
271
+ S: void 0,
272
+ A: [
273
+ "entry.key instanceof Uint8Array",
274
+ "'Invalid key type'"
275
+ ]
276
+ });
277
+ invariant(entry.value instanceof Uint8Array, "Invalid value type", {
278
+ F: __dxlog_file,
279
+ L: 88,
280
+ S: void 0,
281
+ A: [
282
+ "entry.value instanceof Uint8Array",
283
+ "'Invalid value type'"
284
+ ]
285
+ });
286
+ batch.put(entry.key, entry.value, {
287
+ keyEncoding: "binary",
288
+ valueEncoding: "binary"
289
+ });
290
+ break;
291
+ }
292
+ default:
293
+ throw new Error(`Invalid entry type: ${entry.type}`);
294
+ }
295
+ if (++count % 1e3 === 0) {
296
+ await batch.write();
297
+ batch = level.batch();
298
+ log.info("importing", {
299
+ count,
300
+ total: archive.storage.length,
301
+ progress: `${(count / archive.storage.length * 100).toFixed()}%`
302
+ }, {
303
+ F: __dxlog_file,
304
+ L: 101,
305
+ S: void 0,
306
+ C: (f, a) => f(...a)
307
+ });
308
+ }
309
+ }
310
+ log.info("committing changes..", void 0, {
311
+ F: __dxlog_file,
312
+ L: 109,
313
+ S: void 0,
314
+ C: (f, a) => f(...a)
315
+ });
316
+ await batch.write();
317
+ };
318
+
319
+ // packages/sdk/client-services/src/packlets/worker/worker-runtime.ts
320
+ import { Trigger as Trigger2 } from "@dxos/async";
321
+ import { DEFAULT_WORKER_BROADCAST_CHANNEL } from "@dxos/client-protocol";
322
+ import { Context } from "@dxos/context";
323
+ import { invariant as invariant3 } from "@dxos/invariant";
324
+ import { log as log3 } from "@dxos/log";
325
+ import { MemorySignalManager, MemorySignalManagerContext, WebsocketSignalManager, setIdentityTags } from "@dxos/messaging";
326
+ import { RtcTransportProxyFactory } from "@dxos/network-manager";
327
+
328
+ // packages/sdk/client-services/src/packlets/worker/worker-session.ts
329
+ import { asyncTimeout, Trigger } from "@dxos/async";
330
+ import { iframeServiceBundle, PROXY_CONNECTION_TIMEOUT, workerServiceBundle } from "@dxos/client-protocol";
331
+ import { invariant as invariant2 } from "@dxos/invariant";
332
+ import { log as log2, logInfo } from "@dxos/log";
333
+ import { createProtoRpcPeer } from "@dxos/rpc";
334
+ import { Callback } from "@dxos/util";
335
+ function _ts_decorate2(decorators, target, key, desc) {
336
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
337
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
338
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
339
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
340
+ }
341
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/worker/worker-session.ts";
342
+ var WorkerSession = class {
343
+ constructor({ serviceHost, systemPort, appPort, shellPort, readySignal }) {
344
+ this._startTrigger = new Trigger();
345
+ this.onClose = new Callback();
346
+ invariant2(serviceHost, void 0, {
347
+ F: __dxlog_file2,
348
+ L: 54,
349
+ S: this,
350
+ A: [
351
+ "serviceHost",
352
+ ""
353
+ ]
354
+ });
355
+ this._serviceHost = serviceHost;
356
+ const middleware = {
357
+ handleCall: async (method, params, handler) => {
358
+ const error = await readySignal.wait({
359
+ timeout: PROXY_CONNECTION_TIMEOUT
360
+ });
361
+ if (error) {
362
+ throw error;
363
+ }
364
+ return handler(method, params);
365
+ },
366
+ handleStream: async (method, params, handler) => {
367
+ const error = await readySignal.wait({
368
+ timeout: PROXY_CONNECTION_TIMEOUT
369
+ });
370
+ if (error) {
371
+ throw error;
372
+ }
373
+ return handler(method, params);
374
+ }
375
+ };
376
+ this._clientRpc = new ClientRpcServer({
377
+ serviceRegistry: this._serviceHost.serviceRegistry,
378
+ port: appPort,
379
+ ...middleware
380
+ });
381
+ this._shellClientRpc = shellPort ? new ClientRpcServer({
382
+ serviceRegistry: this._serviceHost.serviceRegistry,
383
+ port: shellPort,
384
+ ...middleware
385
+ }) : void 0;
386
+ this._iframeRpc = createProtoRpcPeer({
387
+ requested: iframeServiceBundle,
388
+ exposed: workerServiceBundle,
389
+ handlers: {
390
+ WorkerService: {
391
+ start: async (request) => {
392
+ this.origin = request.origin;
393
+ this.lockKey = request.lockKey;
394
+ this.observabilityGroup = request.observabilityGroup;
395
+ this.signalTelemetryEnabled = request.signalTelemetryEnabled;
396
+ this._startTrigger.wake();
397
+ },
398
+ stop: async () => {
399
+ setTimeout(async () => {
400
+ try {
401
+ await this.close();
402
+ } catch (err) {
403
+ log2.catch(err, void 0, {
404
+ F: __dxlog_file2,
405
+ L: 108,
406
+ S: this,
407
+ C: (f, a) => f(...a)
408
+ });
409
+ }
410
+ });
411
+ }
412
+ }
413
+ },
414
+ port: systemPort,
415
+ timeout: 1e3
416
+ });
417
+ this.bridgeService = this._iframeRpc.rpc.BridgeService;
418
+ }
419
+ async open() {
420
+ log2.info("opening...", void 0, {
421
+ F: __dxlog_file2,
422
+ L: 122,
423
+ S: this,
424
+ C: (f, a) => f(...a)
425
+ });
426
+ await Promise.all([
427
+ this._clientRpc.open(),
428
+ this._iframeRpc.open(),
429
+ this._maybeOpenShell()
430
+ ]);
431
+ await this._startTrigger.wait({
432
+ timeout: PROXY_CONNECTION_TIMEOUT
433
+ });
434
+ if (this.lockKey) {
435
+ void this._afterLockReleases(this.lockKey, () => this.close());
436
+ }
437
+ log2.info("opened", void 0, {
438
+ F: __dxlog_file2,
439
+ L: 133,
440
+ S: this,
441
+ C: (f, a) => f(...a)
442
+ });
443
+ }
444
+ async close() {
445
+ log2.info("closing...", void 0, {
446
+ F: __dxlog_file2,
447
+ L: 137,
448
+ S: this,
449
+ C: (f, a) => f(...a)
450
+ });
451
+ try {
452
+ await this.onClose.callIfSet();
453
+ } catch (err) {
454
+ log2.catch(err, void 0, {
455
+ F: __dxlog_file2,
456
+ L: 141,
457
+ S: this,
458
+ C: (f, a) => f(...a)
459
+ });
460
+ }
461
+ await Promise.all([
462
+ this._clientRpc.close(),
463
+ this._iframeRpc.close()
464
+ ]);
465
+ log2.info("closed", void 0, {
466
+ F: __dxlog_file2,
467
+ L: 145,
468
+ S: this,
469
+ C: (f, a) => f(...a)
470
+ });
471
+ }
472
+ async _maybeOpenShell() {
473
+ try {
474
+ this._shellClientRpc && await asyncTimeout(this._shellClientRpc.open(), 1e3);
475
+ } catch {
476
+ log2.info("No shell connected.", void 0, {
477
+ F: __dxlog_file2,
478
+ L: 152,
479
+ S: this,
480
+ C: (f, a) => f(...a)
481
+ });
482
+ }
483
+ }
484
+ _afterLockReleases(lockKey, callback) {
485
+ return navigator.locks.request(lockKey, () => {
486
+ }).then(callback);
487
+ }
488
+ };
489
+ _ts_decorate2([
490
+ logInfo
491
+ ], WorkerSession.prototype, "origin", void 0);
492
+ _ts_decorate2([
493
+ logInfo
494
+ ], WorkerSession.prototype, "lockKey", void 0);
495
+
496
+ // packages/sdk/client-services/src/packlets/worker/worker-runtime.ts
497
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/worker/worker-runtime.ts";
498
+ var WorkerRuntime = class {
499
+ constructor({ channel = DEFAULT_WORKER_BROADCAST_CHANNEL, configProvider, acquireLock, releaseLock, onStop }) {
500
+ this._transportFactory = new RtcTransportProxyFactory();
501
+ this._ready = new Trigger2();
502
+ this._sessions = /* @__PURE__ */ new Set();
503
+ this._signalMetadataTags = {
504
+ runtime: "worker-runtime"
505
+ };
506
+ this._signalTelemetryEnabled = false;
507
+ this._configProvider = configProvider;
508
+ this._acquireLock = acquireLock;
509
+ this._releaseLock = releaseLock;
510
+ this._onStop = onStop;
511
+ this._channel = channel;
512
+ this._clientServices = new ClientServicesHost({
513
+ callbacks: {
514
+ onReset: async () => this.stop()
515
+ }
516
+ });
517
+ }
518
+ get host() {
519
+ return this._clientServices;
520
+ }
521
+ async start() {
522
+ log3("starting...", void 0, {
523
+ F: __dxlog_file3,
524
+ L: 84,
525
+ S: this,
526
+ C: (f, a) => f(...a)
527
+ });
528
+ try {
529
+ this._broadcastChannel = new BroadcastChannel(this._channel);
530
+ this._broadcastChannel.postMessage({
531
+ action: "stop"
532
+ });
533
+ this._broadcastChannel.onmessage = async (event) => {
534
+ if (event.data?.action === "stop") {
535
+ await this.stop();
536
+ }
537
+ };
538
+ await this._acquireLock();
539
+ this._config = await this._configProvider();
540
+ const signals = this._config.get("runtime.services.signaling");
541
+ this._clientServices.initialize({
542
+ config: this._config,
543
+ signalManager: this._config.get("runtime.client.edgeFeatures")?.signaling ? void 0 : signals ? new WebsocketSignalManager(signals, () => this._signalTelemetryEnabled ? this._signalMetadataTags : {}) : new MemorySignalManager(new MemorySignalManagerContext()),
544
+ transportFactory: this._transportFactory
545
+ });
546
+ await this._clientServices.open(new Context(void 0, {
547
+ F: __dxlog_file3,
548
+ L: 107
549
+ }));
550
+ this._ready.wake(void 0);
551
+ log3("started", void 0, {
552
+ F: __dxlog_file3,
553
+ L: 109,
554
+ S: this,
555
+ C: (f, a) => f(...a)
556
+ });
557
+ setIdentityTags({
558
+ identityService: this._clientServices.services.IdentityService,
559
+ devicesService: this._clientServices.services.DevicesService,
560
+ setTag: (k, v) => {
561
+ this._signalMetadataTags[k] = v;
562
+ }
563
+ });
564
+ } catch (err) {
565
+ this._ready.wake(err);
566
+ log3.error("starting", err, {
567
+ F: __dxlog_file3,
568
+ L: 119,
569
+ S: this,
570
+ C: (f, a) => f(...a)
571
+ });
572
+ }
573
+ }
574
+ async stop() {
575
+ this._releaseLock();
576
+ this._broadcastChannel?.close();
577
+ this._broadcastChannel = void 0;
578
+ await this._clientServices.close();
579
+ await this._onStop?.();
580
+ }
581
+ /**
582
+ * Create a new session.
583
+ */
584
+ async createSession({ appPort, systemPort, shellPort }) {
585
+ const session = new WorkerSession({
586
+ serviceHost: this._clientServices,
587
+ appPort,
588
+ systemPort,
589
+ shellPort,
590
+ readySignal: this._ready
591
+ });
592
+ session.onClose.set(async () => {
593
+ this._sessions.delete(session);
594
+ if (this._sessions.size === 0) {
595
+ await this.stop();
596
+ } else {
597
+ this._reconnectWebrtc();
598
+ }
599
+ });
600
+ await session.open();
601
+ invariant3(!this._signalMetadataTags.origin || this._signalMetadataTags.origin === session.origin, `worker origin changed from ${this._signalMetadataTags.origin} to ${session.origin}?`, {
602
+ F: __dxlog_file3,
603
+ L: 157,
604
+ S: this,
605
+ A: [
606
+ "!this._signalMetadataTags.origin || this._signalMetadataTags.origin === session.origin",
607
+ "`worker origin changed from ${this._signalMetadataTags.origin} to ${session.origin}?`"
608
+ ]
609
+ });
610
+ if (session.observabilityGroup) {
611
+ this._signalMetadataTags.group = session.observabilityGroup;
612
+ }
613
+ this._signalTelemetryEnabled = session.signalTelemetryEnabled ?? false;
614
+ this._signalMetadataTags.origin = session.origin;
615
+ this._sessions.add(session);
616
+ this._reconnectWebrtc();
617
+ }
618
+ /**
619
+ * Selects one of the existing session for WebRTC networking.
620
+ */
621
+ _reconnectWebrtc() {
622
+ log3("reconnecting webrtc...", void 0, {
623
+ F: __dxlog_file3,
624
+ L: 175,
625
+ S: this,
626
+ C: (f, a) => f(...a)
627
+ });
628
+ if (this._sessionForNetworking) {
629
+ if (!this._sessions.has(this._sessionForNetworking)) {
630
+ this._sessionForNetworking = void 0;
631
+ }
632
+ }
633
+ if (!this._sessionForNetworking) {
634
+ const selected = Array.from(this._sessions).find((session) => session.bridgeService);
635
+ if (selected) {
636
+ this._sessionForNetworking = selected;
637
+ this._transportFactory.setBridgeService(selected.bridgeService);
638
+ } else {
639
+ this._transportFactory.setBridgeService(void 0);
640
+ }
641
+ }
642
+ }
643
+ };
644
+ export {
645
+ ClientRpcServer,
646
+ ClientServicesHost,
647
+ DataSpace,
648
+ DataSpaceManager,
649
+ DeviceInvitationProtocol,
650
+ DevtoolsHostEvents,
651
+ DevtoolsServiceImpl,
652
+ DiagnosticsCollector,
653
+ EdgeAgentManager,
654
+ EdgeAgentServiceImpl,
655
+ EdgeFeedReplicator,
656
+ Identity,
657
+ IdentityManager,
658
+ IdentityServiceImpl,
659
+ InvitationsHandler,
660
+ InvitationsManager,
661
+ InvitationsServiceImpl,
662
+ Lock,
663
+ ServiceContext,
664
+ ServiceRegistry,
665
+ SpaceInvitationProtocol,
666
+ SpacesServiceImpl,
667
+ TrustedKeySetAuthVerifier,
668
+ WorkerRuntime,
669
+ WorkerSession,
670
+ createAdmissionKeypair,
671
+ createAuthProvider,
672
+ createCollectDiagnosticsBroadcastHandler,
673
+ createCollectDiagnosticsBroadcastSender,
674
+ createDiagnostics,
675
+ createLevel,
676
+ createStorageObjects,
677
+ decodeProfileArchive,
678
+ encodeProfileArchive,
679
+ exportProfileData,
680
+ getNetworkPeers,
681
+ importProfileData,
682
+ isLocked,
683
+ subscribeToFeedBlocks,
684
+ subscribeToFeeds,
685
+ subscribeToNetworkStatus,
686
+ subscribeToNetworkTopics,
687
+ subscribeToSignal,
688
+ subscribeToSpaces,
689
+ subscribeToSwarmInfo
690
+ };
691
+ //# sourceMappingURL=index.mjs.map