@dxos/edge-client 0.8.4-main.84f28bd → 0.8.4-main.8baae0fced

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 (57) hide show
  1. package/LICENSE +102 -5
  2. package/dist/lib/{browser/chunk-LMP5TVOP.mjs → neutral/chunk-ZIQ5T3A7.mjs} +13 -43
  3. package/dist/lib/{browser/chunk-LMP5TVOP.mjs.map → neutral/chunk-ZIQ5T3A7.mjs.map} +3 -3
  4. package/dist/lib/{browser → neutral}/edge-ws-muxer.mjs +1 -1
  5. package/dist/lib/neutral/index.mjs +1238 -0
  6. package/dist/lib/neutral/index.mjs.map +7 -0
  7. package/dist/lib/neutral/meta.json +1 -0
  8. package/dist/lib/{browser → neutral}/testing/index.mjs +6 -31
  9. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  10. package/dist/types/src/auth.d.ts.map +1 -1
  11. package/dist/types/src/edge-client.d.ts +18 -15
  12. package/dist/types/src/edge-client.d.ts.map +1 -1
  13. package/dist/types/src/edge-http-client.d.ts +114 -21
  14. package/dist/types/src/edge-http-client.d.ts.map +1 -1
  15. package/dist/types/src/edge-identity.d.ts.map +1 -1
  16. package/dist/types/src/edge-ws-connection.d.ts +21 -0
  17. package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
  18. package/dist/types/src/edge-ws-muxer.d.ts.map +1 -1
  19. package/dist/types/src/errors.d.ts.map +1 -1
  20. package/dist/types/src/http-client.d.ts +10 -7
  21. package/dist/types/src/http-client.d.ts.map +1 -1
  22. package/dist/types/src/index.d.ts +4 -3
  23. package/dist/types/src/index.d.ts.map +1 -1
  24. package/dist/types/src/protocol.d.ts +1 -1
  25. package/dist/types/src/protocol.d.ts.map +1 -1
  26. package/dist/types/src/testing/test-server.d.ts.map +1 -1
  27. package/dist/types/src/testing/test-utils.d.ts +3 -3
  28. package/dist/types/src/testing/test-utils.d.ts.map +1 -1
  29. package/dist/types/src/utils.d.ts +1 -1
  30. package/dist/types/src/utils.d.ts.map +1 -1
  31. package/dist/types/tsconfig.tsbuildinfo +1 -1
  32. package/package.json +32 -32
  33. package/src/edge-client.test.ts +20 -15
  34. package/src/edge-client.ts +90 -43
  35. package/src/edge-http-client.test.ts +3 -2
  36. package/src/edge-http-client.ts +462 -70
  37. package/src/edge-ws-connection.ts +131 -9
  38. package/src/edge-ws-muxer.ts +1 -1
  39. package/src/http-client.test.ts +11 -8
  40. package/src/http-client.ts +18 -8
  41. package/src/index.ts +4 -3
  42. package/src/testing/test-utils.ts +8 -8
  43. package/src/websocket.test.ts +1 -1
  44. package/dist/lib/browser/index.mjs +0 -1089
  45. package/dist/lib/browser/index.mjs.map +0 -7
  46. package/dist/lib/browser/meta.json +0 -1
  47. package/dist/lib/browser/testing/index.mjs.map +0 -7
  48. package/dist/lib/node-esm/chunk-X7J46ISZ.mjs +0 -299
  49. package/dist/lib/node-esm/chunk-X7J46ISZ.mjs.map +0 -7
  50. package/dist/lib/node-esm/edge-ws-muxer.mjs +0 -12
  51. package/dist/lib/node-esm/edge-ws-muxer.mjs.map +0 -7
  52. package/dist/lib/node-esm/index.mjs +0 -1090
  53. package/dist/lib/node-esm/index.mjs.map +0 -7
  54. package/dist/lib/node-esm/meta.json +0 -1
  55. package/dist/lib/node-esm/testing/index.mjs +0 -186
  56. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  57. /package/dist/lib/{browser → neutral}/edge-ws-muxer.mjs.map +0 -0
@@ -1,1090 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- CLOUDFLARE_MESSAGE_MAX_BYTES,
4
- CLOUDFLARE_RPC_MAX_BYTES,
5
- Protocol,
6
- WebSocketMuxer,
7
- getTypename,
8
- protocol,
9
- toUint8Array
10
- } from "./chunk-X7J46ISZ.mjs";
11
-
12
- // src/index.ts
13
- export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
14
-
15
- // src/edge-client.ts
16
- import { Trigger, scheduleMicroTask, TriggerState, PersistentLifecycle, Event } from "@dxos/async";
17
- import { Resource as Resource2 } from "@dxos/context";
18
- import { log as log2, logInfo as logInfo2 } from "@dxos/log";
19
- import { EdgeStatus } from "@dxos/protocols/proto/dxos/client/services";
20
-
21
- // src/edge-identity.ts
22
- import { invariant } from "@dxos/invariant";
23
- import { schema } from "@dxos/protocols/proto";
24
- var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
25
- var handleAuthChallenge = async (failedResponse, identity) => {
26
- invariant(failedResponse.status === 401, void 0, {
27
- F: __dxlog_file,
28
- L: 21,
29
- S: void 0,
30
- A: [
31
- "failedResponse.status === 401",
32
- ""
33
- ]
34
- });
35
- const headerValue = failedResponse.headers.get("Www-Authenticate");
36
- invariant(headerValue?.startsWith("VerifiablePresentation challenge="), void 0, {
37
- F: __dxlog_file,
38
- L: 24,
39
- S: void 0,
40
- A: [
41
- "headerValue?.startsWith('VerifiablePresentation challenge=')",
42
- ""
43
- ]
44
- });
45
- const challenge = headerValue?.slice("VerifiablePresentation challenge=".length);
46
- invariant(challenge, void 0, {
47
- F: __dxlog_file,
48
- L: 27,
49
- S: void 0,
50
- A: [
51
- "challenge",
52
- ""
53
- ]
54
- });
55
- const presentation = await identity.presentCredentials({
56
- challenge: Buffer.from(challenge, "base64")
57
- });
58
- return schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
59
- };
60
-
61
- // src/edge-ws-connection.ts
62
- import WebSocket from "isomorphic-ws";
63
- import { scheduleTask, scheduleTaskInterval } from "@dxos/async";
64
- import { Context, Resource } from "@dxos/context";
65
- import { invariant as invariant2 } from "@dxos/invariant";
66
- import { log, logInfo } from "@dxos/log";
67
- import { EdgeWebsocketProtocol } from "@dxos/protocols";
68
- import { buf } from "@dxos/protocols/buf";
69
- import { MessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
70
- function _ts_decorate(decorators, target, key, desc) {
71
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
72
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
73
- 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;
74
- return c > 3 && r && Object.defineProperty(target, key, r), r;
75
- }
76
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-connection.ts";
77
- var SIGNAL_KEEPALIVE_INTERVAL = 4e3;
78
- var SIGNAL_KEEPALIVE_TIMEOUT = 12e3;
79
- var EdgeWsConnection = class extends Resource {
80
- constructor(_identity, _connectionInfo, _callbacks) {
81
- super(), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks;
82
- }
83
- get info() {
84
- return {
85
- open: this.isOpen,
86
- identity: this._identity.identityKey,
87
- device: this._identity.peerKey
88
- };
89
- }
90
- send(message) {
91
- invariant2(this._ws, void 0, {
92
- F: __dxlog_file2,
93
- L: 52,
94
- S: this,
95
- A: [
96
- "this._ws",
97
- ""
98
- ]
99
- });
100
- invariant2(this._wsMuxer, void 0, {
101
- F: __dxlog_file2,
102
- L: 53,
103
- S: this,
104
- A: [
105
- "this._wsMuxer",
106
- ""
107
- ]
108
- });
109
- log("sending...", {
110
- peerKey: this._identity.peerKey,
111
- payload: protocol.getPayloadType(message)
112
- }, {
113
- F: __dxlog_file2,
114
- L: 54,
115
- S: this,
116
- C: (f, a) => f(...a)
117
- });
118
- if (this._ws?.protocol.includes(EdgeWebsocketProtocol.V0)) {
119
- const binary = buf.toBinary(MessageSchema, message);
120
- if (binary.length > CLOUDFLARE_MESSAGE_MAX_BYTES) {
121
- log.error("Message dropped because it was too large (>1MB).", {
122
- byteLength: binary.byteLength,
123
- serviceId: message.serviceId,
124
- payload: protocol.getPayloadType(message)
125
- }, {
126
- F: __dxlog_file2,
127
- L: 58,
128
- S: this,
129
- C: (f, a) => f(...a)
130
- });
131
- return;
132
- }
133
- this._ws.send(binary);
134
- } else {
135
- this._wsMuxer.send(message).catch((e) => log.catch(e, void 0, {
136
- F: __dxlog_file2,
137
- L: 67,
138
- S: this,
139
- C: (f, a) => f(...a)
140
- }));
141
- }
142
- }
143
- async _open() {
144
- const baseProtocols = [
145
- ...Object.values(EdgeWebsocketProtocol)
146
- ];
147
- this._ws = new WebSocket(this._connectionInfo.url.toString(), this._connectionInfo.protocolHeader ? [
148
- ...baseProtocols,
149
- this._connectionInfo.protocolHeader
150
- ] : [
151
- ...baseProtocols
152
- ]);
153
- const muxer = new WebSocketMuxer(this._ws);
154
- this._wsMuxer = muxer;
155
- this._ws.onopen = () => {
156
- if (this.isOpen) {
157
- log("connected", void 0, {
158
- F: __dxlog_file2,
159
- L: 84,
160
- S: this,
161
- C: (f, a) => f(...a)
162
- });
163
- this._callbacks.onConnected();
164
- this._scheduleHeartbeats();
165
- } else {
166
- log.verbose("connected after becoming inactive", {
167
- currentIdentity: this._identity
168
- }, {
169
- F: __dxlog_file2,
170
- L: 88,
171
- S: this,
172
- C: (f, a) => f(...a)
173
- });
174
- }
175
- };
176
- this._ws.onclose = (event) => {
177
- if (this.isOpen) {
178
- log.warn("disconnected while being open", {
179
- code: event.code,
180
- reason: event.reason
181
- }, {
182
- F: __dxlog_file2,
183
- L: 93,
184
- S: this,
185
- C: (f, a) => f(...a)
186
- });
187
- this._callbacks.onRestartRequired();
188
- muxer.destroy();
189
- }
190
- };
191
- this._ws.onerror = (event) => {
192
- if (this.isOpen) {
193
- log.warn("edge connection socket error", {
194
- error: event.error,
195
- info: event.message
196
- }, {
197
- F: __dxlog_file2,
198
- L: 100,
199
- S: this,
200
- C: (f, a) => f(...a)
201
- });
202
- this._callbacks.onRestartRequired();
203
- } else {
204
- log.verbose("error ignored on closed connection", {
205
- error: event.error
206
- }, {
207
- F: __dxlog_file2,
208
- L: 103,
209
- S: this,
210
- C: (f, a) => f(...a)
211
- });
212
- }
213
- };
214
- this._ws.onmessage = async (event) => {
215
- if (!this.isOpen) {
216
- log.verbose("message ignored on closed connection", {
217
- event: event.type
218
- }, {
219
- F: __dxlog_file2,
220
- L: 111,
221
- S: this,
222
- C: (f, a) => f(...a)
223
- });
224
- return;
225
- }
226
- if (event.data === "__pong__") {
227
- this._rescheduleHeartbeatTimeout();
228
- return;
229
- }
230
- const bytes = await toUint8Array(event.data);
231
- if (!this.isOpen) {
232
- return;
233
- }
234
- const message = this._ws?.protocol?.includes(EdgeWebsocketProtocol.V0) ? buf.fromBinary(MessageSchema, bytes) : muxer.receiveData(bytes);
235
- if (message) {
236
- log("received", {
237
- from: message.source,
238
- payload: protocol.getPayloadType(message)
239
- }, {
240
- F: __dxlog_file2,
241
- L: 128,
242
- S: this,
243
- C: (f, a) => f(...a)
244
- });
245
- this._callbacks.onMessage(message);
246
- }
247
- };
248
- }
249
- async _close() {
250
- void this._inactivityTimeoutCtx?.dispose().catch(() => {
251
- });
252
- try {
253
- this._ws?.close();
254
- this._ws = void 0;
255
- this._wsMuxer?.destroy();
256
- this._wsMuxer = void 0;
257
- } catch (err) {
258
- if (err instanceof Error && err.message.includes("WebSocket is closed before the connection is established.")) {
259
- return;
260
- }
261
- log.warn("Error closing websocket", {
262
- err
263
- }, {
264
- F: __dxlog_file2,
265
- L: 146,
266
- S: this,
267
- C: (f, a) => f(...a)
268
- });
269
- }
270
- }
271
- _scheduleHeartbeats() {
272
- invariant2(this._ws, void 0, {
273
- F: __dxlog_file2,
274
- L: 151,
275
- S: this,
276
- A: [
277
- "this._ws",
278
- ""
279
- ]
280
- });
281
- scheduleTaskInterval(this._ctx, async () => {
282
- this._ws?.send("__ping__");
283
- }, SIGNAL_KEEPALIVE_INTERVAL);
284
- this._ws.send("__ping__");
285
- this._rescheduleHeartbeatTimeout();
286
- }
287
- _rescheduleHeartbeatTimeout() {
288
- if (!this.isOpen) {
289
- return;
290
- }
291
- void this._inactivityTimeoutCtx?.dispose();
292
- this._inactivityTimeoutCtx = new Context(void 0, {
293
- F: __dxlog_file2,
294
- L: 170
295
- });
296
- scheduleTask(this._inactivityTimeoutCtx, () => {
297
- if (this.isOpen) {
298
- log.warn("restart due to inactivity timeout", void 0, {
299
- F: __dxlog_file2,
300
- L: 175,
301
- S: this,
302
- C: (f, a) => f(...a)
303
- });
304
- this._callbacks.onRestartRequired();
305
- }
306
- }, SIGNAL_KEEPALIVE_TIMEOUT);
307
- }
308
- };
309
- _ts_decorate([
310
- logInfo
311
- ], EdgeWsConnection.prototype, "info", null);
312
-
313
- // src/errors.ts
314
- var EdgeConnectionClosedError = class extends Error {
315
- constructor() {
316
- super("Edge connection closed.");
317
- }
318
- };
319
- var EdgeIdentityChangedError = class extends Error {
320
- constructor() {
321
- super("Edge identity changed.");
322
- }
323
- };
324
-
325
- // src/utils.ts
326
- var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
327
- const isSecure = baseUrl.startsWith("https") || baseUrl.startsWith("wss");
328
- const url = new URL(baseUrl);
329
- url.protocol = protocol2 + (isSecure ? "s" : "");
330
- return url.toString();
331
- };
332
-
333
- // src/edge-client.ts
334
- function _ts_decorate2(decorators, target, key, desc) {
335
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
336
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
337
- 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;
338
- return c > 3 && r && Object.defineProperty(target, key, r), r;
339
- }
340
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
341
- var DEFAULT_TIMEOUT = 1e4;
342
- var EdgeClient = class extends Resource2 {
343
- constructor(_identity, _config) {
344
- super(), this._identity = _identity, this._config = _config, this.statusChanged = new Event(), this._persistentLifecycle = new PersistentLifecycle({
345
- start: async () => this._connect(),
346
- stop: async (state) => this._disconnect(state)
347
- }), this._messageListeners = /* @__PURE__ */ new Set(), this._reconnectListeners = /* @__PURE__ */ new Set(), this._currentConnection = void 0, this._ready = new Trigger(), this._isActive = (connection) => connection === this._currentConnection;
348
- this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
349
- this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
350
- }
351
- get info() {
352
- return {
353
- open: this.isOpen,
354
- status: this.status,
355
- identity: this._identity.identityKey,
356
- device: this._identity.peerKey
357
- };
358
- }
359
- get status() {
360
- return Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED ? EdgeStatus.CONNECTED : EdgeStatus.NOT_CONNECTED;
361
- }
362
- get identityKey() {
363
- return this._identity.identityKey;
364
- }
365
- get peerKey() {
366
- return this._identity.peerKey;
367
- }
368
- setIdentity(identity) {
369
- if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {
370
- log2("Edge identity changed", {
371
- identity,
372
- oldIdentity: this._identity
373
- }, {
374
- F: __dxlog_file3,
375
- L: 99,
376
- S: this,
377
- C: (f, a) => f(...a)
378
- });
379
- this._identity = identity;
380
- this._closeCurrentConnection(new EdgeIdentityChangedError());
381
- void this._persistentLifecycle.scheduleRestart();
382
- }
383
- }
384
- onMessage(listener) {
385
- this._messageListeners.add(listener);
386
- return () => this._messageListeners.delete(listener);
387
- }
388
- onReconnected(listener) {
389
- this._reconnectListeners.add(listener);
390
- if (this._ready.state === TriggerState.RESOLVED) {
391
- scheduleMicroTask(this._ctx, () => {
392
- if (this._reconnectListeners.has(listener)) {
393
- try {
394
- listener();
395
- } catch (error) {
396
- log2.catch(error, void 0, {
397
- F: __dxlog_file3,
398
- L: 121,
399
- S: this,
400
- C: (f, a) => f(...a)
401
- });
402
- }
403
- }
404
- });
405
- }
406
- return () => this._reconnectListeners.delete(listener);
407
- }
408
- /**
409
- * Open connection to messaging service.
410
- */
411
- async _open() {
412
- log2("opening...", {
413
- info: this.info
414
- }, {
415
- F: __dxlog_file3,
416
- L: 133,
417
- S: this,
418
- C: (f, a) => f(...a)
419
- });
420
- this._persistentLifecycle.open().catch((err) => {
421
- log2.warn("Error while opening connection", {
422
- err
423
- }, {
424
- F: __dxlog_file3,
425
- L: 135,
426
- S: this,
427
- C: (f, a) => f(...a)
428
- });
429
- });
430
- }
431
- /**
432
- * Close connection and free resources.
433
- */
434
- async _close() {
435
- log2("closing...", {
436
- peerKey: this._identity.peerKey
437
- }, {
438
- F: __dxlog_file3,
439
- L: 143,
440
- S: this,
441
- C: (f, a) => f(...a)
442
- });
443
- this._closeCurrentConnection();
444
- await this._persistentLifecycle.close();
445
- }
446
- async _connect() {
447
- if (this._ctx.disposed) {
448
- return void 0;
449
- }
450
- const identity = this._identity;
451
- const path = `/ws/${identity.identityKey}/${identity.peerKey}`;
452
- const protocolHeader = this._config.disableAuth ? void 0 : await this._createAuthHeader(path);
453
- if (this._identity !== identity) {
454
- log2("identity changed during auth header request", void 0, {
455
- F: __dxlog_file3,
456
- L: 157,
457
- S: this,
458
- C: (f, a) => f(...a)
459
- });
460
- return void 0;
461
- }
462
- const restartRequired = new Trigger();
463
- const url = new URL(path, this._baseWsUrl);
464
- log2("Opening websocket", {
465
- url: url.toString(),
466
- protocolHeader
467
- }, {
468
- F: __dxlog_file3,
469
- L: 163,
470
- S: this,
471
- C: (f, a) => f(...a)
472
- });
473
- const connection = new EdgeWsConnection(identity, {
474
- url,
475
- protocolHeader
476
- }, {
477
- onConnected: () => {
478
- if (this._isActive(connection)) {
479
- this._ready.wake();
480
- this._notifyReconnected();
481
- } else {
482
- log2.verbose("connected callback ignored, because connection is not active", void 0, {
483
- F: __dxlog_file3,
484
- L: 173,
485
- S: this,
486
- C: (f, a) => f(...a)
487
- });
488
- }
489
- },
490
- onRestartRequired: () => {
491
- if (this._isActive(connection)) {
492
- this._closeCurrentConnection();
493
- void this._persistentLifecycle.scheduleRestart();
494
- } else {
495
- log2.verbose("restart requested by inactive connection", void 0, {
496
- F: __dxlog_file3,
497
- L: 181,
498
- S: this,
499
- C: (f, a) => f(...a)
500
- });
501
- }
502
- restartRequired.wake();
503
- },
504
- onMessage: (message) => {
505
- if (this._isActive(connection)) {
506
- this._notifyMessageReceived(message);
507
- } else {
508
- log2.verbose("ignored a message on inactive connection", {
509
- from: message.source,
510
- type: message.payload?.typeUrl
511
- }, {
512
- F: __dxlog_file3,
513
- L: 189,
514
- S: this,
515
- C: (f, a) => f(...a)
516
- });
517
- }
518
- }
519
- });
520
- this._currentConnection = connection;
521
- await connection.open();
522
- await Promise.race([
523
- this._ready.wait({
524
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
525
- }),
526
- restartRequired
527
- ]);
528
- return connection;
529
- }
530
- async _disconnect(state) {
531
- await state.close();
532
- this.statusChanged.emit(this.status);
533
- }
534
- _closeCurrentConnection(error = new EdgeConnectionClosedError()) {
535
- this._currentConnection = void 0;
536
- this._ready.throw(error);
537
- this._ready.reset();
538
- this.statusChanged.emit(this.status);
539
- }
540
- _notifyReconnected() {
541
- this.statusChanged.emit(this.status);
542
- for (const listener of this._reconnectListeners) {
543
- try {
544
- listener();
545
- } catch (err) {
546
- log2.error("ws reconnect listener failed", {
547
- err
548
- }, {
549
- F: __dxlog_file3,
550
- L: 225,
551
- S: this,
552
- C: (f, a) => f(...a)
553
- });
554
- }
555
- }
556
- }
557
- _notifyMessageReceived(message) {
558
- for (const listener of this._messageListeners) {
559
- try {
560
- listener(message);
561
- } catch (err) {
562
- log2.error("ws incoming message processing failed", {
563
- err,
564
- payload: protocol.getPayloadType(message)
565
- }, {
566
- F: __dxlog_file3,
567
- L: 235,
568
- S: this,
569
- C: (f, a) => f(...a)
570
- });
571
- }
572
- }
573
- }
574
- /**
575
- * Send message.
576
- * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.
577
- */
578
- async send(message) {
579
- if (this._ready.state !== TriggerState.RESOLVED) {
580
- log2("waiting for websocket to become ready", void 0, {
581
- F: __dxlog_file3,
582
- L: 246,
583
- S: this,
584
- C: (f, a) => f(...a)
585
- });
586
- await this._ready.wait({
587
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
588
- });
589
- }
590
- if (!this._currentConnection) {
591
- throw new EdgeConnectionClosedError();
592
- }
593
- if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
594
- throw new EdgeIdentityChangedError();
595
- }
596
- this._currentConnection.send(message);
597
- }
598
- async _createAuthHeader(path) {
599
- const httpUrl = new URL(path, this._baseHttpUrl);
600
- httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), "http");
601
- const response = await fetch(httpUrl, {
602
- method: "GET"
603
- });
604
- if (response.status === 401) {
605
- return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));
606
- } else {
607
- log2.warn("no auth challenge from edge", {
608
- status: response.status,
609
- statusText: response.statusText
610
- }, {
611
- F: __dxlog_file3,
612
- L: 271,
613
- S: this,
614
- C: (f, a) => f(...a)
615
- });
616
- return void 0;
617
- }
618
- }
619
- };
620
- _ts_decorate2([
621
- logInfo2
622
- ], EdgeClient.prototype, "info", null);
623
- var encodePresentationWsAuthHeader = (encodedPresentation) => {
624
- const encodedToken = Buffer.from(encodedPresentation).toString("base64").replace(/=*$/, "").replaceAll("/", "|");
625
- return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
626
- };
627
-
628
- // src/auth.ts
629
- import { createCredential, signPresentation } from "@dxos/credentials";
630
- import { invariant as invariant3 } from "@dxos/invariant";
631
- import { Keyring } from "@dxos/keyring";
632
- import { PublicKey } from "@dxos/keys";
633
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/auth.ts";
634
- var createDeviceEdgeIdentity = async (signer, key) => {
635
- return {
636
- identityKey: key.toHex(),
637
- peerKey: key.toHex(),
638
- presentCredentials: async ({ challenge }) => {
639
- return signPresentation({
640
- presentation: {
641
- credentials: [
642
- // Verifier requires at least one credential in the presentation to establish the subject.
643
- await createCredential({
644
- assertion: {
645
- "@type": "dxos.halo.credentials.Auth"
646
- },
647
- issuer: key,
648
- subject: key,
649
- signer
650
- })
651
- ]
652
- },
653
- signer,
654
- signerKey: key,
655
- nonce: challenge
656
- });
657
- }
658
- };
659
- };
660
- var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
661
- const credentialsToSign = credentials.length > 0 ? credentials : [
662
- await createCredential({
663
- assertion: {
664
- "@type": "dxos.halo.credentials.Auth"
665
- },
666
- issuer: identityKey,
667
- subject: identityKey,
668
- signer,
669
- chain,
670
- signingKey: peerKey
671
- })
672
- ];
673
- return {
674
- identityKey: identityKey.toHex(),
675
- peerKey: peerKey.toHex(),
676
- presentCredentials: async ({ challenge }) => {
677
- invariant3(chain, void 0, {
678
- F: __dxlog_file4,
679
- L: 75,
680
- S: void 0,
681
- A: [
682
- "chain",
683
- ""
684
- ]
685
- });
686
- return signPresentation({
687
- presentation: {
688
- credentials: credentialsToSign
689
- },
690
- signer,
691
- nonce: challenge,
692
- signerKey: peerKey,
693
- chain
694
- });
695
- }
696
- };
697
- };
698
- var createEphemeralEdgeIdentity = async () => {
699
- const keyring = new Keyring();
700
- const key = await keyring.createKey();
701
- return createDeviceEdgeIdentity(keyring, key);
702
- };
703
- var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
704
- const deviceAdmission = await createCredential({
705
- assertion: {
706
- "@type": "dxos.halo.credentials.AuthorizedDevice",
707
- deviceKey,
708
- identityKey
709
- },
710
- issuer: identityKey,
711
- subject: deviceKey,
712
- signer
713
- });
714
- return createChainEdgeIdentity(signer, identityKey, deviceKey, {
715
- credential: deviceAdmission
716
- }, [
717
- await createCredential({
718
- assertion: {
719
- "@type": "dxos.halo.credentials.Auth"
720
- },
721
- issuer: identityKey,
722
- subject: identityKey,
723
- signer
724
- })
725
- ]);
726
- };
727
- var createStubEdgeIdentity = () => {
728
- const identityKey = PublicKey.random();
729
- const deviceKey = PublicKey.random();
730
- return {
731
- identityKey: identityKey.toHex(),
732
- peerKey: deviceKey.toHex(),
733
- presentCredentials: async () => {
734
- throw new Error("Stub identity does not support authentication.");
735
- }
736
- };
737
- };
738
-
739
- // src/edge-http-client.ts
740
- import { FetchHttpClient, HttpClient } from "@effect/platform";
741
- import { Effect as Effect2, pipe } from "effect";
742
- import { sleep } from "@dxos/async";
743
- import { Context as Context3 } from "@dxos/context";
744
- import { log as log4 } from "@dxos/log";
745
- import { EdgeAuthChallengeError, EdgeCallFailedError } from "@dxos/protocols";
746
- import { createUrl } from "@dxos/util";
747
-
748
- // src/http-client.ts
749
- import { Context as Context2, Duration, Effect, Layer, Schedule } from "effect";
750
- import { log as log3 } from "@dxos/log";
751
- var __dxlog_file5 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/http-client.ts";
752
- var HttpConfig = class _HttpConfig extends Context2.Tag("HttpConfig")() {
753
- static {
754
- this.default = Layer.succeed(_HttpConfig, {
755
- timeout: Duration.millis(1e3),
756
- retryTimes: 3,
757
- retryBaseDelay: Duration.millis(1e3)
758
- });
759
- }
760
- };
761
- var withRetry = (effect, { timeout = Duration.millis(1e3), retryBaseDelay = Duration.millis(1e3), retryTimes = 3 } = {}) => {
762
- return effect.pipe(Effect.flatMap((res) => (
763
- // Treat 500 errors as retryable?
764
- res.status === 500 ? Effect.fail(new Error(res.status.toString())) : res.json
765
- )), Effect.timeout(timeout), Effect.retry({
766
- schedule: Schedule.exponential(retryBaseDelay).pipe(Schedule.jittered),
767
- times: retryTimes
768
- }));
769
- };
770
- var withRetryConfig = (effect) => Effect.gen(function* () {
771
- const config = yield* HttpConfig;
772
- return yield* withRetry(effect, config);
773
- });
774
- var withLogging = (effect) => effect.pipe(Effect.tap((res) => log3.info("response", {
775
- status: res.status
776
- }, {
777
- F: __dxlog_file5,
778
- L: 58,
779
- S: void 0,
780
- C: (f, a) => f(...a)
781
- })));
782
- var encodeAuthHeader = (challenge) => {
783
- const encodedChallenge = Buffer.from(challenge).toString("base64");
784
- return `VerifiablePresentation pb;base64,${encodedChallenge}`;
785
- };
786
-
787
- // src/edge-http-client.ts
788
- var __dxlog_file6 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
789
- var DEFAULT_RETRY_TIMEOUT = 1500;
790
- var DEFAULT_RETRY_JITTER = 500;
791
- var DEFAULT_MAX_RETRIES_COUNT = 3;
792
- var EdgeHttpClient = class {
793
- constructor(baseUrl) {
794
- this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
795
- log4("created", {
796
- url: this._baseUrl
797
- }, {
798
- F: __dxlog_file6,
799
- L: 84,
800
- S: this,
801
- C: (f, a) => f(...a)
802
- });
803
- }
804
- get baseUrl() {
805
- return this._baseUrl;
806
- }
807
- setIdentity(identity) {
808
- if (this._edgeIdentity?.identityKey !== identity.identityKey || this._edgeIdentity?.peerKey !== identity.peerKey) {
809
- this._edgeIdentity = identity;
810
- this._authHeader = void 0;
811
- }
812
- }
813
- //
814
- // Status
815
- //
816
- async getStatus(args) {
817
- return this._call(new URL("/status", this.baseUrl), {
818
- ...args,
819
- method: "GET"
820
- });
821
- }
822
- //
823
- // Agents
824
- //
825
- createAgent(body, args) {
826
- return this._call(new URL("/agents/create", this.baseUrl), {
827
- ...args,
828
- method: "POST",
829
- body
830
- });
831
- }
832
- getAgentStatus(request, args) {
833
- return this._call(new URL(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, this.baseUrl), {
834
- ...args,
835
- method: "GET"
836
- });
837
- }
838
- //
839
- // Credentials
840
- //
841
- getCredentialsForNotarization(spaceId, args) {
842
- return this._call(new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), {
843
- ...args,
844
- method: "GET"
845
- });
846
- }
847
- async notarizeCredentials(spaceId, body, args) {
848
- await this._call(new URL(`/spaces/${spaceId}/notarization`, this.baseUrl), {
849
- ...args,
850
- body,
851
- method: "POST"
852
- });
853
- }
854
- //
855
- // Identity
856
- //
857
- async recoverIdentity(body, args) {
858
- return this._call(new URL("/identity/recover", this.baseUrl), {
859
- ...args,
860
- body,
861
- method: "POST"
862
- });
863
- }
864
- //
865
- // Invitations
866
- //
867
- async joinSpaceByInvitation(spaceId, body, args) {
868
- return this._call(new URL(`/spaces/${spaceId}/join`, this.baseUrl), {
869
- ...args,
870
- body,
871
- method: "POST"
872
- });
873
- }
874
- //
875
- // OAuth and credentials
876
- //
877
- async initiateOAuthFlow(body, args) {
878
- return this._call(new URL("/oauth/initiate", this.baseUrl), {
879
- ...args,
880
- body,
881
- method: "POST"
882
- });
883
- }
884
- //
885
- // Spaces
886
- //
887
- async createSpace(body, args) {
888
- return this._call(new URL("/spaces/create", this.baseUrl), {
889
- ...args,
890
- body,
891
- method: "POST"
892
- });
893
- }
894
- //
895
- // Queues
896
- //
897
- async queryQueue(subspaceTag, spaceId, query, args) {
898
- const { queueId } = query;
899
- return this._call(createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query`, this.baseUrl), {
900
- after: query.after,
901
- before: query.before,
902
- limit: query.limit,
903
- reverse: query.reverse,
904
- objectIds: query.objectIds?.join(",")
905
- }), {
906
- ...args,
907
- method: "GET"
908
- });
909
- }
910
- async insertIntoQueue(subspaceTag, spaceId, queueId, objects, args) {
911
- return this._call(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {
912
- ...args,
913
- body: {
914
- objects
915
- },
916
- method: "POST"
917
- });
918
- }
919
- async deleteFromQueue(subspaceTag, spaceId, queueId, objectIds, args) {
920
- return this._call(createUrl(new URL(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, this.baseUrl), {
921
- ids: objectIds.join(",")
922
- }), {
923
- ...args,
924
- method: "DELETE"
925
- });
926
- }
927
- //
928
- // Functions
929
- //
930
- async uploadFunction(pathParts, body, args) {
931
- const path = [
932
- "functions",
933
- ...pathParts.functionId ? [
934
- pathParts.functionId
935
- ] : []
936
- ].join("/");
937
- return this._call(new URL(path, this.baseUrl), {
938
- ...args,
939
- body,
940
- method: "PUT"
941
- });
942
- }
943
- //
944
- // Workflows
945
- //
946
- async executeWorkflow(spaceId, graphId, input, args) {
947
- return this._call(new URL(`/workflows/${spaceId}/${graphId}`, this.baseUrl), {
948
- ...args,
949
- body: input,
950
- method: "POST"
951
- });
952
- }
953
- //
954
- // Internal
955
- //
956
- async _fetch(url, args) {
957
- return pipe(HttpClient.get(url), withLogging, withRetryConfig, Effect2.provide(FetchHttpClient.layer), Effect2.provide(HttpConfig.default), Effect2.withSpan("EdgeHttpClient"), Effect2.runPromise);
958
- }
959
- // TODO(burdon): Refactor with effect (see edge-http-client.test.ts).
960
- async _call(url, args) {
961
- const shouldRetry = createRetryHandler(args);
962
- const requestContext = args.context ?? new Context3(void 0, {
963
- F: __dxlog_file6,
964
- L: 289
965
- });
966
- log4("fetch", {
967
- url,
968
- request: args.body
969
- }, {
970
- F: __dxlog_file6,
971
- L: 290,
972
- S: this,
973
- C: (f, a) => f(...a)
974
- });
975
- let handledAuth = false;
976
- while (true) {
977
- let processingError;
978
- let retryAfterHeaderValue = Number.NaN;
979
- try {
980
- const request = createRequest(args, this._authHeader);
981
- const response = await fetch(url, request);
982
- retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
983
- if (response.ok) {
984
- const body = await response.json();
985
- if (body.success) {
986
- return body.data;
987
- }
988
- log4.warn("unsuccessful edge response", {
989
- url,
990
- body
991
- }, {
992
- F: __dxlog_file6,
993
- L: 306,
994
- S: this,
995
- C: (f, a) => f(...a)
996
- });
997
- if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
998
- processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
999
- } else {
1000
- processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
1001
- }
1002
- } else if (response.status === 401 && !handledAuth) {
1003
- this._authHeader = await this._handleUnauthorized(response);
1004
- handledAuth = true;
1005
- continue;
1006
- } else {
1007
- processingError = EdgeCallFailedError.fromHttpFailure(response);
1008
- }
1009
- } catch (error) {
1010
- processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
1011
- }
1012
- if (processingError.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
1013
- log4("retrying edge request", {
1014
- url,
1015
- processingError
1016
- }, {
1017
- F: __dxlog_file6,
1018
- L: 324,
1019
- S: this,
1020
- C: (f, a) => f(...a)
1021
- });
1022
- } else {
1023
- throw processingError;
1024
- }
1025
- }
1026
- }
1027
- async _handleUnauthorized(response) {
1028
- if (!this._edgeIdentity) {
1029
- log4.warn("unauthorized response received before identity was set", void 0, {
1030
- F: __dxlog_file6,
1031
- L: 333,
1032
- S: this,
1033
- C: (f, a) => f(...a)
1034
- });
1035
- throw EdgeCallFailedError.fromHttpFailure(response);
1036
- }
1037
- const challenge = await handleAuthChallenge(response, this._edgeIdentity);
1038
- return encodeAuthHeader(challenge);
1039
- }
1040
- };
1041
- var createRequest = ({ method, body }, authHeader) => {
1042
- return {
1043
- method,
1044
- body: body && JSON.stringify(body),
1045
- headers: authHeader ? {
1046
- Authorization: authHeader
1047
- } : void 0
1048
- };
1049
- };
1050
- var createRetryHandler = ({ retry }) => {
1051
- if (!retry || retry.count < 1) {
1052
- return async () => false;
1053
- }
1054
- let retries = 0;
1055
- const maxRetries = retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
1056
- const baseTimeout = retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
1057
- const jitter = retry.jitter ?? DEFAULT_RETRY_JITTER;
1058
- return async (ctx, retryAfter) => {
1059
- if (++retries > maxRetries || ctx.disposed) {
1060
- return false;
1061
- }
1062
- if (retryAfter) {
1063
- await sleep(retryAfter);
1064
- } else {
1065
- const timeout = baseTimeout + Math.random() * jitter;
1066
- await sleep(timeout);
1067
- }
1068
- return true;
1069
- };
1070
- };
1071
- export {
1072
- CLOUDFLARE_MESSAGE_MAX_BYTES,
1073
- CLOUDFLARE_RPC_MAX_BYTES,
1074
- EdgeClient,
1075
- EdgeConnectionClosedError,
1076
- EdgeHttpClient,
1077
- EdgeIdentityChangedError,
1078
- Protocol,
1079
- WebSocketMuxer,
1080
- createChainEdgeIdentity,
1081
- createDeviceEdgeIdentity,
1082
- createEphemeralEdgeIdentity,
1083
- createStubEdgeIdentity,
1084
- createTestHaloEdgeIdentity,
1085
- getTypename,
1086
- handleAuthChallenge,
1087
- protocol,
1088
- toUint8Array
1089
- };
1090
- //# sourceMappingURL=index.mjs.map