@dxos/client-services 0.4.9 → 0.4.10-main.068c3d8

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 (106) hide show
  1. package/dist/lib/browser/{chunk-RQ33OGAG.mjs → chunk-U3AY6WTI.mjs} +1358 -991
  2. package/dist/lib/browser/chunk-U3AY6WTI.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +62 -22
  4. package/dist/lib/browser/index.mjs.map +3 -3
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/packlets/testing/index.mjs +12 -5
  7. package/dist/lib/browser/packlets/testing/index.mjs.map +3 -3
  8. package/dist/lib/node/{chunk-CBSM4HU4.cjs → chunk-3ILFTQW5.cjs} +1181 -902
  9. package/dist/lib/node/chunk-3ILFTQW5.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +98 -58
  11. package/dist/lib/node/index.cjs.map +3 -3
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/packlets/testing/index.cjs +16 -9
  14. package/dist/lib/node/packlets/testing/index.cjs.map +3 -3
  15. package/dist/types/src/index.d.ts +1 -0
  16. package/dist/types/src/index.d.ts.map +1 -1
  17. package/dist/types/src/packlets/diagnostics/browser-diagnostics-broadcast.d.ts +5 -0
  18. package/dist/types/src/packlets/diagnostics/browser-diagnostics-broadcast.d.ts.map +1 -0
  19. package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts +5 -0
  20. package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts.map +1 -0
  21. package/dist/types/src/packlets/diagnostics/diagnostics-collector.d.ts +15 -0
  22. package/dist/types/src/packlets/diagnostics/diagnostics-collector.d.ts.map +1 -0
  23. package/dist/types/src/packlets/{services → diagnostics}/diagnostics.d.ts +1 -1
  24. package/dist/types/src/packlets/diagnostics/diagnostics.d.ts.map +1 -0
  25. package/dist/types/src/packlets/diagnostics/index.d.ts +4 -0
  26. package/dist/types/src/packlets/diagnostics/index.d.ts.map +1 -0
  27. package/dist/types/src/packlets/indexing/util.d.ts +3 -2
  28. package/dist/types/src/packlets/indexing/util.d.ts.map +1 -1
  29. package/dist/types/src/packlets/invitations/index.d.ts +1 -0
  30. package/dist/types/src/packlets/invitations/index.d.ts.map +1 -1
  31. package/dist/types/src/packlets/invitations/invitation-extension.d.ts +1 -0
  32. package/dist/types/src/packlets/invitations/invitation-extension.d.ts.map +1 -1
  33. package/dist/types/src/packlets/invitations/invitations-handler.d.ts +4 -2
  34. package/dist/types/src/packlets/invitations/invitations-handler.d.ts.map +1 -1
  35. package/dist/types/src/packlets/invitations/invitations-manager.d.ts +42 -0
  36. package/dist/types/src/packlets/invitations/invitations-manager.d.ts.map +1 -0
  37. package/dist/types/src/packlets/invitations/invitations-service.d.ts +7 -23
  38. package/dist/types/src/packlets/invitations/invitations-service.d.ts.map +1 -1
  39. package/dist/types/src/packlets/services/index.d.ts +1 -1
  40. package/dist/types/src/packlets/services/index.d.ts.map +1 -1
  41. package/dist/types/src/packlets/services/service-context.d.ts +9 -5
  42. package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
  43. package/dist/types/src/packlets/services/service-host.d.ts +5 -1
  44. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  45. package/dist/types/src/packlets/services/util.d.ts +1 -0
  46. package/dist/types/src/packlets/services/util.d.ts.map +1 -1
  47. package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
  48. package/dist/types/src/packlets/storage/index.d.ts +1 -0
  49. package/dist/types/src/packlets/storage/index.d.ts.map +1 -1
  50. package/dist/types/src/packlets/storage/level.d.ts +4 -0
  51. package/dist/types/src/packlets/storage/level.d.ts.map +1 -0
  52. package/dist/types/src/packlets/storage/storage.d.ts.map +1 -1
  53. package/dist/types/src/packlets/storage/util.d.ts +4 -0
  54. package/dist/types/src/packlets/storage/util.d.ts.map +1 -0
  55. package/dist/types/src/packlets/system/system-service.d.ts +1 -1
  56. package/dist/types/src/packlets/system/system-service.d.ts.map +1 -1
  57. package/dist/types/src/packlets/testing/test-builder.d.ts +4 -2
  58. package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
  59. package/dist/types/src/packlets/vault/shared-worker-connection.d.ts +5 -5
  60. package/dist/types/src/packlets/vault/shared-worker-connection.d.ts.map +1 -1
  61. package/dist/types/src/packlets/vault/worker-runtime.d.ts +2 -0
  62. package/dist/types/src/packlets/vault/worker-runtime.d.ts.map +1 -1
  63. package/dist/types/src/packlets/vault/worker-session.d.ts +2 -0
  64. package/dist/types/src/packlets/vault/worker-session.d.ts.map +1 -1
  65. package/dist/types/src/version.d.ts +1 -1
  66. package/dist/types/src/version.d.ts.map +1 -1
  67. package/package.json +36 -34
  68. package/src/index.ts +1 -0
  69. package/src/packlets/devices/devices-service.test.ts +1 -1
  70. package/src/packlets/diagnostics/browser-diagnostics-broadcast.ts +94 -0
  71. package/src/packlets/diagnostics/diagnostics-broadcast.ts +20 -0
  72. package/src/packlets/diagnostics/diagnostics-collector.ts +65 -0
  73. package/src/packlets/{services → diagnostics}/diagnostics.ts +2 -2
  74. package/src/packlets/diagnostics/index.ts +7 -0
  75. package/src/packlets/identity/identity-service.test.ts +1 -1
  76. package/src/packlets/indexing/util.ts +6 -6
  77. package/src/packlets/invitations/device-invitation-protocol.test.ts +1 -1
  78. package/src/packlets/invitations/index.ts +1 -0
  79. package/src/packlets/invitations/invitation-extension.ts +28 -1
  80. package/src/packlets/invitations/invitations-handler.ts +74 -34
  81. package/src/packlets/invitations/invitations-manager.ts +197 -0
  82. package/src/packlets/invitations/invitations-service.ts +21 -168
  83. package/src/packlets/network/network-service.test.ts +1 -1
  84. package/src/packlets/services/automerge-host.test.ts +9 -3
  85. package/src/packlets/services/index.ts +1 -1
  86. package/src/packlets/services/service-context.test.ts +9 -6
  87. package/src/packlets/services/service-context.ts +29 -11
  88. package/src/packlets/services/service-host.ts +53 -19
  89. package/src/packlets/services/service-registry.test.ts +1 -1
  90. package/src/packlets/services/util.ts +2 -0
  91. package/src/packlets/spaces/data-space-manager.test.ts +4 -4
  92. package/src/packlets/spaces/data-space.ts +51 -2
  93. package/src/packlets/spaces/spaces-service.test.ts +1 -1
  94. package/src/packlets/storage/index.ts +1 -0
  95. package/src/packlets/storage/level.ts +19 -0
  96. package/src/packlets/storage/storage.ts +3 -9
  97. package/src/packlets/storage/util.ts +19 -0
  98. package/src/packlets/system/system-service.ts +1 -1
  99. package/src/packlets/testing/test-builder.ts +23 -5
  100. package/src/packlets/vault/shared-worker-connection.ts +3 -8
  101. package/src/packlets/vault/worker-runtime.ts +27 -2
  102. package/src/packlets/vault/worker-session.ts +6 -0
  103. package/src/version.ts +1 -5
  104. package/dist/lib/browser/chunk-RQ33OGAG.mjs.map +0 -7
  105. package/dist/lib/node/chunk-CBSM4HU4.cjs.map +0 -7
  106. package/dist/types/src/packlets/services/diagnostics.d.ts.map +0 -1
@@ -1282,6 +1282,7 @@ import { PushStream, scheduleTask as scheduleTask2, TimeoutError, Trigger as Tri
1282
1282
  import { AuthenticatingInvitation, AUTHENTICATION_CODE_LENGTH, CancellableInvitation, INVITATION_TIMEOUT } from "@dxos/client-protocol";
1283
1283
  import { Context as Context5 } from "@dxos/context";
1284
1284
  import { generatePasscode } from "@dxos/credentials";
1285
+ import { createKeyPair, sign } from "@dxos/crypto";
1285
1286
  import { invariant as invariant6 } from "@dxos/invariant";
1286
1287
  import { PublicKey as PublicKey6 } from "@dxos/keys";
1287
1288
  import { log as log5 } from "@dxos/log";
@@ -1293,6 +1294,7 @@ import { AuthenticationResponse as AuthenticationResponse2 } from "@dxos/protoco
1293
1294
  // packages/sdk/client-services/src/packlets/invitations/invitation-extension.ts
1294
1295
  import { Trigger as Trigger2 } from "@dxos/async";
1295
1296
  import { cancelWithContext, Context as Context4 } from "@dxos/context";
1297
+ import { randomBytes, verify } from "@dxos/crypto";
1296
1298
  import { invariant as invariant5 } from "@dxos/invariant";
1297
1299
  import { PublicKey as PublicKey5 } from "@dxos/keys";
1298
1300
  import { log as log4 } from "@dxos/log";
@@ -1316,6 +1318,7 @@ var InvitationHostExtension = class extends RpcExtension {
1316
1318
  this._callbacks = _callbacks;
1317
1319
  this._ctx = new Context4();
1318
1320
  this._remoteOptionsTrigger = new Trigger2();
1321
+ this._challenge = void 0;
1319
1322
  this.invitation = void 0;
1320
1323
  this.guestProfile = void 0;
1321
1324
  this.authenticationPassed = false;
@@ -1330,7 +1333,7 @@ var InvitationHostExtension = class extends RpcExtension {
1330
1333
  options: async (options) => {
1331
1334
  invariant5(!this._remoteOptions, "Remote options already set.", {
1332
1335
  F: __dxlog_file6,
1333
- L: 87,
1336
+ L: 90,
1334
1337
  S: this,
1335
1338
  A: [
1336
1339
  "!this._remoteOptions",
@@ -1347,7 +1350,7 @@ var InvitationHostExtension = class extends RpcExtension {
1347
1350
  id: traceId
1348
1351
  }), {
1349
1352
  F: __dxlog_file6,
1350
- L: 96,
1353
+ L: 99,
1351
1354
  S: this,
1352
1355
  C: (f, a) => f(...a)
1353
1356
  });
@@ -1357,7 +1360,7 @@ var InvitationHostExtension = class extends RpcExtension {
1357
1360
  invitationId
1358
1361
  }, {
1359
1362
  F: __dxlog_file6,
1360
- L: 100,
1363
+ L: 103,
1361
1364
  S: this,
1362
1365
  C: (f, a) => f(...a)
1363
1366
  });
@@ -1371,7 +1374,7 @@ var InvitationHostExtension = class extends RpcExtension {
1371
1374
  guestProfile: profile
1372
1375
  }, {
1373
1376
  F: __dxlog_file6,
1374
- L: 109,
1377
+ L: 112,
1375
1378
  S: this,
1376
1379
  C: (f, a) => f(...a)
1377
1380
  });
@@ -1380,25 +1383,27 @@ var InvitationHostExtension = class extends RpcExtension {
1380
1383
  ...this.invitation,
1381
1384
  state: Invitation2.State.READY_FOR_AUTHENTICATION
1382
1385
  });
1386
+ this._challenge = this.invitation.authMethod === Invitation2.AuthMethod.KNOWN_PUBLIC_KEY ? randomBytes(32) : void 0;
1383
1387
  log4.trace("dxos.sdk.invitation-handler.host.introduce", trace3.end({
1384
1388
  id: traceId
1385
1389
  }), {
1386
1390
  F: __dxlog_file6,
1387
- L: 116,
1391
+ L: 122,
1388
1392
  S: this,
1389
1393
  C: (f, a) => f(...a)
1390
1394
  });
1391
1395
  return {
1392
- authMethod: this.invitation.authMethod
1396
+ authMethod: this.invitation.authMethod,
1397
+ challenge: this._challenge
1393
1398
  };
1394
1399
  },
1395
- authenticate: async ({ authCode: code }) => {
1400
+ authenticate: async ({ authCode: code, signedChallenge }) => {
1396
1401
  const traceId = PublicKey5.random().toHex();
1397
1402
  log4.trace("dxos.sdk.invitation-handler.host.authenticate", trace3.begin({
1398
1403
  id: traceId
1399
1404
  }), {
1400
1405
  F: __dxlog_file6,
1401
- L: 124,
1406
+ L: 131,
1402
1407
  S: this,
1403
1408
  C: (f, a) => f(...a)
1404
1409
  });
@@ -1406,14 +1411,14 @@ var InvitationHostExtension = class extends RpcExtension {
1406
1411
  authCode: code
1407
1412
  }, {
1408
1413
  F: __dxlog_file6,
1409
- L: 125,
1414
+ L: 132,
1410
1415
  S: this,
1411
1416
  C: (f, a) => f(...a)
1412
1417
  });
1413
1418
  let status = AuthenticationResponse.Status.OK;
1414
1419
  invariant5(this.invitation, "Invitation is not set.", {
1415
1420
  F: __dxlog_file6,
1416
- L: 128,
1421
+ L: 135,
1417
1422
  S: this,
1418
1423
  A: [
1419
1424
  "this.invitation",
@@ -1424,7 +1429,7 @@ var InvitationHostExtension = class extends RpcExtension {
1424
1429
  case Invitation2.AuthMethod.NONE: {
1425
1430
  log4("authentication not required", void 0, {
1426
1431
  F: __dxlog_file6,
1427
- L: 131,
1432
+ L: 138,
1428
1433
  S: this,
1429
1434
  C: (f, a) => f(...a)
1430
1435
  });
@@ -1444,12 +1449,25 @@ var InvitationHostExtension = class extends RpcExtension {
1444
1449
  }
1445
1450
  break;
1446
1451
  }
1452
+ case Invitation2.AuthMethod.KNOWN_PUBLIC_KEY: {
1453
+ if (!this.invitation.guestKeypair) {
1454
+ status = AuthenticationResponse.Status.INTERNAL_ERROR;
1455
+ break;
1456
+ }
1457
+ const isSignatureValid = this._challenge && verify(this._challenge, Buffer.from(signedChallenge ?? []), this.invitation.guestKeypair.publicKey.asBuffer());
1458
+ if (isSignatureValid) {
1459
+ this.authenticationPassed = true;
1460
+ } else {
1461
+ status = AuthenticationResponse.Status.INVALID_SIGNATURE;
1462
+ }
1463
+ break;
1464
+ }
1447
1465
  default: {
1448
1466
  log4.error("invalid authentication method", {
1449
1467
  authMethod: this.invitation.authMethod
1450
1468
  }, {
1451
1469
  F: __dxlog_file6,
1452
- L: 149,
1470
+ L: 176,
1453
1471
  S: this,
1454
1472
  C: (f, a) => f(...a)
1455
1473
  });
@@ -1464,7 +1482,7 @@ var InvitationHostExtension = class extends RpcExtension {
1464
1482
  }
1465
1483
  }), {
1466
1484
  F: __dxlog_file6,
1467
- L: 155,
1485
+ L: 182,
1468
1486
  S: this,
1469
1487
  C: (f, a) => f(...a)
1470
1488
  });
@@ -1478,14 +1496,14 @@ var InvitationHostExtension = class extends RpcExtension {
1478
1496
  id: traceId
1479
1497
  }), {
1480
1498
  F: __dxlog_file6,
1481
- L: 161,
1499
+ L: 188,
1482
1500
  S: this,
1483
1501
  C: (f, a) => f(...a)
1484
1502
  });
1485
1503
  try {
1486
1504
  invariant5(this.invitation, "Invitation is not set.", {
1487
1505
  F: __dxlog_file6,
1488
- L: 164,
1506
+ L: 191,
1489
1507
  S: this,
1490
1508
  A: [
1491
1509
  "this.invitation",
@@ -1500,7 +1518,7 @@ var InvitationHostExtension = class extends RpcExtension {
1500
1518
  id: traceId
1501
1519
  }), {
1502
1520
  F: __dxlog_file6,
1503
- L: 172,
1521
+ L: 199,
1504
1522
  S: this,
1505
1523
  C: (f, a) => f(...a)
1506
1524
  });
@@ -1557,7 +1575,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1557
1575
  options: async (options) => {
1558
1576
  invariant5(!this._remoteOptions, "Remote options already set.", {
1559
1577
  F: __dxlog_file6,
1560
- L: 239,
1578
+ L: 266,
1561
1579
  S: this,
1562
1580
  A: [
1563
1581
  "!this._remoteOptions",
@@ -1584,7 +1602,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1584
1602
  try {
1585
1603
  log4("begin options", void 0, {
1586
1604
  F: __dxlog_file6,
1587
- L: 260,
1605
+ L: 287,
1588
1606
  S: this,
1589
1607
  C: (f, a) => f(...a)
1590
1608
  });
@@ -1596,7 +1614,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1596
1614
  }));
1597
1615
  log4("end options", void 0, {
1598
1616
  F: __dxlog_file6,
1599
- L: 263,
1617
+ L: 290,
1600
1618
  S: this,
1601
1619
  C: (f, a) => f(...a)
1602
1620
  });
@@ -1610,7 +1628,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1610
1628
  } catch (err) {
1611
1629
  log4("openError", err, {
1612
1630
  F: __dxlog_file6,
1613
- L: 273,
1631
+ L: 300,
1614
1632
  S: this,
1615
1633
  C: (f, a) => f(...a)
1616
1634
  });
@@ -1620,7 +1638,7 @@ var InvitationGuestExtension = class extends RpcExtension {
1620
1638
  async onClose() {
1621
1639
  log4("onClose", void 0, {
1622
1640
  F: __dxlog_file6,
1623
- L: 279,
1641
+ L: 306,
1624
1642
  S: this,
1625
1643
  C: (f, a) => f(...a)
1626
1644
  });
@@ -1639,11 +1657,11 @@ var InvitationsHandler = class {
1639
1657
  this._networkManager = _networkManager;
1640
1658
  }
1641
1659
  createInvitation(protocol, options) {
1642
- const { invitationId = PublicKey6.random().toHex(), type = Invitation3.Type.INTERACTIVE, authMethod = Invitation3.AuthMethod.SHARED_SECRET, state = Invitation3.State.INIT, timeout = INVITATION_TIMEOUT, swarmKey = PublicKey6.random(), persistent = true, created = /* @__PURE__ */ new Date(), lifetime = 86400 } = options ?? {};
1660
+ const { invitationId = PublicKey6.random().toHex(), type = Invitation3.Type.INTERACTIVE, authMethod = Invitation3.AuthMethod.SHARED_SECRET, state = Invitation3.State.INIT, timeout = INVITATION_TIMEOUT, swarmKey = PublicKey6.random(), persistent = options?.authMethod !== Invitation3.AuthMethod.KNOWN_PUBLIC_KEY, created = /* @__PURE__ */ new Date(), guestKeypair = void 0, lifetime = 86400, multiUse = false } = options ?? {};
1643
1661
  const authCode = options?.authCode ?? (authMethod === Invitation3.AuthMethod.SHARED_SECRET ? generatePasscode(AUTHENTICATION_CODE_LENGTH) : void 0);
1644
1662
  invariant6(protocol, void 0, {
1645
1663
  F: __dxlog_file7,
1646
- L: 84,
1664
+ L: 87,
1647
1665
  S: this,
1648
1666
  A: [
1649
1667
  "protocol",
@@ -1658,9 +1676,11 @@ var InvitationsHandler = class {
1658
1676
  swarmKey,
1659
1677
  authCode,
1660
1678
  timeout,
1661
- persistent,
1679
+ persistent: persistent && type !== Invitation3.Type.DELEGATED,
1680
+ guestKeypair: guestKeypair ?? (authMethod === Invitation3.AuthMethod.KNOWN_PUBLIC_KEY ? createAdmissionKeypair() : void 0),
1662
1681
  created,
1663
1682
  lifetime,
1683
+ multiUse,
1664
1684
  ...protocol.getInvitationContext()
1665
1685
  };
1666
1686
  const stream = new PushStream();
@@ -1675,7 +1695,7 @@ var InvitationsHandler = class {
1675
1695
  ...protocol.toJSON()
1676
1696
  }, {
1677
1697
  F: __dxlog_file7,
1678
- L: 109,
1698
+ L: 115,
1679
1699
  S: this,
1680
1700
  C: (f, a) => f(...a)
1681
1701
  });
@@ -1700,7 +1720,7 @@ var InvitationsHandler = class {
1700
1720
  const deviceKey = admissionRequest.device?.deviceKey ?? admissionRequest.space?.deviceKey;
1701
1721
  invariant6(deviceKey, void 0, {
1702
1722
  F: __dxlog_file7,
1703
- L: 130,
1723
+ L: 136,
1704
1724
  S: this,
1705
1725
  A: [
1706
1726
  "deviceKey",
@@ -1723,7 +1743,7 @@ var InvitationsHandler = class {
1723
1743
  id: traceId
1724
1744
  }), {
1725
1745
  F: __dxlog_file7,
1726
- L: 148,
1746
+ L: 154,
1727
1747
  S: this,
1728
1748
  C: (f, a) => f(...a)
1729
1749
  });
@@ -1731,7 +1751,7 @@ var InvitationsHandler = class {
1731
1751
  ...protocol.toJSON()
1732
1752
  }, {
1733
1753
  F: __dxlog_file7,
1734
- L: 149,
1754
+ L: 155,
1735
1755
  S: this,
1736
1756
  C: (f, a) => f(...a)
1737
1757
  });
@@ -1747,7 +1767,7 @@ var InvitationsHandler = class {
1747
1767
  ...protocol.toJSON()
1748
1768
  }, {
1749
1769
  F: __dxlog_file7,
1750
- L: 152,
1770
+ L: 158,
1751
1771
  S: this,
1752
1772
  C: (f, a) => f(...a)
1753
1773
  });
@@ -1759,7 +1779,7 @@ var InvitationsHandler = class {
1759
1779
  id: traceId
1760
1780
  }), {
1761
1781
  F: __dxlog_file7,
1762
- L: 154,
1782
+ L: 160,
1763
1783
  S: this,
1764
1784
  C: (f, a) => f(...a)
1765
1785
  });
@@ -1769,7 +1789,7 @@ var InvitationsHandler = class {
1769
1789
  ...protocol.toJSON()
1770
1790
  }, {
1771
1791
  F: __dxlog_file7,
1772
- L: 157,
1792
+ L: 163,
1773
1793
  S: this,
1774
1794
  C: (f, a) => f(...a)
1775
1795
  });
@@ -1780,7 +1800,7 @@ var InvitationsHandler = class {
1780
1800
  } else {
1781
1801
  log5.error("failed", err, {
1782
1802
  F: __dxlog_file7,
1783
- L: 160,
1803
+ L: 166,
1784
1804
  S: this,
1785
1805
  C: (f, a) => f(...a)
1786
1806
  });
@@ -1791,12 +1811,12 @@ var InvitationsHandler = class {
1791
1811
  error: err
1792
1812
  }), {
1793
1813
  F: __dxlog_file7,
1794
- L: 163,
1814
+ L: 169,
1795
1815
  S: this,
1796
1816
  C: (f, a) => f(...a)
1797
1817
  });
1798
1818
  } finally {
1799
- if (type !== Invitation3.Type.MULTIUSE) {
1819
+ if (!multiUse) {
1800
1820
  await swarmConnection.close();
1801
1821
  await ctx.dispose();
1802
1822
  }
@@ -1812,7 +1832,7 @@ var InvitationsHandler = class {
1812
1832
  ...protocol.toJSON()
1813
1833
  }, {
1814
1834
  F: __dxlog_file7,
1815
- L: 178,
1835
+ L: 184,
1816
1836
  S: this,
1817
1837
  C: (f, a) => f(...a)
1818
1838
  });
@@ -1823,7 +1843,7 @@ var InvitationsHandler = class {
1823
1843
  } else {
1824
1844
  log5.error("failed", err, {
1825
1845
  F: __dxlog_file7,
1826
- L: 181,
1846
+ L: 187,
1827
1847
  S: this,
1828
1848
  C: (f, a) => f(...a)
1829
1849
  });
@@ -1833,11 +1853,11 @@ var InvitationsHandler = class {
1833
1853
  });
1834
1854
  return extension;
1835
1855
  };
1836
- if (invitation.lifetime && invitation.created && invitation.lifetime !== 0) {
1856
+ if (invitation.lifetime && invitation.created) {
1837
1857
  if (invitation.created.getTime() + invitation.lifetime * 1e3 < Date.now()) {
1838
1858
  log5.warn("invitation has already expired", void 0, {
1839
1859
  F: __dxlog_file7,
1840
- L: 192,
1860
+ L: 198,
1841
1861
  S: this,
1842
1862
  C: (f, a) => f(...a)
1843
1863
  });
@@ -1888,7 +1908,7 @@ var InvitationsHandler = class {
1888
1908
  const { timeout = INVITATION_TIMEOUT } = invitation;
1889
1909
  invariant6(protocol, void 0, {
1890
1910
  F: __dxlog_file7,
1891
- L: 246,
1911
+ L: 252,
1892
1912
  S: this,
1893
1913
  A: [
1894
1914
  "protocol",
@@ -1898,7 +1918,7 @@ var InvitationsHandler = class {
1898
1918
  if (deviceProfile) {
1899
1919
  invariant6(invitation.kind === Invitation3.Kind.DEVICE, "deviceProfile provided for non-device invitation", {
1900
1920
  F: __dxlog_file7,
1901
- L: 250,
1921
+ L: 255,
1902
1922
  S: this,
1903
1923
  A: [
1904
1924
  "invitation.kind === Invitation.Kind.DEVICE",
@@ -1913,7 +1933,7 @@ var InvitationsHandler = class {
1913
1933
  const setState = (newData) => {
1914
1934
  invariant6(newData.state !== void 0, void 0, {
1915
1935
  F: __dxlog_file7,
1916
- L: 261,
1936
+ L: 266,
1917
1937
  S: this,
1918
1938
  A: [
1919
1939
  "newData.state !== undefined",
@@ -1933,7 +1953,7 @@ var InvitationsHandler = class {
1933
1953
  ...protocol.toJSON()
1934
1954
  }, {
1935
1955
  F: __dxlog_file7,
1936
- L: 269,
1956
+ L: 274,
1937
1957
  S: this,
1938
1958
  C: (f, a) => f(...a)
1939
1959
  });
@@ -1943,7 +1963,7 @@ var InvitationsHandler = class {
1943
1963
  } else {
1944
1964
  log5.warn("auth failed", err, {
1945
1965
  F: __dxlog_file7,
1946
- L: 272,
1966
+ L: 277,
1947
1967
  S: this,
1948
1968
  C: (f, a) => f(...a)
1949
1969
  });
@@ -1957,7 +1977,7 @@ var InvitationsHandler = class {
1957
1977
  ...protocol.toJSON()
1958
1978
  }, {
1959
1979
  F: __dxlog_file7,
1960
- L: 280,
1980
+ L: 285,
1961
1981
  S: this,
1962
1982
  C: (f, a) => f(...a)
1963
1983
  });
@@ -1972,7 +1992,7 @@ var InvitationsHandler = class {
1972
1992
  currentState
1973
1993
  }, {
1974
1994
  F: __dxlog_file7,
1975
- L: 290,
1995
+ L: 295,
1976
1996
  S: this,
1977
1997
  C: (f, a) => f(...a)
1978
1998
  });
@@ -1987,7 +2007,7 @@ var InvitationsHandler = class {
1987
2007
  id: traceId
1988
2008
  }), {
1989
2009
  F: __dxlog_file7,
1990
- L: 299,
2010
+ L: 304,
1991
2011
  S: this,
1992
2012
  C: (f, a) => f(...a)
1993
2013
  });
@@ -1999,7 +2019,7 @@ var InvitationsHandler = class {
1999
2019
  ...protocol.toJSON()
2000
2020
  }, {
2001
2021
  F: __dxlog_file7,
2002
- L: 307,
2022
+ L: 312,
2003
2023
  S: this,
2004
2024
  C: (f, a) => f(...a)
2005
2025
  });
@@ -2010,7 +2030,7 @@ var InvitationsHandler = class {
2010
2030
  ...protocol.toJSON()
2011
2031
  }, {
2012
2032
  F: __dxlog_file7,
2013
- L: 311,
2033
+ L: 316,
2014
2034
  S: this,
2015
2035
  C: (f, a) => f(...a)
2016
2036
  });
@@ -2020,62 +2040,28 @@ var InvitationsHandler = class {
2020
2040
  response: introductionResponse
2021
2041
  }, {
2022
2042
  F: __dxlog_file7,
2023
- L: 315,
2043
+ L: 320,
2024
2044
  S: this,
2025
2045
  C: (f, a) => f(...a)
2026
2046
  });
2027
2047
  invitation.authMethod = introductionResponse.authMethod;
2028
2048
  if (isAuthenticationRequired(invitation)) {
2029
- for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
2030
- log5("guest waiting for authentication code...", void 0, {
2031
- F: __dxlog_file7,
2032
- L: 321,
2033
- S: this,
2034
- C: (f, a) => f(...a)
2035
- });
2036
- setState({
2037
- state: Invitation3.State.READY_FOR_AUTHENTICATION
2038
- });
2039
- const authCode = await authenticated.wait({
2040
- timeout
2041
- });
2042
- log5("sending authentication request", void 0, {
2043
- F: __dxlog_file7,
2044
- L: 325,
2045
- S: this,
2046
- C: (f, a) => f(...a)
2047
- });
2048
- setState({
2049
- state: Invitation3.State.AUTHENTICATING
2050
- });
2051
- const response = await extension.rpc.InvitationHostService.authenticate({
2052
- authCode
2053
- });
2054
- if (response.status === void 0 || response.status === AuthenticationResponse2.Status.OK) {
2049
+ switch (invitation.authMethod) {
2050
+ case Invitation3.AuthMethod.SHARED_SECRET:
2051
+ await this._handleGuestOtpAuth(extension, setState, authenticated, {
2052
+ timeout
2053
+ });
2054
+ break;
2055
+ case Invitation3.AuthMethod.KNOWN_PUBLIC_KEY:
2056
+ await this._handleGuestKpkAuth(extension, setState, invitation, introductionResponse);
2055
2057
  break;
2056
- }
2057
- if (response.status === AuthenticationResponse2.Status.INVALID_OTP) {
2058
- if (attempt === MAX_OTP_ATTEMPTS) {
2059
- throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
2060
- } else {
2061
- log5("retrying invalid code", {
2062
- attempt
2063
- }, {
2064
- F: __dxlog_file7,
2065
- L: 336,
2066
- S: this,
2067
- C: (f, a) => f(...a)
2068
- });
2069
- authenticated.reset();
2070
- }
2071
- }
2072
2058
  }
2073
2059
  }
2074
2060
  log5("request admission", {
2075
2061
  ...protocol.toJSON()
2076
2062
  }, {
2077
2063
  F: __dxlog_file7,
2078
- L: 344,
2064
+ L: 336,
2079
2065
  S: this,
2080
2066
  C: (f, a) => f(...a)
2081
2067
  });
@@ -2087,7 +2073,7 @@ var InvitationsHandler = class {
2087
2073
  ...protocol.toJSON()
2088
2074
  }, {
2089
2075
  F: __dxlog_file7,
2090
- L: 355,
2076
+ L: 347,
2091
2077
  S: this,
2092
2078
  C: (f, a) => f(...a)
2093
2079
  });
@@ -2100,7 +2086,7 @@ var InvitationsHandler = class {
2100
2086
  id: traceId
2101
2087
  }), {
2102
2088
  F: __dxlog_file7,
2103
- L: 357,
2089
+ L: 349,
2104
2090
  S: this,
2105
2091
  C: (f, a) => f(...a)
2106
2092
  });
@@ -2110,7 +2096,7 @@ var InvitationsHandler = class {
2110
2096
  ...protocol.toJSON()
2111
2097
  }, {
2112
2098
  F: __dxlog_file7,
2113
- L: 360,
2099
+ L: 352,
2114
2100
  S: this,
2115
2101
  C: (f, a) => f(...a)
2116
2102
  });
@@ -2120,7 +2106,7 @@ var InvitationsHandler = class {
2120
2106
  } else {
2121
2107
  log5("auth failed", err, {
2122
2108
  F: __dxlog_file7,
2123
- L: 363,
2109
+ L: 355,
2124
2110
  S: this,
2125
2111
  C: (f, a) => f(...a)
2126
2112
  });
@@ -2131,7 +2117,7 @@ var InvitationsHandler = class {
2131
2117
  error: err
2132
2118
  }), {
2133
2119
  F: __dxlog_file7,
2134
- L: 366,
2120
+ L: 358,
2135
2121
  S: this,
2136
2122
  C: (f, a) => f(...a)
2137
2123
  });
@@ -2149,7 +2135,7 @@ var InvitationsHandler = class {
2149
2135
  ...protocol.toJSON()
2150
2136
  }, {
2151
2137
  F: __dxlog_file7,
2152
- L: 377,
2138
+ L: 369,
2153
2139
  S: this,
2154
2140
  C: (f, a) => f(...a)
2155
2141
  });
@@ -2159,7 +2145,7 @@ var InvitationsHandler = class {
2159
2145
  } else {
2160
2146
  log5("auth failed", err, {
2161
2147
  F: __dxlog_file7,
2162
- L: 380,
2148
+ L: 372,
2163
2149
  S: this,
2164
2150
  C: (f, a) => f(...a)
2165
2151
  });
@@ -2176,7 +2162,7 @@ var InvitationsHandler = class {
2176
2162
  } else {
2177
2163
  invariant6(invitation.swarmKey, void 0, {
2178
2164
  F: __dxlog_file7,
2179
- L: 394,
2165
+ L: 386,
2180
2166
  S: this,
2181
2167
  A: [
2182
2168
  "invitation.swarmKey",
@@ -2214,206 +2200,115 @@ var InvitationsHandler = class {
2214
2200
  });
2215
2201
  return observable;
2216
2202
  }
2203
+ async _handleGuestOtpAuth(extension, setState, authenticated, options) {
2204
+ for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
2205
+ log5("guest waiting for authentication code...", void 0, {
2206
+ F: __dxlog_file7,
2207
+ L: 426,
2208
+ S: this,
2209
+ C: (f, a) => f(...a)
2210
+ });
2211
+ setState({
2212
+ state: Invitation3.State.READY_FOR_AUTHENTICATION
2213
+ });
2214
+ const authCode = await authenticated.wait(options);
2215
+ log5("sending authentication request", void 0, {
2216
+ F: __dxlog_file7,
2217
+ L: 430,
2218
+ S: this,
2219
+ C: (f, a) => f(...a)
2220
+ });
2221
+ setState({
2222
+ state: Invitation3.State.AUTHENTICATING
2223
+ });
2224
+ const response = await extension.rpc.InvitationHostService.authenticate({
2225
+ authCode
2226
+ });
2227
+ if (response.status === void 0 || response.status === AuthenticationResponse2.Status.OK) {
2228
+ break;
2229
+ }
2230
+ if (response.status === AuthenticationResponse2.Status.INVALID_OTP) {
2231
+ if (attempt === MAX_OTP_ATTEMPTS) {
2232
+ throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
2233
+ } else {
2234
+ log5("retrying invalid code", {
2235
+ attempt
2236
+ }, {
2237
+ F: __dxlog_file7,
2238
+ L: 441,
2239
+ S: this,
2240
+ C: (f, a) => f(...a)
2241
+ });
2242
+ authenticated.reset();
2243
+ }
2244
+ }
2245
+ }
2246
+ }
2247
+ async _handleGuestKpkAuth(extension, setState, invitation, introductionResponse) {
2248
+ if (invitation.guestKeypair?.privateKey == null) {
2249
+ throw new Error("keypair missing in the invitation");
2250
+ }
2251
+ if (introductionResponse.challenge == null) {
2252
+ throw new Error("challenge missing in the introduction");
2253
+ }
2254
+ log5("sending authentication request", void 0, {
2255
+ F: __dxlog_file7,
2256
+ L: 460,
2257
+ S: this,
2258
+ C: (f, a) => f(...a)
2259
+ });
2260
+ setState({
2261
+ state: Invitation3.State.AUTHENTICATING
2262
+ });
2263
+ const signature = sign(Buffer.from(introductionResponse.challenge), invitation.guestKeypair.privateKey);
2264
+ const response = await extension.rpc.InvitationHostService.authenticate({
2265
+ signedChallenge: signature
2266
+ });
2267
+ if (response.status !== AuthenticationResponse2.Status.OK) {
2268
+ throw new Error(`Authentication failed with code: ${response.status}`);
2269
+ }
2270
+ }
2217
2271
  };
2218
- var invitationExpired = (invitation) => {
2219
- return invitation.created && invitation.lifetime && invitation.lifetime !== 0 && invitation.created.getTime() + invitation.lifetime * 1e3 < Date.now();
2272
+ var createAdmissionKeypair = () => {
2273
+ const keypair = createKeyPair();
2274
+ return {
2275
+ publicKey: PublicKey6.from(keypair.publicKey),
2276
+ privateKey: keypair.secretKey
2277
+ };
2220
2278
  };
2221
2279
 
2222
2280
  // packages/sdk/client-services/src/packlets/invitations/invitations-service.ts
2223
- import { Event as Event3, scheduleTask as scheduleTask3 } from "@dxos/async";
2224
2281
  import { Stream as Stream8 } from "@dxos/codec-protobuf";
2225
- import { Context as Context6 } from "@dxos/context";
2226
- import { invariant as invariant7 } from "@dxos/invariant";
2227
- import { log as log6 } from "@dxos/log";
2228
- import { Invitation as Invitation4, QueryInvitationsResponse } from "@dxos/protocols/proto/dxos/client/services";
2229
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/invitations-service.ts";
2282
+ import { QueryInvitationsResponse } from "@dxos/protocols/proto/dxos/client/services";
2230
2283
  var InvitationsServiceImpl = class {
2231
- constructor(_invitationsHandler, _getHandler, _metadataStore) {
2232
- this._invitationsHandler = _invitationsHandler;
2233
- this._getHandler = _getHandler;
2234
- this._metadataStore = _metadataStore;
2235
- this._createInvitations = /* @__PURE__ */ new Map();
2236
- this._acceptInvitations = /* @__PURE__ */ new Map();
2237
- this._invitationCreated = new Event3();
2238
- this._invitationAccepted = new Event3();
2239
- this._removedCreated = new Event3();
2240
- this._removedAccepted = new Event3();
2241
- this._saved = new Event3();
2242
- this._persistentInvitationsLoadedEvent = new Event3();
2243
- this._persistentInvitationsLoaded = false;
2284
+ constructor(_invitationsManager) {
2285
+ this._invitationsManager = _invitationsManager;
2244
2286
  }
2245
2287
  // TODO(burdon): Guest/host label.
2246
2288
  getLoggingContext() {
2247
2289
  return {};
2248
2290
  }
2249
2291
  createInvitation(options) {
2250
- let invitation;
2251
- const savePersistentInvitationCtx = new Context6();
2252
- const existingInvitation = this._createInvitations.get(options.invitationId);
2253
- if (existingInvitation) {
2254
- invitation = existingInvitation;
2255
- } else {
2256
- const handler = this._getHandler(options);
2257
- invitation = this._invitationsHandler.createInvitation(handler, options);
2258
- this._createInvitations.set(invitation.get().invitationId, invitation);
2259
- this._invitationCreated.emit(invitation.get());
2260
- }
2292
+ const invitation = this._invitationsManager.createInvitation(options);
2261
2293
  return new Stream8(({ next, close }) => {
2262
- if (invitation.get().persistent) {
2263
- scheduleTask3(savePersistentInvitationCtx, async () => {
2264
- try {
2265
- await this._metadataStore.addInvitation(invitation.get());
2266
- this._saved.emit(invitation.get());
2267
- } catch (err) {
2268
- close(err);
2269
- }
2270
- });
2271
- }
2272
- invitation.subscribe((invitation2) => {
2273
- next(invitation2);
2274
- }, async (err) => {
2275
- await savePersistentInvitationCtx.dispose();
2276
- close(err);
2277
- }, async () => {
2278
- close();
2279
- if (invitation.get().persistent) {
2280
- await savePersistentInvitationCtx.dispose();
2281
- await this._metadataStore.removeInvitation(invitation.get().invitationId);
2282
- }
2283
- this._createInvitations.delete(invitation.get().invitationId);
2284
- if (invitation.get().type !== Invitation4.Type.MULTIUSE) {
2285
- this._removedCreated.emit(invitation.get());
2286
- }
2287
- });
2294
+ invitation.subscribe(next, close, close);
2288
2295
  });
2289
2296
  }
2290
- async loadPersistentInvitations() {
2291
- const persistentInvitations = this._metadataStore.getInvitations();
2292
- const freshInvitations = persistentInvitations.filter(async (invitation) => !invitationExpired(invitation));
2293
- const cInvitations = freshInvitations.map((persistentInvitation) => {
2294
- invariant7(!this._createInvitations.get(persistentInvitation.invitationId), "invitation already exists", {
2295
- F: __dxlog_file8,
2296
- L: 109,
2297
- S: this,
2298
- A: [
2299
- "!this._createInvitations.get(persistentInvitation.invitationId)",
2300
- "'invitation already exists'"
2301
- ]
2302
- });
2303
- const handler = this._getHandler(persistentInvitation);
2304
- const invitation = this._invitationsHandler.createInvitation(handler, persistentInvitation);
2305
- this._createInvitations.set(invitation.get().invitationId, invitation);
2306
- this._invitationCreated.emit(invitation.get());
2307
- return persistentInvitation;
2308
- });
2309
- this._persistentInvitationsLoadedEvent.emit();
2310
- this._persistentInvitationsLoaded = true;
2311
- return {
2312
- invitations: cInvitations
2313
- };
2314
- }
2315
- acceptInvitation({ invitation: options, deviceProfile }) {
2316
- let invitation;
2317
- if (deviceProfile) {
2318
- invariant7(options.kind === Invitation4.Kind.DEVICE, "deviceProfile provided for non-device invitation", {
2319
- F: __dxlog_file8,
2320
- L: 127,
2321
- S: this,
2322
- A: [
2323
- "options.kind === Invitation.Kind.DEVICE",
2324
- "'deviceProfile provided for non-device invitation'"
2325
- ]
2326
- });
2327
- }
2328
- const existingInvitation = this._acceptInvitations.get(options.invitationId);
2329
- if (existingInvitation) {
2330
- invitation = existingInvitation;
2331
- } else {
2332
- const handler = this._getHandler(options);
2333
- invitation = this._invitationsHandler.acceptInvitation(handler, options, deviceProfile);
2334
- this._acceptInvitations.set(invitation.get().invitationId, invitation);
2335
- this._invitationAccepted.emit(invitation.get());
2336
- }
2297
+ acceptInvitation(request) {
2298
+ const invitation = this._invitationsManager.acceptInvitation(request);
2337
2299
  return new Stream8(({ next, close }) => {
2338
- invitation.subscribe((invitation2) => {
2339
- next(invitation2);
2340
- }, (err) => {
2341
- close(err);
2342
- }, () => {
2343
- close();
2344
- this._acceptInvitations.delete(invitation.get().invitationId);
2345
- if (invitation.get().type !== Invitation4.Type.MULTIUSE) {
2346
- this._removedAccepted.emit(invitation.get());
2347
- }
2348
- });
2300
+ invitation.subscribe(next, close, close);
2349
2301
  });
2350
2302
  }
2351
- async authenticate({ invitationId, authCode }) {
2352
- log6("authenticating...", void 0, {
2353
- F: __dxlog_file8,
2354
- L: 160,
2355
- S: this,
2356
- C: (f, a) => f(...a)
2357
- });
2358
- invariant7(invitationId, void 0, {
2359
- F: __dxlog_file8,
2360
- L: 161,
2361
- S: this,
2362
- A: [
2363
- "invitationId",
2364
- ""
2365
- ]
2366
- });
2367
- const observable = this._acceptInvitations.get(invitationId);
2368
- if (!observable) {
2369
- log6.warn("invalid invitation", {
2370
- invitationId
2371
- }, {
2372
- F: __dxlog_file8,
2373
- L: 164,
2374
- S: this,
2375
- C: (f, a) => f(...a)
2376
- });
2377
- } else {
2378
- await observable.authenticate(authCode);
2379
- }
2303
+ async authenticate(request) {
2304
+ return this._invitationsManager.authenticate(request);
2380
2305
  }
2381
- async cancelInvitation({ invitationId }) {
2382
- log6("cancelInvitation...", {
2383
- invitationId
2384
- }, {
2385
- F: __dxlog_file8,
2386
- L: 171,
2387
- S: this,
2388
- C: (f, a) => f(...a)
2389
- });
2390
- invariant7(invitationId, void 0, {
2391
- F: __dxlog_file8,
2392
- L: 172,
2393
- S: this,
2394
- A: [
2395
- "invitationId",
2396
- ""
2397
- ]
2398
- });
2399
- const created = this._createInvitations.get(invitationId);
2400
- const accepted = this._acceptInvitations.get(invitationId);
2401
- if (created) {
2402
- await created.cancel();
2403
- this._createInvitations.delete(invitationId);
2404
- this._removedCreated.emit(created.get());
2405
- if (created.get().persistent) {
2406
- await this._metadataStore.removeInvitation(created.get().invitationId);
2407
- }
2408
- } else if (accepted) {
2409
- await accepted.cancel();
2410
- this._acceptInvitations.delete(invitationId);
2411
- this._removedAccepted.emit(accepted.get());
2412
- }
2306
+ async cancelInvitation(request) {
2307
+ return this._invitationsManager.cancelInvitation(request);
2413
2308
  }
2414
2309
  queryInvitations() {
2415
2310
  return new Stream8(({ next, ctx }) => {
2416
- this._invitationCreated.on(ctx, (invitation) => {
2311
+ this._invitationsManager.invitationCreated.on(ctx, (invitation) => {
2417
2312
  next({
2418
2313
  action: QueryInvitationsResponse.Action.ADDED,
2419
2314
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2422,7 +2317,7 @@ var InvitationsServiceImpl = class {
2422
2317
  ]
2423
2318
  });
2424
2319
  });
2425
- this._invitationAccepted.on(ctx, (invitation) => {
2320
+ this._invitationsManager.invitationAccepted.on(ctx, (invitation) => {
2426
2321
  next({
2427
2322
  action: QueryInvitationsResponse.Action.ADDED,
2428
2323
  type: QueryInvitationsResponse.Type.ACCEPTED,
@@ -2431,7 +2326,7 @@ var InvitationsServiceImpl = class {
2431
2326
  ]
2432
2327
  });
2433
2328
  });
2434
- this._removedCreated.on(ctx, (invitation) => {
2329
+ this._invitationsManager.removedCreated.on(ctx, (invitation) => {
2435
2330
  next({
2436
2331
  action: QueryInvitationsResponse.Action.REMOVED,
2437
2332
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2440,7 +2335,7 @@ var InvitationsServiceImpl = class {
2440
2335
  ]
2441
2336
  });
2442
2337
  });
2443
- this._removedAccepted.on(ctx, (invitation) => {
2338
+ this._invitationsManager.removedAccepted.on(ctx, (invitation) => {
2444
2339
  next({
2445
2340
  action: QueryInvitationsResponse.Action.REMOVED,
2446
2341
  type: QueryInvitationsResponse.Type.ACCEPTED,
@@ -2449,7 +2344,7 @@ var InvitationsServiceImpl = class {
2449
2344
  ]
2450
2345
  });
2451
2346
  });
2452
- this._saved.on(ctx, (invitation) => {
2347
+ this._invitationsManager.saved.on(ctx, (invitation) => {
2453
2348
  next({
2454
2349
  action: QueryInvitationsResponse.Action.SAVED,
2455
2350
  type: QueryInvitationsResponse.Type.CREATED,
@@ -2461,28 +2356,21 @@ var InvitationsServiceImpl = class {
2461
2356
  next({
2462
2357
  action: QueryInvitationsResponse.Action.ADDED,
2463
2358
  type: QueryInvitationsResponse.Type.CREATED,
2464
- invitations: Array.from(this._createInvitations.values()).map((invitation) => invitation.get()),
2359
+ invitations: this._invitationsManager.getCreatedInvitations(),
2465
2360
  existing: true
2466
2361
  });
2467
2362
  next({
2468
2363
  action: QueryInvitationsResponse.Action.ADDED,
2469
2364
  type: QueryInvitationsResponse.Type.ACCEPTED,
2470
- invitations: Array.from(this._acceptInvitations.values()).map((invitation) => invitation.get()),
2365
+ invitations: this._invitationsManager.getAcceptedInvitations(),
2471
2366
  existing: true
2472
2367
  });
2473
- if (this._persistentInvitationsLoaded) {
2368
+ this._invitationsManager.onPersistentInvitationsLoaded(ctx, () => {
2474
2369
  next({
2475
2370
  action: QueryInvitationsResponse.Action.LOAD_COMPLETE,
2476
2371
  type: QueryInvitationsResponse.Type.CREATED
2477
2372
  });
2478
- } else {
2479
- this._persistentInvitationsLoadedEvent.on(ctx, () => {
2480
- next({
2481
- action: QueryInvitationsResponse.Action.LOAD_COMPLETE,
2482
- type: QueryInvitationsResponse.Type.CREATED
2483
- });
2484
- });
2485
- }
2373
+ });
2486
2374
  });
2487
2375
  }
2488
2376
  };
@@ -2490,11 +2378,11 @@ var InvitationsServiceImpl = class {
2490
2378
  // packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts
2491
2379
  import { createAdmissionCredentials, getCredentialAssertion } from "@dxos/credentials";
2492
2380
  import { writeMessages as writeMessages2 } from "@dxos/feed-store";
2493
- import { invariant as invariant8 } from "@dxos/invariant";
2494
- import { log as log7 } from "@dxos/log";
2381
+ import { invariant as invariant7 } from "@dxos/invariant";
2382
+ import { log as log6 } from "@dxos/log";
2495
2383
  import { AlreadyJoinedError as AlreadyJoinedError2 } from "@dxos/protocols";
2496
- import { Invitation as Invitation5 } from "@dxos/protocols/proto/dxos/client/services";
2497
- var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts";
2384
+ import { Invitation as Invitation4 } from "@dxos/protocols/proto/dxos/client/services";
2385
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/space-invitation-protocol.ts";
2498
2386
  var SpaceInvitationProtocol = class {
2499
2387
  constructor(_spaceManager, _signingContext, _keyring, _spaceKey) {
2500
2388
  this._spaceManager = _spaceManager;
@@ -2510,13 +2398,13 @@ var SpaceInvitationProtocol = class {
2510
2398
  }
2511
2399
  getInvitationContext() {
2512
2400
  return {
2513
- kind: Invitation5.Kind.SPACE,
2401
+ kind: Invitation4.Kind.SPACE,
2514
2402
  spaceKey: this._spaceKey
2515
2403
  };
2516
2404
  }
2517
2405
  async admit(request, guestProfile) {
2518
- invariant8(this._spaceKey, void 0, {
2519
- F: __dxlog_file9,
2406
+ invariant7(this._spaceKey, void 0, {
2407
+ F: __dxlog_file8,
2520
2408
  L: 47,
2521
2409
  S: this,
2522
2410
  A: [
@@ -2525,8 +2413,8 @@ var SpaceInvitationProtocol = class {
2525
2413
  ]
2526
2414
  });
2527
2415
  const space = await this._spaceManager.spaces.get(this._spaceKey);
2528
- invariant8(space, void 0, {
2529
- F: __dxlog_file9,
2416
+ invariant7(space, void 0, {
2417
+ F: __dxlog_file8,
2530
2418
  L: 49,
2531
2419
  S: this,
2532
2420
  A: [
@@ -2534,8 +2422,8 @@ var SpaceInvitationProtocol = class {
2534
2422
  ""
2535
2423
  ]
2536
2424
  });
2537
- invariant8(request.space, void 0, {
2538
- F: __dxlog_file9,
2425
+ invariant7(request.space, void 0, {
2426
+ F: __dxlog_file8,
2539
2427
  L: 51,
2540
2428
  S: this,
2541
2429
  A: [
@@ -2544,18 +2432,18 @@ var SpaceInvitationProtocol = class {
2544
2432
  ]
2545
2433
  });
2546
2434
  const { identityKey, deviceKey } = request.space;
2547
- log7("writing guest credentials", {
2435
+ log6("writing guest credentials", {
2548
2436
  host: this._signingContext.deviceKey,
2549
2437
  guest: deviceKey
2550
2438
  }, {
2551
- F: __dxlog_file9,
2439
+ F: __dxlog_file8,
2552
2440
  L: 54,
2553
2441
  S: this,
2554
2442
  C: (f, a) => f(...a)
2555
2443
  });
2556
2444
  const credentials = await createAdmissionCredentials(this._signingContext.credentialSigner, identityKey, space.key, space.inner.genesisFeedKey, guestProfile);
2557
- invariant8(credentials[0].credential, void 0, {
2558
- F: __dxlog_file9,
2445
+ invariant7(credentials[0].credential, void 0, {
2446
+ F: __dxlog_file8,
2559
2447
  L: 65,
2560
2448
  S: this,
2561
2449
  A: [
@@ -2564,8 +2452,8 @@ var SpaceInvitationProtocol = class {
2564
2452
  ]
2565
2453
  });
2566
2454
  const spaceMemberCredential = credentials[0].credential.credential;
2567
- invariant8(getCredentialAssertion(spaceMemberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
2568
- F: __dxlog_file9,
2455
+ invariant7(getCredentialAssertion(spaceMemberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
2456
+ F: __dxlog_file8,
2569
2457
  L: 67,
2570
2458
  S: this,
2571
2459
  A: [
@@ -2604,8 +2492,8 @@ var SpaceInvitationProtocol = class {
2604
2492
  };
2605
2493
  }
2606
2494
  async accept(response) {
2607
- invariant8(response.space, void 0, {
2608
- F: __dxlog_file9,
2495
+ invariant7(response.space, void 0, {
2496
+ F: __dxlog_file8,
2609
2497
  L: 107,
2610
2498
  S: this,
2611
2499
  A: [
@@ -2615,8 +2503,8 @@ var SpaceInvitationProtocol = class {
2615
2503
  });
2616
2504
  const { credential, controlTimeframe, dataTimeframe } = response.space;
2617
2505
  const assertion = getCredentialAssertion(credential);
2618
- invariant8(assertion["@type"] === "dxos.halo.credentials.SpaceMember", "Invalid credential", {
2619
- F: __dxlog_file9,
2506
+ invariant7(assertion["@type"] === "dxos.halo.credentials.SpaceMember", "Invalid credential", {
2507
+ F: __dxlog_file8,
2620
2508
  L: 110,
2621
2509
  S: this,
2622
2510
  A: [
@@ -2624,8 +2512,8 @@ var SpaceInvitationProtocol = class {
2624
2512
  "'Invalid credential'"
2625
2513
  ]
2626
2514
  });
2627
- invariant8(credential.subject.id.equals(this._signingContext.identityKey), void 0, {
2628
- F: __dxlog_file9,
2515
+ invariant7(credential.subject.id.equals(this._signingContext.identityKey), void 0, {
2516
+ F: __dxlog_file8,
2629
2517
  L: 111,
2630
2518
  S: this,
2631
2519
  A: [
@@ -2649,308 +2537,381 @@ var SpaceInvitationProtocol = class {
2649
2537
  }
2650
2538
  };
2651
2539
 
2652
- // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
2653
- import { Stream as Stream9 } from "@dxos/codec-protobuf";
2654
- import { raise } from "@dxos/debug";
2655
- import { parseMethodName, RpcPeer } from "@dxos/rpc";
2656
- import { MapCounter, trace as trace5 } from "@dxos/tracing";
2657
- function _ts_decorate3(decorators, target, key, desc) {
2658
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2659
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2660
- r = Reflect.decorate(decorators, target, key, desc);
2661
- else
2662
- for (var i = decorators.length - 1; i >= 0; i--)
2663
- if (d = decorators[i])
2664
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2665
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2666
- }
2667
- var ClientRpcServer = class {
2668
- constructor(params) {
2669
- this._handlerCache = /* @__PURE__ */ new Map();
2670
- this._callMetrics = new MapCounter();
2671
- const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
2672
- this._handleCall = handleCall;
2673
- this._handleStream = handleStream;
2674
- this._serviceRegistry = serviceRegistry;
2675
- this._rpcPeer = new RpcPeer({
2676
- ...rpcOptions,
2677
- callHandler: (method, params2) => {
2678
- const [serviceName, methodName] = parseMethodName(method);
2679
- const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
2680
- this._callMetrics.inc(`${serviceName}.${methodName} request`);
2681
- if (this._handleCall) {
2682
- return this._handleCall(methodName, params2, handler);
2683
- } else {
2684
- return handler(methodName, params2);
2685
- }
2686
- },
2687
- streamHandler: (method, params2) => {
2688
- const [serviceName, methodName] = parseMethodName(method);
2689
- const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
2690
- this._callMetrics.inc(`${serviceName}.${methodName} request stream`);
2691
- if (this._handleStream) {
2692
- return Stream9.map(Stream9.unwrapPromise(this._handleStream(methodName, params2, handler)), (data) => {
2693
- this._callMetrics.inc(`${serviceName}.${methodName} response stream`);
2694
- return data;
2695
- });
2696
- } else {
2697
- return handler(methodName, params2);
2698
- }
2540
+ // packages/sdk/client-services/src/packlets/invitations/invitations-manager.ts
2541
+ import { Event as Event3 } from "@dxos/async";
2542
+ import { hasInvitationExpired } from "@dxos/echo-pipeline";
2543
+ import { invariant as invariant8 } from "@dxos/invariant";
2544
+ import { log as log7 } from "@dxos/log";
2545
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/invitations/invitations-manager.ts";
2546
+ var InvitationsManager = class {
2547
+ constructor(_invitationsHandler, _getHandler, _metadataStore) {
2548
+ this._invitationsHandler = _invitationsHandler;
2549
+ this._getHandler = _getHandler;
2550
+ this._metadataStore = _metadataStore;
2551
+ this._createInvitations = /* @__PURE__ */ new Map();
2552
+ this._acceptInvitations = /* @__PURE__ */ new Map();
2553
+ this.invitationCreated = new Event3();
2554
+ this.invitationAccepted = new Event3();
2555
+ this.removedCreated = new Event3();
2556
+ this.removedAccepted = new Event3();
2557
+ this.saved = new Event3();
2558
+ this._persistentInvitationsLoadedEvent = new Event3();
2559
+ this._persistentInvitationsLoaded = false;
2560
+ }
2561
+ createInvitation(options) {
2562
+ const existingInvitation = this._createInvitations.get(options.invitationId);
2563
+ if (existingInvitation) {
2564
+ return existingInvitation;
2565
+ }
2566
+ const handler = this._getHandler(options);
2567
+ const invitation = this._invitationsHandler.createInvitation(handler, options);
2568
+ this._createInvitations.set(invitation.get().invitationId, invitation);
2569
+ this.invitationCreated.emit(invitation.get());
2570
+ const saveInvitationTask = invitation.get().persistent ? this._safePersistInBackground(invitation) : Promise.resolve();
2571
+ this._onInvitationComplete(invitation, async () => {
2572
+ this._createInvitations.delete(invitation.get().invitationId);
2573
+ this.removedCreated.emit(invitation.get());
2574
+ if (invitation.get().persistent) {
2575
+ await saveInvitationTask;
2576
+ await this._safeDeleteInvitation(invitation.get());
2699
2577
  }
2700
2578
  });
2579
+ return invitation;
2701
2580
  }
2702
- get _services() {
2703
- return Object.keys(this._serviceRegistry.services);
2704
- }
2705
- async open() {
2706
- await this._rpcPeer.open();
2707
- }
2708
- async close() {
2709
- await this._rpcPeer.close();
2710
- }
2711
- _getServiceHandler(serviceName) {
2712
- if (!this._handlerCache.has(serviceName)) {
2713
- const [key, descriptor] = Object.entries(this._serviceRegistry.descriptors).find(([key2, descriptor2]) => descriptor2.name === serviceName) ?? raise(new Error(`Service not available: ${serviceName}`));
2714
- const service = this._serviceRegistry.services[key];
2715
- if (!service) {
2716
- throw new Error(`Service not available: ${serviceName}`);
2717
- }
2718
- this._handlerCache.set(serviceName, descriptor.createServer(service));
2581
+ async loadPersistentInvitations() {
2582
+ if (this._persistentInvitationsLoaded) {
2583
+ const invitations = this.getCreatedInvitations().filter((i) => i.persistent);
2584
+ return {
2585
+ invitations
2586
+ };
2719
2587
  }
2720
- return this._handlerCache.get(serviceName);
2721
- }
2722
- };
2723
- _ts_decorate3([
2724
- trace5.metricsCounter()
2725
- ], ClientRpcServer.prototype, "_callMetrics", void 0);
2726
- _ts_decorate3([
2727
- trace5.info()
2728
- ], ClientRpcServer.prototype, "_services", null);
2729
- ClientRpcServer = _ts_decorate3([
2730
- trace5.resource()
2731
- ], ClientRpcServer);
2732
-
2733
- // packages/sdk/client-services/src/packlets/services/diagnostics.ts
2734
- import { getFirstStreamValue } from "@dxos/codec-protobuf";
2735
- import { credentialTypeFilter } from "@dxos/credentials";
2736
- import { invariant as invariant9 } from "@dxos/invariant";
2737
- import { STORAGE_VERSION } from "@dxos/protocols";
2738
- import { SpaceMember } from "@dxos/protocols/proto/dxos/client/services";
2739
- import { TRACE_PROCESSOR } from "@dxos/tracing";
2740
-
2741
- // packages/sdk/client-services/src/packlets/services/platform.ts
2742
- import { Platform } from "@dxos/protocols/proto/dxos/client/services";
2743
- var getPlatform = () => {
2744
- if (process.browser) {
2745
- if (typeof window !== "undefined") {
2746
- const { userAgent } = window.navigator;
2588
+ try {
2589
+ const persistentInvitations = this._metadataStore.getInvitations();
2590
+ const freshInvitations = persistentInvitations.filter((invitation) => !hasInvitationExpired(invitation));
2591
+ const cInvitations = freshInvitations.map((persistentInvitation) => {
2592
+ invariant8(!this._createInvitations.get(persistentInvitation.invitationId), "invitation already exists", {
2593
+ F: __dxlog_file9,
2594
+ L: 82,
2595
+ S: this,
2596
+ A: [
2597
+ "!this._createInvitations.get(persistentInvitation.invitationId)",
2598
+ "'invitation already exists'"
2599
+ ]
2600
+ });
2601
+ return this.createInvitation({
2602
+ ...persistentInvitation,
2603
+ persistent: false
2604
+ }).get();
2605
+ });
2747
2606
  return {
2748
- type: Platform.PLATFORM_TYPE.BROWSER,
2749
- userAgent,
2750
- uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1e3)
2607
+ invitations: cInvitations
2751
2608
  };
2752
- } else {
2609
+ } catch (err) {
2610
+ log7.catch(err, void 0, {
2611
+ F: __dxlog_file9,
2612
+ L: 88,
2613
+ S: this,
2614
+ C: (f, a) => f(...a)
2615
+ });
2753
2616
  return {
2754
- type: Platform.PLATFORM_TYPE.SHARED_WORKER,
2755
- uptime: Math.floor((Date.now() - performance.timeOrigin) / 1e3)
2617
+ invitations: []
2756
2618
  };
2619
+ } finally {
2620
+ this._persistentInvitationsLoadedEvent.emit();
2621
+ this._persistentInvitationsLoaded = true;
2757
2622
  }
2758
- } else {
2759
- const { platform: platform2, version, arch } = process;
2760
- return {
2761
- type: Platform.PLATFORM_TYPE.NODE,
2762
- platform: platform2,
2763
- arch,
2764
- runtime: version,
2765
- uptime: Math.floor(process.uptime()),
2766
- memory: process.memoryUsage()
2767
- };
2768
2623
  }
2769
- };
2770
-
2771
- // packages/sdk/client-services/src/version.ts
2772
- var DXOS_VERSION = "0.4.9";
2773
-
2774
- // packages/sdk/client-services/src/packlets/services/diagnostics.ts
2775
- var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/diagnostics.ts";
2776
- var DEFAULT_TIMEOUT = 1e3;
2777
- var createDiagnostics = async (clientServices, serviceContext, config) => {
2778
- const diagnostics = {
2779
- created: (/* @__PURE__ */ new Date()).toISOString(),
2780
- platform: getPlatform(),
2781
- client: {
2782
- version: DXOS_VERSION,
2783
- storage: {
2784
- version: STORAGE_VERSION
2785
- }
2786
- },
2787
- trace: TRACE_PROCESSOR.getDiagnostics()
2788
- };
2789
- {
2790
- invariant9(clientServices.LoggingService, "SystemService is not available.", {
2791
- F: __dxlog_file10,
2792
- L: 108,
2793
- S: void 0,
2624
+ acceptInvitation(request) {
2625
+ const options = request.invitation;
2626
+ const existingInvitation = this._acceptInvitations.get(options.invitationId);
2627
+ if (existingInvitation) {
2628
+ return existingInvitation;
2629
+ }
2630
+ const handler = this._getHandler(options);
2631
+ const invitation = this._invitationsHandler.acceptInvitation(handler, options, request.deviceProfile);
2632
+ this._acceptInvitations.set(invitation.get().invitationId, invitation);
2633
+ this.invitationAccepted.emit(invitation.get());
2634
+ this._onInvitationComplete(invitation, () => {
2635
+ this._acceptInvitations.delete(invitation.get().invitationId);
2636
+ this.removedAccepted.emit(invitation.get());
2637
+ });
2638
+ return invitation;
2639
+ }
2640
+ async authenticate({ invitationId, authCode }) {
2641
+ log7("authenticating...", void 0, {
2642
+ F: __dxlog_file9,
2643
+ L: 117,
2644
+ S: this,
2645
+ C: (f, a) => f(...a)
2646
+ });
2647
+ invariant8(invitationId, void 0, {
2648
+ F: __dxlog_file9,
2649
+ L: 118,
2650
+ S: this,
2794
2651
  A: [
2795
- "clientServices.LoggingService",
2796
- "'SystemService is not available.'"
2652
+ "invitationId",
2653
+ ""
2797
2654
  ]
2798
2655
  });
2799
- diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {
2800
- timeout: DEFAULT_TIMEOUT
2801
- }).catch(() => void 0);
2656
+ const observable = this._acceptInvitations.get(invitationId);
2657
+ if (!observable) {
2658
+ log7.warn("invalid invitation", {
2659
+ invitationId
2660
+ }, {
2661
+ F: __dxlog_file9,
2662
+ L: 121,
2663
+ S: this,
2664
+ C: (f, a) => f(...a)
2665
+ });
2666
+ } else {
2667
+ await observable.authenticate(authCode);
2668
+ }
2802
2669
  }
2803
- if (typeof navigator !== "undefined" && navigator.storage) {
2804
- const map = /* @__PURE__ */ new Map();
2805
- const dir = await navigator.storage.getDirectory();
2806
- for await (const filename of dir?.keys()) {
2807
- const idx = filename.indexOf("-", filename.indexOf("-") + 1);
2808
- if (idx === -1) {
2809
- continue;
2670
+ async cancelInvitation({ invitationId }) {
2671
+ log7("cancelInvitation...", {
2672
+ invitationId
2673
+ }, {
2674
+ F: __dxlog_file9,
2675
+ L: 128,
2676
+ S: this,
2677
+ C: (f, a) => f(...a)
2678
+ });
2679
+ invariant8(invitationId, void 0, {
2680
+ F: __dxlog_file9,
2681
+ L: 129,
2682
+ S: this,
2683
+ A: [
2684
+ "invitationId",
2685
+ ""
2686
+ ]
2687
+ });
2688
+ const created = this._createInvitations.get(invitationId);
2689
+ if (created) {
2690
+ if (created.get().persistent) {
2691
+ await this._metadataStore.removeInvitation(invitationId);
2810
2692
  }
2811
- map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);
2693
+ await created.cancel();
2694
+ this._createInvitations.delete(invitationId);
2695
+ this.removedCreated.emit(created.get());
2696
+ return;
2812
2697
  }
2813
- diagnostics.storage = Array.from(map.entries()).sort((a, b) => b[1] - a[1]).map(([file, count]) => ({
2814
- file,
2815
- count
2816
- }));
2817
- }
2818
- const identity = serviceContext.identityManager.identity;
2819
- if (identity) {
2820
- diagnostics.identity = {
2821
- identityKey: identity.identityKey,
2822
- spaceKey: identity.space.key,
2823
- profile: identity.profileDocument
2824
- };
2825
- const { devices } = await getFirstStreamValue(clientServices.DevicesService.queryDevices(), {
2826
- timeout: DEFAULT_TIMEOUT
2827
- }).catch(() => void 0) ?? {};
2828
- diagnostics.devices = devices;
2829
- if (serviceContext.dataSpaceManager) {
2830
- diagnostics.spaces = await Promise.all(Array.from(serviceContext.dataSpaceManager.spaces.values()).map((space) => getSpaceStats(space)) ?? []);
2698
+ const accepted = this._acceptInvitations.get(invitationId);
2699
+ if (accepted) {
2700
+ await accepted.cancel();
2701
+ this._acceptInvitations.delete(invitationId);
2702
+ this.removedAccepted.emit(accepted.get());
2831
2703
  }
2832
- const { feeds = [] } = await getFirstStreamValue(clientServices.DevtoolsHost.subscribeToFeeds({}), {
2833
- timeout: DEFAULT_TIMEOUT
2834
- }).catch(() => void 0) ?? {};
2835
- diagnostics.feeds = feeds.map(({ feedKey, bytes, length }) => ({
2836
- feedKey,
2837
- bytes,
2838
- length
2839
- }));
2840
- const status = await getFirstStreamValue(clientServices.NetworkService.queryStatus(), {
2841
- timeout: DEFAULT_TIMEOUT
2842
- }).catch(() => void 0);
2843
- diagnostics.networkStatus = status;
2844
- diagnostics.swarms = serviceContext.networkManager.connectionLog?.swarms;
2845
2704
  }
2846
- diagnostics.config = config.values;
2847
- return diagnostics;
2848
- };
2849
- var getSpaceStats = async (space) => {
2850
- const stats = {
2851
- key: space.key,
2852
- metrics: space.metrics,
2853
- epochs: space.inner.spaceState.credentials.filter(credentialTypeFilter("dxos.halo.credentials.Epoch")).map((credential) => ({
2854
- ...credential.subject.assertion,
2855
- id: credential.id
2856
- })),
2857
- members: Array.from(space.inner.spaceState.members.values()).map((member) => ({
2858
- identity: {
2859
- identityKey: member.key,
2860
- profile: {
2861
- displayName: member.assertion.profile?.displayName
2862
- }
2863
- },
2864
- presence: space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0 ? SpaceMember.PresenceState.ONLINE : SpaceMember.PresenceState.OFFLINE
2865
- })),
2866
- pipeline: {
2867
- // TODO(burdon): Pick properties from credentials if needed.
2868
- currentEpoch: space.automergeSpaceState.lastEpoch,
2869
- appliedEpoch: space.automergeSpaceState.lastEpoch,
2870
- controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),
2871
- currentControlTimeframe: space.inner.controlPipeline.state.timeframe,
2872
- targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,
2873
- totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe
2874
- }
2875
- };
2876
- if (stats.metrics) {
2877
- const { open, ready } = stats.metrics;
2878
- stats.metrics.startupTime = open && ready && ready.getTime() - open.getTime();
2705
+ getCreatedInvitations() {
2706
+ return [
2707
+ ...this._createInvitations.values()
2708
+ ].map((i) => i.get());
2879
2709
  }
2880
- return stats;
2881
- };
2882
-
2883
- // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2884
- import { Event as Event6, asyncTimeout, scheduleTask as scheduleTask5, sleep as sleep2, synchronized, trackLeaks } from "@dxos/async";
2885
- import { AUTH_TIMEOUT as AUTH_TIMEOUT2 } from "@dxos/client-protocol";
2886
- import { cancelWithContext as cancelWithContext2, Context as Context8, ContextDisposedError } from "@dxos/context";
2887
- import { timed, warnAfterTimeout } from "@dxos/debug";
2888
- import { createMappedFeedWriter } from "@dxos/echo-pipeline";
2889
- import { failedInvariant, invariant as invariant11 } from "@dxos/invariant";
2890
- import { PublicKey as PublicKey8 } from "@dxos/keys";
2891
- import { log as log9 } from "@dxos/log";
2892
- import { CancelledError, SystemError } from "@dxos/protocols";
2893
- import { SpaceState, CreateEpochRequest } from "@dxos/protocols/proto/dxos/client/services";
2894
- import { AdmittedFeed as AdmittedFeed3 } from "@dxos/protocols/proto/dxos/halo/credentials";
2895
- import { Timeframe as Timeframe2 } from "@dxos/timeframe";
2896
- import { trace as trace6 } from "@dxos/tracing";
2897
- import { ComplexSet as ComplexSet3 } from "@dxos/util";
2898
-
2899
- // packages/sdk/client-services/src/packlets/spaces/automerge-space-state.ts
2900
- import { Event as Event4 } from "@dxos/async";
2901
- import { checkCredentialType } from "@dxos/credentials";
2902
- var AutomergeSpaceState = class {
2903
- constructor(_onNewRoot) {
2904
- this._onNewRoot = _onNewRoot;
2905
- this.rootUrl = void 0;
2906
- this.lastEpoch = void 0;
2907
- this.onNewEpoch = new Event4();
2908
- this._isProcessingRootDocs = false;
2710
+ getAcceptedInvitations() {
2711
+ return [
2712
+ ...this._acceptInvitations.values()
2713
+ ].map((i) => i.get());
2909
2714
  }
2910
- async processCredential(credential) {
2911
- if (!checkCredentialType(credential, "dxos.halo.credentials.Epoch")) {
2912
- return;
2913
- }
2914
- this.lastEpoch = credential;
2915
- if (credential.subject.assertion.automergeRoot) {
2916
- this.rootUrl = credential.subject.assertion.automergeRoot;
2917
- if (this._isProcessingRootDocs) {
2918
- this._onNewRoot(this.rootUrl);
2919
- }
2715
+ onPersistentInvitationsLoaded(ctx, callback) {
2716
+ if (this._persistentInvitationsLoaded) {
2717
+ callback();
2718
+ } else {
2719
+ this._persistentInvitationsLoadedEvent.once(ctx, () => callback());
2920
2720
  }
2921
- this.onNewEpoch.emit(credential);
2922
2721
  }
2923
- startProcessingRootDocs() {
2924
- if (this._isProcessingRootDocs) {
2925
- return;
2926
- }
2927
- if (this.rootUrl) {
2928
- this._onNewRoot(this.rootUrl);
2722
+ _safePersistInBackground(invitation) {
2723
+ return new Promise((resolve) => {
2724
+ setTimeout(async () => {
2725
+ try {
2726
+ await this._metadataStore.addInvitation(invitation.get());
2727
+ this.saved.emit(invitation.get());
2728
+ } catch (err) {
2729
+ log7.catch(err, void 0, {
2730
+ F: __dxlog_file9,
2731
+ L: 173,
2732
+ S: this,
2733
+ C: (f, a) => f(...a)
2734
+ });
2735
+ await invitation.cancel();
2736
+ } finally {
2737
+ resolve();
2738
+ }
2739
+ });
2740
+ });
2741
+ }
2742
+ async _safeDeleteInvitation(invitation) {
2743
+ try {
2744
+ await this._metadataStore.removeInvitation(invitation.invitationId);
2745
+ } catch (err) {
2746
+ log7.catch(err, void 0, {
2747
+ F: __dxlog_file9,
2748
+ L: 186,
2749
+ S: this,
2750
+ C: (f, a) => f(...a)
2751
+ });
2929
2752
  }
2930
- this._isProcessingRootDocs = true;
2931
2753
  }
2932
- async ensureEpochInitialized() {
2933
- await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);
2754
+ _onInvitationComplete(invitation, callback) {
2755
+ invitation.subscribe(() => {
2756
+ }, () => {
2757
+ }, callback);
2934
2758
  }
2935
2759
  };
2936
2760
 
2937
- // packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts
2938
- import { DeferredTask, Event as Event5, scheduleTask as scheduleTask4, sleep, TimeoutError as TimeoutError2, Trigger as Trigger4 } from "@dxos/async";
2939
- import { Context as Context7, rejectOnDispose } from "@dxos/context";
2940
- import { invariant as invariant10 } from "@dxos/invariant";
2941
- import { PublicKey as PublicKey7 } from "@dxos/keys";
2942
- import { log as log8 } from "@dxos/log";
2761
+ // packages/sdk/client-services/src/packlets/services/client-rpc-server.ts
2762
+ import { Stream as Stream9 } from "@dxos/codec-protobuf";
2763
+ import { raise } from "@dxos/debug";
2764
+ import { parseMethodName, RpcPeer } from "@dxos/rpc";
2765
+ import { MapCounter, trace as trace5 } from "@dxos/tracing";
2766
+ function _ts_decorate3(decorators, target, key, desc) {
2767
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2768
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2769
+ r = Reflect.decorate(decorators, target, key, desc);
2770
+ else
2771
+ for (var i = decorators.length - 1; i >= 0; i--)
2772
+ if (d = decorators[i])
2773
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2774
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2775
+ }
2776
+ var ClientRpcServer = class {
2777
+ constructor(params) {
2778
+ this._handlerCache = /* @__PURE__ */ new Map();
2779
+ this._callMetrics = new MapCounter();
2780
+ const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;
2781
+ this._handleCall = handleCall;
2782
+ this._handleStream = handleStream;
2783
+ this._serviceRegistry = serviceRegistry;
2784
+ this._rpcPeer = new RpcPeer({
2785
+ ...rpcOptions,
2786
+ callHandler: (method, params2) => {
2787
+ const [serviceName, methodName] = parseMethodName(method);
2788
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).call(method2, params3);
2789
+ this._callMetrics.inc(`${serviceName}.${methodName} request`);
2790
+ if (this._handleCall) {
2791
+ return this._handleCall(methodName, params2, handler);
2792
+ } else {
2793
+ return handler(methodName, params2);
2794
+ }
2795
+ },
2796
+ streamHandler: (method, params2) => {
2797
+ const [serviceName, methodName] = parseMethodName(method);
2798
+ const handler = (method2, params3) => this._getServiceHandler(serviceName).callStream(method2, params3);
2799
+ this._callMetrics.inc(`${serviceName}.${methodName} request stream`);
2800
+ if (this._handleStream) {
2801
+ return Stream9.map(Stream9.unwrapPromise(this._handleStream(methodName, params2, handler)), (data) => {
2802
+ this._callMetrics.inc(`${serviceName}.${methodName} response stream`);
2803
+ return data;
2804
+ });
2805
+ } else {
2806
+ return handler(methodName, params2);
2807
+ }
2808
+ }
2809
+ });
2810
+ }
2811
+ get _services() {
2812
+ return Object.keys(this._serviceRegistry.services);
2813
+ }
2814
+ async open() {
2815
+ await this._rpcPeer.open();
2816
+ }
2817
+ async close() {
2818
+ await this._rpcPeer.close();
2819
+ }
2820
+ _getServiceHandler(serviceName) {
2821
+ if (!this._handlerCache.has(serviceName)) {
2822
+ const [key, descriptor] = Object.entries(this._serviceRegistry.descriptors).find(([key2, descriptor2]) => descriptor2.name === serviceName) ?? raise(new Error(`Service not available: ${serviceName}`));
2823
+ const service = this._serviceRegistry.services[key];
2824
+ if (!service) {
2825
+ throw new Error(`Service not available: ${serviceName}`);
2826
+ }
2827
+ this._handlerCache.set(serviceName, descriptor.createServer(service));
2828
+ }
2829
+ return this._handlerCache.get(serviceName);
2830
+ }
2831
+ };
2832
+ _ts_decorate3([
2833
+ trace5.metricsCounter()
2834
+ ], ClientRpcServer.prototype, "_callMetrics", void 0);
2835
+ _ts_decorate3([
2836
+ trace5.info()
2837
+ ], ClientRpcServer.prototype, "_services", null);
2838
+ ClientRpcServer = _ts_decorate3([
2839
+ trace5.resource()
2840
+ ], ClientRpcServer);
2841
+
2842
+ // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2843
+ import { Event as Event6, asyncTimeout, scheduleTask as scheduleTask4, sleep as sleep2, synchronized, trackLeaks } from "@dxos/async";
2844
+ import { AUTH_TIMEOUT as AUTH_TIMEOUT2 } from "@dxos/client-protocol";
2845
+ import { cancelWithContext as cancelWithContext2, Context as Context7, ContextDisposedError } from "@dxos/context";
2846
+ import { timed, warnAfterTimeout } from "@dxos/debug";
2847
+ import { TYPE_PROPERTIES } from "@dxos/echo-db";
2848
+ import { createMappedFeedWriter } from "@dxos/echo-pipeline";
2849
+ import { AutomergeDocumentLoaderImpl } from "@dxos/echo-pipeline";
2850
+ import { failedInvariant, invariant as invariant10 } from "@dxos/invariant";
2851
+ import { PublicKey as PublicKey8 } from "@dxos/keys";
2852
+ import { log as log9 } from "@dxos/log";
2853
+ import { CancelledError, SystemError } from "@dxos/protocols";
2854
+ import { SpaceState, CreateEpochRequest } from "@dxos/protocols/proto/dxos/client/services";
2855
+ import { AdmittedFeed as AdmittedFeed3 } from "@dxos/protocols/proto/dxos/halo/credentials";
2856
+ import { Timeframe as Timeframe2 } from "@dxos/timeframe";
2857
+ import { trace as trace6 } from "@dxos/tracing";
2858
+ import { ComplexSet as ComplexSet3, assignDeep } from "@dxos/util";
2859
+
2860
+ // packages/sdk/client-services/src/packlets/spaces/automerge-space-state.ts
2861
+ import { Event as Event4 } from "@dxos/async";
2862
+ import { checkCredentialType } from "@dxos/credentials";
2863
+ var AutomergeSpaceState = class {
2864
+ constructor(_onNewRoot) {
2865
+ this._onNewRoot = _onNewRoot;
2866
+ this.rootUrl = void 0;
2867
+ this.lastEpoch = void 0;
2868
+ this.onNewEpoch = new Event4();
2869
+ this._isProcessingRootDocs = false;
2870
+ }
2871
+ async processCredential(credential) {
2872
+ if (!checkCredentialType(credential, "dxos.halo.credentials.Epoch")) {
2873
+ return;
2874
+ }
2875
+ this.lastEpoch = credential;
2876
+ if (credential.subject.assertion.automergeRoot) {
2877
+ this.rootUrl = credential.subject.assertion.automergeRoot;
2878
+ if (this._isProcessingRootDocs) {
2879
+ this._onNewRoot(this.rootUrl);
2880
+ }
2881
+ }
2882
+ this.onNewEpoch.emit(credential);
2883
+ }
2884
+ startProcessingRootDocs() {
2885
+ if (this._isProcessingRootDocs) {
2886
+ return;
2887
+ }
2888
+ if (this.rootUrl) {
2889
+ this._onNewRoot(this.rootUrl);
2890
+ }
2891
+ this._isProcessingRootDocs = true;
2892
+ }
2893
+ async ensureEpochInitialized() {
2894
+ await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);
2895
+ }
2896
+ };
2897
+
2898
+ // packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts
2899
+ import { DeferredTask, Event as Event5, scheduleTask as scheduleTask3, sleep, TimeoutError as TimeoutError2, Trigger as Trigger4 } from "@dxos/async";
2900
+ import { Context as Context6, rejectOnDispose } from "@dxos/context";
2901
+ import { invariant as invariant9 } from "@dxos/invariant";
2902
+ import { PublicKey as PublicKey7 } from "@dxos/keys";
2903
+ import { log as log8 } from "@dxos/log";
2943
2904
  import { schema as schema3 } from "@dxos/protocols";
2944
2905
  import { RpcExtension as RpcExtension2 } from "@dxos/teleport";
2945
2906
  import { ComplexMap as ComplexMap2, ComplexSet as ComplexSet2, entry } from "@dxos/util";
2946
- var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts";
2907
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/notarization-plugin.ts";
2947
2908
  var DEFAULT_RETRY_TIMEOUT = 1e3;
2948
2909
  var DEFAULT_SUCCESS_DELAY = 1e3;
2949
2910
  var DEFAULT_NOTARIZE_TIMEOUT = 1e4;
2950
2911
  var WRITER_NOT_SET_ERROR_CODE = "WRITER_NOT_SET";
2951
2912
  var NotarizationPlugin = class {
2952
2913
  constructor() {
2953
- this._ctx = new Context7();
2914
+ this._ctx = new Context6();
2954
2915
  this._extensionOpened = new Event5();
2955
2916
  this._extensions = /* @__PURE__ */ new Set();
2956
2917
  this._processedCredentials = new ComplexSet2(PublicKey7.hash);
@@ -2971,13 +2932,13 @@ var NotarizationPlugin = class {
2971
2932
  log8("notarize", {
2972
2933
  credentials
2973
2934
  }, {
2974
- F: __dxlog_file11,
2935
+ F: __dxlog_file10,
2975
2936
  L: 90,
2976
2937
  S: this,
2977
2938
  C: (f, a) => f(...a)
2978
2939
  });
2979
- invariant10(credentials.every((credential) => credential.id), "Credentials must have an id", {
2980
- F: __dxlog_file11,
2940
+ invariant9(credentials.every((credential) => credential.id), "Credentials must have an id", {
2941
+ F: __dxlog_file10,
2981
2942
  L: 91,
2982
2943
  S: this,
2983
2944
  A: [
@@ -2991,7 +2952,7 @@ var NotarizationPlugin = class {
2991
2952
  log8.warn("Notarization error", {
2992
2953
  err
2993
2954
  }, {
2994
- F: __dxlog_file11,
2955
+ F: __dxlog_file10,
2995
2956
  L: 99,
2996
2957
  S: this,
2997
2958
  C: (f, a) => f(...a)
@@ -3002,12 +2963,12 @@ var NotarizationPlugin = class {
3002
2963
  });
3003
2964
  opCtx?.onDispose(() => ctx.dispose());
3004
2965
  if (timeout !== 0) {
3005
- scheduleTask4(ctx, () => {
2966
+ scheduleTask3(ctx, () => {
3006
2967
  log8.warn("Notarization timeout", {
3007
2968
  timeout,
3008
2969
  peers: Array.from(this._extensions).map((extension) => extension.remotePeerId)
3009
2970
  }, {
3010
- F: __dxlog_file11,
2971
+ F: __dxlog_file10,
3011
2972
  L: 111,
3012
2973
  S: this,
3013
2974
  C: (f, a) => f(...a)
@@ -3030,13 +2991,13 @@ var NotarizationPlugin = class {
3030
2991
  log8.info("Exhausted all peers to notarize with", {
3031
2992
  retryIn: retryTimeout
3032
2993
  }, {
3033
- F: __dxlog_file11,
2994
+ F: __dxlog_file10,
3034
2995
  L: 136,
3035
2996
  S: this,
3036
2997
  C: (f, a) => f(...a)
3037
2998
  });
3038
2999
  peersTried.clear();
3039
- scheduleTask4(ctx, () => notarizeTask.schedule(), retryTimeout);
3000
+ scheduleTask3(ctx, () => notarizeTask.schedule(), retryTimeout);
3040
3001
  return;
3041
3002
  }
3042
3003
  peersTried.add(peer);
@@ -3044,7 +3005,7 @@ var NotarizationPlugin = class {
3044
3005
  peer: peer.localPeerId,
3045
3006
  credentialId: credentials.map((credential) => credential.id)
3046
3007
  }, {
3047
- F: __dxlog_file11,
3008
+ F: __dxlog_file10,
3048
3009
  L: 143,
3049
3010
  S: this,
3050
3011
  C: (f, a) => f(...a)
@@ -3053,7 +3014,7 @@ var NotarizationPlugin = class {
3053
3014
  credentials: credentials.filter((credential) => !this._processedCredentials.has(credential.id))
3054
3015
  });
3055
3016
  log8("success", void 0, {
3056
- F: __dxlog_file11,
3017
+ F: __dxlog_file10,
3057
3018
  L: 147,
3058
3019
  S: this,
3059
3020
  C: (f, a) => f(...a)
@@ -3062,7 +3023,7 @@ var NotarizationPlugin = class {
3062
3023
  } catch (err) {
3063
3024
  if (!ctx.disposed && !err.message.includes(WRITER_NOT_SET_ERROR_CODE)) {
3064
3025
  log8.info("error notarizing (recoverable)", err, {
3065
- F: __dxlog_file11,
3026
+ F: __dxlog_file10,
3066
3027
  L: 151,
3067
3028
  S: this,
3068
3029
  C: (f, a) => f(...a)
@@ -3080,7 +3041,7 @@ var NotarizationPlugin = class {
3080
3041
  errors.wait()
3081
3042
  ]);
3082
3043
  log8("done", void 0, {
3083
- F: __dxlog_file11,
3044
+ F: __dxlog_file10,
3084
3045
  L: 162,
3085
3046
  S: this,
3086
3047
  C: (f, a) => f(...a)
@@ -3101,8 +3062,8 @@ var NotarizationPlugin = class {
3101
3062
  this._processCredentialsTriggers.delete(credential.id);
3102
3063
  }
3103
3064
  setWriter(writer) {
3104
- invariant10(!this._writer, "Writer already set.", {
3105
- F: __dxlog_file11,
3065
+ invariant9(!this._writer, "Writer already set.", {
3066
+ F: __dxlog_file10,
3106
3067
  L: 181,
3107
3068
  S: this,
3108
3069
  A: [
@@ -3126,8 +3087,8 @@ var NotarizationPlugin = class {
3126
3087
  throw new Error(WRITER_NOT_SET_ERROR_CODE);
3127
3088
  }
3128
3089
  for (const credential of request.credentials ?? []) {
3129
- invariant10(credential.id, "Credential must have an id", {
3130
- F: __dxlog_file11,
3090
+ invariant9(credential.id, "Credential must have an id", {
3091
+ F: __dxlog_file10,
3131
3092
  L: 200,
3132
3093
  S: this,
3133
3094
  A: [
@@ -3147,7 +3108,7 @@ var NotarizationPlugin = class {
3147
3108
  log8("extension opened", {
3148
3109
  peer: extension.localPeerId
3149
3110
  }, {
3150
- F: __dxlog_file11,
3111
+ F: __dxlog_file10,
3151
3112
  L: 211,
3152
3113
  S: this,
3153
3114
  C: (f, a) => f(...a)
@@ -3159,7 +3120,7 @@ var NotarizationPlugin = class {
3159
3120
  log8("extension closed", {
3160
3121
  peer: extension.localPeerId
3161
3122
  }, {
3162
- F: __dxlog_file11,
3123
+ F: __dxlog_file10,
3163
3124
  L: 216,
3164
3125
  S: this,
3165
3126
  C: (f, a) => f(...a)
@@ -3213,10 +3174,10 @@ function _ts_decorate4(decorators, target, key, desc) {
3213
3174
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3214
3175
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3215
3176
  }
3216
- var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space.ts";
3177
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space.ts";
3217
3178
  var DataSpace = class {
3218
3179
  constructor(params) {
3219
- this._ctx = new Context8();
3180
+ this._ctx = new Context7();
3220
3181
  this._notarizationPlugin = new NotarizationPlugin();
3221
3182
  this._cache = void 0;
3222
3183
  // TODO(dmaretskyi): Move into Space?
@@ -3248,8 +3209,8 @@ var DataSpace = class {
3248
3209
  log9("new state", {
3249
3210
  state: SpaceState[this._state]
3250
3211
  }, {
3251
- F: __dxlog_file12,
3252
- L: 132,
3212
+ F: __dxlog_file11,
3213
+ L: 140,
3253
3214
  S: this,
3254
3215
  C: (f, a) => f(...a)
3255
3216
  });
@@ -3293,13 +3254,13 @@ var DataSpace = class {
3293
3254
  await this._notarizationPlugin.open();
3294
3255
  await this._inner.spaceState.addCredentialProcessor(this._notarizationPlugin);
3295
3256
  await this._inner.spaceState.addCredentialProcessor(this._automergeSpaceState);
3296
- await this._inner.open(new Context8());
3257
+ await this._inner.open(new Context7());
3297
3258
  this._state = SpaceState.CONTROL_ONLY;
3298
3259
  log9("new state", {
3299
3260
  state: SpaceState[this._state]
3300
3261
  }, {
3301
- F: __dxlog_file12,
3302
- L: 190,
3262
+ F: __dxlog_file11,
3263
+ L: 198,
3303
3264
  S: this,
3304
3265
  C: (f, a) => f(...a)
3305
3266
  });
@@ -3316,13 +3277,13 @@ var DataSpace = class {
3316
3277
  log9("new state", {
3317
3278
  state: SpaceState[this._state]
3318
3279
  }, {
3319
- F: __dxlog_file12,
3320
- L: 204,
3280
+ F: __dxlog_file11,
3281
+ L: 212,
3321
3282
  S: this,
3322
3283
  C: (f, a) => f(...a)
3323
3284
  });
3324
3285
  await this._ctx.dispose();
3325
- this._ctx = new Context8();
3286
+ this._ctx = new Context7();
3326
3287
  await this.authVerifier.close();
3327
3288
  await this._inner.close();
3328
3289
  await this._inner.spaceState.removeCredentialProcessor(this._automergeSpaceState);
@@ -3341,23 +3302,23 @@ var DataSpace = class {
3341
3302
  * Initialize the data pipeline in a separate task.
3342
3303
  */
3343
3304
  initializeDataPipelineAsync() {
3344
- scheduleTask5(this._ctx, async () => {
3305
+ scheduleTask4(this._ctx, async () => {
3345
3306
  try {
3346
3307
  this.metrics.pipelineInitBegin = /* @__PURE__ */ new Date();
3347
3308
  await this.initializeDataPipeline();
3348
3309
  } catch (err) {
3349
3310
  if (err instanceof CancelledError || err instanceof ContextDisposedError) {
3350
3311
  log9("data pipeline initialization cancelled", err, {
3351
- F: __dxlog_file12,
3352
- L: 237,
3312
+ F: __dxlog_file11,
3313
+ L: 245,
3353
3314
  S: this,
3354
3315
  C: (f, a) => f(...a)
3355
3316
  });
3356
3317
  return;
3357
3318
  }
3358
3319
  log9.error("Error initializing data pipeline", err, {
3359
- F: __dxlog_file12,
3360
- L: 241,
3320
+ F: __dxlog_file11,
3321
+ L: 249,
3361
3322
  S: this,
3362
3323
  C: (f, a) => f(...a)
3363
3324
  });
@@ -3365,8 +3326,8 @@ var DataSpace = class {
3365
3326
  log9("new state", {
3366
3327
  state: SpaceState[this._state]
3367
3328
  }, {
3368
- F: __dxlog_file12,
3369
- L: 243,
3329
+ F: __dxlog_file11,
3330
+ L: 251,
3370
3331
  S: this,
3371
3332
  C: (f, a) => f(...a)
3372
3333
  });
@@ -3385,8 +3346,8 @@ var DataSpace = class {
3385
3346
  log9("new state", {
3386
3347
  state: SpaceState[this._state]
3387
3348
  }, {
3388
- F: __dxlog_file12,
3389
- L: 259,
3349
+ F: __dxlog_file11,
3350
+ L: 267,
3390
3351
  S: this,
3391
3352
  C: (f, a) => f(...a)
3392
3353
  });
@@ -3395,8 +3356,8 @@ var DataSpace = class {
3395
3356
  this._automergeSpaceState.startProcessingRootDocs();
3396
3357
  await cancelWithContext2(this._ctx, this.automergeSpaceState.ensureEpochInitialized());
3397
3358
  log9("data pipeline ready", void 0, {
3398
- F: __dxlog_file12,
3399
- L: 271,
3359
+ F: __dxlog_file11,
3360
+ L: 279,
3400
3361
  S: this,
3401
3362
  C: (f, a) => f(...a)
3402
3363
  });
@@ -3405,8 +3366,8 @@ var DataSpace = class {
3405
3366
  log9("new state", {
3406
3367
  state: SpaceState[this._state]
3407
3368
  }, {
3408
- F: __dxlog_file12,
3409
- L: 275,
3369
+ F: __dxlog_file11,
3370
+ L: 283,
3410
3371
  S: this,
3411
3372
  C: (f, a) => f(...a)
3412
3373
  });
@@ -3421,8 +3382,8 @@ var DataSpace = class {
3421
3382
  this.metrics.controlPipelineReady = /* @__PURE__ */ new Date();
3422
3383
  await this._createWritableFeeds();
3423
3384
  log9("writable feeds created", void 0, {
3424
- F: __dxlog_file12,
3425
- L: 291,
3385
+ F: __dxlog_file11,
3386
+ L: 299,
3426
3387
  S: this,
3427
3388
  C: (f, a) => f(...a)
3428
3389
  });
@@ -3484,8 +3445,8 @@ var DataSpace = class {
3484
3445
  space: this.key,
3485
3446
  rootUrl
3486
3447
  }, {
3487
- F: __dxlog_file12,
3488
- L: 357,
3448
+ F: __dxlog_file11,
3449
+ L: 365,
3489
3450
  S: this,
3490
3451
  C: (f, a) => f(...a)
3491
3452
  });
@@ -3516,8 +3477,8 @@ var DataSpace = class {
3516
3477
  rootUrl,
3517
3478
  err
3518
3479
  }, {
3519
- F: __dxlog_file12,
3520
- L: 380,
3480
+ F: __dxlog_file11,
3481
+ L: 388,
3521
3482
  S: this,
3522
3483
  C: (f, a) => f(...a)
3523
3484
  });
@@ -3570,15 +3531,75 @@ var DataSpace = class {
3570
3531
  const rootHandle = this._automergeHost.repo.find(currentRootUrl);
3571
3532
  await cancelWithContext2(this._ctx, asyncTimeout(rootHandle.whenReady(), 1e4));
3572
3533
  const newRoot = this._automergeHost.repo.create(rootHandle.docSync());
3573
- invariant11(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3574
- F: __dxlog_file12,
3575
- L: 430,
3534
+ invariant10(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3535
+ F: __dxlog_file11,
3536
+ L: 438,
3537
+ S: this,
3538
+ A: [
3539
+ "typeof newRoot.url === 'string' && newRoot.url.length > 0",
3540
+ ""
3541
+ ]
3542
+ });
3543
+ epoch = {
3544
+ previousId: this._automergeSpaceState.lastEpoch?.id,
3545
+ number: (this._automergeSpaceState.lastEpoch?.subject.assertion.number ?? -1) + 1,
3546
+ timeframe: this._automergeSpaceState.lastEpoch?.subject.assertion.timeframe ?? new Timeframe2(),
3547
+ automergeRoot: newRoot.url
3548
+ };
3549
+ }
3550
+ break;
3551
+ case CreateEpochRequest.Migration.FRAGMENT_AUTOMERGE_ROOT:
3552
+ {
3553
+ log9.info("Fragmenting", void 0, {
3554
+ F: __dxlog_file11,
3555
+ L: 450,
3556
+ S: this,
3557
+ C: (f, a) => f(...a)
3558
+ });
3559
+ const currentRootUrl = this._automergeSpaceState.rootUrl;
3560
+ const rootHandle = this._automergeHost.repo.find(currentRootUrl);
3561
+ await cancelWithContext2(this._ctx, asyncTimeout(rootHandle.whenReady(), 1e4));
3562
+ const objects = Object.entries(rootHandle.docSync().objects);
3563
+ const properties = objects.find(([_, value]) => value.system.type?.itemId === TYPE_PROPERTIES);
3564
+ const otherObjects = objects.filter(([key]) => key !== properties?.[0]);
3565
+ invariant10(properties, "Properties not found", {
3566
+ F: __dxlog_file11,
3567
+ L: 460,
3568
+ S: this,
3569
+ A: [
3570
+ "properties",
3571
+ "'Properties not found'"
3572
+ ]
3573
+ });
3574
+ const newSpaceDoc = {
3575
+ ...rootHandle.docSync(),
3576
+ objects: Object.fromEntries([
3577
+ properties
3578
+ ])
3579
+ };
3580
+ const newRoot = this._automergeHost.repo.create(newSpaceDoc);
3581
+ invariant10(typeof newRoot.url === "string" && newRoot.url.length > 0, void 0, {
3582
+ F: __dxlog_file11,
3583
+ L: 465,
3576
3584
  S: this,
3577
3585
  A: [
3578
3586
  "typeof newRoot.url === 'string' && newRoot.url.length > 0",
3579
3587
  ""
3580
3588
  ]
3581
3589
  });
3590
+ const docLoader = new AutomergeDocumentLoaderImpl(this.key, this._automergeHost.repo);
3591
+ await docLoader.loadSpaceRootDocHandle(this._ctx, {
3592
+ rootUrl: newRoot.url
3593
+ });
3594
+ otherObjects.forEach(([key, value]) => {
3595
+ const handle = docLoader.createDocumentForObject(key);
3596
+ handle.change((doc) => {
3597
+ assignDeep(doc, [
3598
+ "objects",
3599
+ key
3600
+ ], value);
3601
+ });
3602
+ });
3582
3603
  epoch = {
3583
3604
  previousId: this._automergeSpaceState.lastEpoch?.id,
3584
3605
  number: (this._automergeSpaceState.lastEpoch?.subject.assertion.number ?? -1) + 1,
@@ -3627,8 +3648,8 @@ var DataSpace = class {
3627
3648
  log9("new state", {
3628
3649
  state: SpaceState[this._state]
3629
3650
  }, {
3630
- F: __dxlog_file12,
3631
- L: 482,
3651
+ F: __dxlog_file11,
3652
+ L: 531,
3632
3653
  S: this,
3633
3654
  C: (f, a) => f(...a)
3634
3655
  });
@@ -3683,9 +3704,9 @@ DataSpace = _ts_decorate4([
3683
3704
 
3684
3705
  // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
3685
3706
  import { Event as Event7, synchronized as synchronized2, trackLeaks as trackLeaks2 } from "@dxos/async";
3686
- import { Context as Context9, cancelWithContext as cancelWithContext3 } from "@dxos/context";
3707
+ import { Context as Context8, cancelWithContext as cancelWithContext3 } from "@dxos/context";
3687
3708
  import { getCredentialAssertion as getCredentialAssertion2 } from "@dxos/credentials";
3688
- import { invariant as invariant12 } from "@dxos/invariant";
3709
+ import { invariant as invariant11 } from "@dxos/invariant";
3689
3710
  import { PublicKey as PublicKey9 } from "@dxos/keys";
3690
3711
  import { log as log10 } from "@dxos/log";
3691
3712
  import { trace as trace7 } from "@dxos/protocols";
@@ -3696,7 +3717,7 @@ import { ComplexMap as ComplexMap3, deferFunction as deferFunction2, forEachAsyn
3696
3717
  // packages/sdk/client-services/src/packlets/spaces/genesis.ts
3697
3718
  import { createCredential } from "@dxos/credentials";
3698
3719
  import { failUndefined } from "@dxos/debug";
3699
- import { AdmittedFeed as AdmittedFeed4, SpaceMember as SpaceMember2 } from "@dxos/protocols/proto/dxos/halo/credentials";
3720
+ import { AdmittedFeed as AdmittedFeed4, SpaceMember } from "@dxos/protocols/proto/dxos/halo/credentials";
3700
3721
  import { Timeframe as Timeframe3 } from "@dxos/timeframe";
3701
3722
  var spaceGenesis = async (keyring, signingContext, space, automergeRoot) => {
3702
3723
  const credentials = [
@@ -3716,7 +3737,7 @@ var spaceGenesis = async (keyring, signingContext, space, automergeRoot) => {
3716
3737
  assertion: {
3717
3738
  "@type": "dxos.halo.credentials.SpaceMember",
3718
3739
  spaceKey: space.key,
3719
- role: SpaceMember2.Role.ADMIN,
3740
+ role: SpaceMember.Role.ADMIN,
3720
3741
  profile: signingContext.getProfile(),
3721
3742
  genesisFeedKey: space.controlFeedKey ?? failUndefined()
3722
3743
  }
@@ -3774,7 +3795,7 @@ function _ts_decorate5(decorators, target, key, desc) {
3774
3795
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3775
3796
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3776
3797
  }
3777
- var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts";
3798
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts";
3778
3799
  var PRESENCE_ANNOUNCE_INTERVAL = 1e4;
3779
3800
  var PRESENCE_OFFLINE_TIMEOUT = 2e4;
3780
3801
  var DataSpaceManager = class {
@@ -3785,7 +3806,7 @@ var DataSpaceManager = class {
3785
3806
  this._signingContext = _signingContext;
3786
3807
  this._feedStore = _feedStore;
3787
3808
  this._automergeHost = _automergeHost;
3788
- this._ctx = new Context9();
3809
+ this._ctx = new Context8();
3789
3810
  this.updated = new Event7();
3790
3811
  this._spaces = new ComplexMap3(PublicKey9.hash);
3791
3812
  this._isOpen = false;
@@ -3800,7 +3821,7 @@ var DataSpaceManager = class {
3800
3821
  }
3801
3822
  async open() {
3802
3823
  log10("open", void 0, {
3803
- F: __dxlog_file13,
3824
+ F: __dxlog_file12,
3804
3825
  L: 98,
3805
3826
  S: this,
3806
3827
  C: (f, a) => f(...a)
@@ -3808,7 +3829,7 @@ var DataSpaceManager = class {
3808
3829
  log10.trace("dxos.echo.data-space-manager.open", trace7.begin({
3809
3830
  id: this._instanceId
3810
3831
  }), {
3811
- F: __dxlog_file13,
3832
+ F: __dxlog_file12,
3812
3833
  L: 99,
3813
3834
  S: this,
3814
3835
  C: (f, a) => f(...a)
@@ -3816,7 +3837,7 @@ var DataSpaceManager = class {
3816
3837
  log10("metadata loaded", {
3817
3838
  spaces: this._metadataStore.spaces.length
3818
3839
  }, {
3819
- F: __dxlog_file13,
3840
+ F: __dxlog_file12,
3820
3841
  L: 100,
3821
3842
  S: this,
3822
3843
  C: (f, a) => f(...a)
@@ -3826,7 +3847,7 @@ var DataSpaceManager = class {
3826
3847
  log10("load space", {
3827
3848
  spaceMetadata
3828
3849
  }, {
3829
- F: __dxlog_file13,
3850
+ F: __dxlog_file12,
3830
3851
  L: 104,
3831
3852
  S: this,
3832
3853
  C: (f, a) => f(...a)
@@ -3837,7 +3858,7 @@ var DataSpaceManager = class {
3837
3858
  spaceMetadata,
3838
3859
  err
3839
3860
  }, {
3840
- F: __dxlog_file13,
3861
+ F: __dxlog_file12,
3841
3862
  L: 107,
3842
3863
  S: this,
3843
3864
  C: (f, a) => f(...a)
@@ -3854,7 +3875,7 @@ var DataSpaceManager = class {
3854
3875
  log10.trace("dxos.echo.data-space-manager.open", trace7.end({
3855
3876
  id: this._instanceId
3856
3877
  }), {
3857
- F: __dxlog_file13,
3878
+ F: __dxlog_file12,
3858
3879
  L: 120,
3859
3880
  S: this,
3860
3881
  C: (f, a) => f(...a)
@@ -3862,7 +3883,7 @@ var DataSpaceManager = class {
3862
3883
  }
3863
3884
  async close() {
3864
3885
  log10("close", void 0, {
3865
- F: __dxlog_file13,
3886
+ F: __dxlog_file12,
3866
3887
  L: 125,
3867
3888
  S: this,
3868
3889
  C: (f, a) => f(...a)
@@ -3877,8 +3898,8 @@ var DataSpaceManager = class {
3877
3898
  * Creates a new space writing the genesis credentials to the control feed.
3878
3899
  */
3879
3900
  async createSpace() {
3880
- invariant12(this._isOpen, "Not open.", {
3881
- F: __dxlog_file13,
3901
+ invariant11(this._isOpen, "Not open.", {
3902
+ F: __dxlog_file12,
3882
3903
  L: 138,
3883
3904
  S: this,
3884
3905
  A: [
@@ -3899,7 +3920,7 @@ var DataSpaceManager = class {
3899
3920
  log10("creating space...", {
3900
3921
  spaceKey
3901
3922
  }, {
3902
- F: __dxlog_file13,
3923
+ F: __dxlog_file12,
3903
3924
  L: 150,
3904
3925
  S: this,
3905
3926
  C: (f, a) => f(...a)
@@ -3914,8 +3935,8 @@ var DataSpaceManager = class {
3914
3935
  const credentials = await spaceGenesis(this._keyring, this._signingContext, space.inner, automergeRoot.url);
3915
3936
  await this._metadataStore.addSpace(metadata);
3916
3937
  const memberCredential = credentials[1];
3917
- invariant12(getCredentialAssertion2(memberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
3918
- F: __dxlog_file13,
3938
+ invariant11(getCredentialAssertion2(memberCredential)["@type"] === "dxos.halo.credentials.SpaceMember", void 0, {
3939
+ F: __dxlog_file12,
3919
3940
  L: 163,
3920
3941
  S: this,
3921
3942
  A: [
@@ -3933,13 +3954,13 @@ var DataSpaceManager = class {
3933
3954
  log10("accept space", {
3934
3955
  opts
3935
3956
  }, {
3936
- F: __dxlog_file13,
3957
+ F: __dxlog_file12,
3937
3958
  L: 175,
3938
3959
  S: this,
3939
3960
  C: (f, a) => f(...a)
3940
3961
  });
3941
- invariant12(this._isOpen, "Not open.", {
3942
- F: __dxlog_file13,
3962
+ invariant11(this._isOpen, "Not open.", {
3963
+ F: __dxlog_file12,
3943
3964
  L: 176,
3944
3965
  S: this,
3945
3966
  A: [
@@ -3947,8 +3968,8 @@ var DataSpaceManager = class {
3947
3968
  "'Not open.'"
3948
3969
  ]
3949
3970
  });
3950
- invariant12(!this._spaces.has(opts.spaceKey), "Space already exists.", {
3951
- F: __dxlog_file13,
3971
+ invariant11(!this._spaces.has(opts.spaceKey), "Space already exists.", {
3972
+ F: __dxlog_file12,
3952
3973
  L: 177,
3953
3974
  S: this,
3954
3975
  A: [
@@ -3983,7 +4004,7 @@ var DataSpaceManager = class {
3983
4004
  log10("construct space", {
3984
4005
  metadata
3985
4006
  }, {
3986
- F: __dxlog_file13,
4007
+ F: __dxlog_file12,
3987
4008
  L: 210,
3988
4009
  S: this,
3989
4010
  C: (f, a) => f(...a)
@@ -4021,7 +4042,7 @@ var DataSpaceManager = class {
4021
4042
  },
4022
4043
  onAuthFailure: () => {
4023
4044
  log10.warn("auth failure", void 0, {
4024
- F: __dxlog_file13,
4045
+ F: __dxlog_file12,
4025
4046
  L: 247,
4026
4047
  S: this,
4027
4048
  C: (f, a) => f(...a)
@@ -4045,7 +4066,7 @@ var DataSpaceManager = class {
4045
4066
  log10("before space ready", {
4046
4067
  space: space.key
4047
4068
  }, {
4048
- F: __dxlog_file13,
4069
+ F: __dxlog_file12,
4049
4070
  L: 265,
4050
4071
  S: this,
4051
4072
  C: (f, a) => f(...a)
@@ -4056,7 +4077,7 @@ var DataSpaceManager = class {
4056
4077
  space: space.key,
4057
4078
  open: this._isOpen
4058
4079
  }, {
4059
- F: __dxlog_file13,
4080
+ F: __dxlog_file12,
4060
4081
  L: 268,
4061
4082
  S: this,
4062
4083
  C: (f, a) => f(...a)
@@ -4069,7 +4090,7 @@ var DataSpaceManager = class {
4069
4090
  log10("before space close", {
4070
4091
  space: space.key
4071
4092
  }, {
4072
- F: __dxlog_file13,
4093
+ F: __dxlog_file12,
4073
4094
  L: 274,
4074
4095
  S: this,
4075
4096
  C: (f, a) => f(...a)
@@ -4106,14 +4127,14 @@ DataSpaceManager = _ts_decorate5([
4106
4127
  ], DataSpaceManager);
4107
4128
 
4108
4129
  // packages/sdk/client-services/src/packlets/spaces/spaces-service.ts
4109
- import { EventSubscriptions as EventSubscriptions2, UpdateScheduler, scheduleTask as scheduleTask6 } from "@dxos/async";
4130
+ import { EventSubscriptions as EventSubscriptions2, UpdateScheduler, scheduleTask as scheduleTask5 } from "@dxos/async";
4110
4131
  import { Stream as Stream10 } from "@dxos/codec-protobuf";
4111
4132
  import { raise as raise2 } from "@dxos/debug";
4112
- import { invariant as invariant13 } from "@dxos/invariant";
4133
+ import { invariant as invariant12 } from "@dxos/invariant";
4113
4134
  import { log as log11 } from "@dxos/log";
4114
4135
  import { ApiError, SpaceNotFoundError, encodeError } from "@dxos/protocols";
4115
- import { SpaceMember as SpaceMember3, SpaceState as SpaceState3 } from "@dxos/protocols/proto/dxos/client/services";
4116
- var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/spaces-service.ts";
4136
+ import { SpaceMember as SpaceMember2, SpaceState as SpaceState3 } from "@dxos/protocols/proto/dxos/client/services";
4137
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/spaces/spaces-service.ts";
4117
4138
  var SpacesServiceImpl = class {
4118
4139
  constructor(_identityManager, _spaceManager, _getDataSpaceManager) {
4119
4140
  this._identityManager = _identityManager;
@@ -4152,7 +4173,7 @@ var SpacesServiceImpl = class {
4152
4173
  log11("update", {
4153
4174
  spaces
4154
4175
  }, {
4155
- F: __dxlog_file14,
4176
+ F: __dxlog_file13,
4156
4177
  L: 77,
4157
4178
  S: this,
4158
4179
  C: (f, a) => f(...a)
@@ -4163,7 +4184,7 @@ var SpacesServiceImpl = class {
4163
4184
  }, {
4164
4185
  maxFrequency: false ? void 0 : 2
4165
4186
  });
4166
- scheduleTask6(ctx, async () => {
4187
+ scheduleTask5(ctx, async () => {
4167
4188
  const dataSpaceManager = await this._getDataSpaceManager();
4168
4189
  const subscriptions = new EventSubscriptions2();
4169
4190
  ctx.onDispose(() => subscriptions.clear());
@@ -4197,7 +4218,7 @@ var SpacesServiceImpl = class {
4197
4218
  }
4198
4219
  subscribeMessages({ spaceKey, channel }) {
4199
4220
  return new Stream10(({ ctx, next }) => {
4200
- scheduleTask6(ctx, async () => {
4221
+ scheduleTask5(ctx, async () => {
4201
4222
  const dataSpaceManager = await this._getDataSpaceManager();
4202
4223
  const space = dataSpaceManager.spaces.get(spaceKey) ?? raise2(new SpaceNotFoundError(spaceKey));
4203
4224
  const handle = space.listen(getChannelId(channel), (message) => {
@@ -4216,7 +4237,7 @@ var SpacesServiceImpl = class {
4216
4237
  }
4217
4238
  };
4218
4239
  ctx.onDispose(() => space.spaceState.removeCredentialProcessor(processor));
4219
- scheduleTask6(ctx, async () => {
4240
+ scheduleTask5(ctx, async () => {
4220
4241
  await space.spaceState.addCredentialProcessor(processor);
4221
4242
  if (noTail) {
4222
4243
  close();
@@ -4234,8 +4255,8 @@ var SpacesServiceImpl = class {
4234
4255
  }
4235
4256
  });
4236
4257
  } else {
4237
- invariant13(!credential.id, "Id on unsigned credentials is not allowed", {
4238
- F: __dxlog_file14,
4258
+ invariant12(!credential.id, "Id on unsigned credentials is not allowed", {
4259
+ F: __dxlog_file13,
4239
4260
  L: 164,
4240
4261
  S: this,
4241
4262
  A: [
@@ -4243,8 +4264,8 @@ var SpacesServiceImpl = class {
4243
4264
  "'Id on unsigned credentials is not allowed'"
4244
4265
  ]
4245
4266
  });
4246
- invariant13(this._identityManager.identity, "Identity is not available", {
4247
- F: __dxlog_file14,
4267
+ invariant12(this._identityManager.identity, "Identity is not available", {
4268
+ F: __dxlog_file13,
4248
4269
  L: 165,
4249
4270
  S: this,
4250
4271
  A: [
@@ -4253,8 +4274,8 @@ var SpacesServiceImpl = class {
4253
4274
  ]
4254
4275
  });
4255
4276
  const signer = this._identityManager.identity.getIdentityCredentialSigner();
4256
- invariant13(credential.issuer.equals(signer.getIssuer()), void 0, {
4257
- F: __dxlog_file14,
4277
+ invariant12(credential.issuer.equals(signer.getIssuer()), void 0, {
4278
+ F: __dxlog_file13,
4258
4279
  L: 167,
4259
4280
  S: this,
4260
4281
  A: [
@@ -4310,7 +4331,7 @@ var SpacesServiceImpl = class {
4310
4331
  identityKey: member.key,
4311
4332
  profile: member.profile ?? {}
4312
4333
  },
4313
- presence: member.removed ? SpaceMember3.PresenceState.REMOVED : isMe || peers.length > 0 ? SpaceMember3.PresenceState.ONLINE : SpaceMember3.PresenceState.OFFLINE,
4334
+ presence: member.removed ? SpaceMember2.PresenceState.REMOVED : isMe || peers.length > 0 ? SpaceMember2.PresenceState.ONLINE : SpaceMember2.PresenceState.OFFLINE,
4314
4335
  peerStates: peers
4315
4336
  };
4316
4337
  }),
@@ -4324,18 +4345,18 @@ var getChannelId = (channel) => `user-channel/${channel}`;
4324
4345
 
4325
4346
  // packages/sdk/client-services/src/packlets/services/service-context.ts
4326
4347
  import { Trigger as Trigger5 } from "@dxos/async";
4327
- import { Context as Context10 } from "@dxos/context";
4348
+ import { Context as Context9, Resource } from "@dxos/context";
4328
4349
  import { getCredentialAssertion as getCredentialAssertion3 } from "@dxos/credentials";
4329
4350
  import { failUndefined as failUndefined2 } from "@dxos/debug";
4330
4351
  import { AutomergeHost, MetadataStore, SnapshotStore, SpaceManager, valueEncoding } from "@dxos/echo-pipeline";
4331
4352
  import { FeedFactory, FeedStore } from "@dxos/feed-store";
4332
- import { IndexMetadataStore, IndexStore, Indexer } from "@dxos/indexing";
4333
- import { invariant as invariant14 } from "@dxos/invariant";
4353
+ import { IndexMetadataStore, IndexStore, Indexer, createStorageCallbacks } from "@dxos/indexing";
4354
+ import { invariant as invariant13 } from "@dxos/invariant";
4334
4355
  import { Keyring } from "@dxos/keyring";
4335
4356
  import { PublicKey as PublicKey10 } from "@dxos/keys";
4336
4357
  import { log as log12 } from "@dxos/log";
4337
- import { InvalidStorageVersionError, STORAGE_VERSION as STORAGE_VERSION2, trace as trace8 } from "@dxos/protocols";
4338
- import { Invitation as Invitation6 } from "@dxos/protocols/proto/dxos/client/services";
4358
+ import { InvalidStorageVersionError, STORAGE_VERSION, trace as trace8 } from "@dxos/protocols";
4359
+ import { Invitation as Invitation5 } from "@dxos/protocols/proto/dxos/client/services";
4339
4360
  import { BlobStore } from "@dxos/teleport-extension-object-sync";
4340
4361
  import { trace as Trace2 } from "@dxos/tracing";
4341
4362
  import { safeInstanceof } from "@dxos/util";
@@ -4344,7 +4365,7 @@ import { safeInstanceof } from "@dxos/util";
4344
4365
  import { getHeads } from "@dxos/automerge/automerge";
4345
4366
  import { warnAfterTimeout as warnAfterTimeout2 } from "@dxos/debug";
4346
4367
  import { idCodec } from "@dxos/protocols";
4347
- var createLoadDocuments = (automergeHost) => (
4368
+ var createSelectedDocumentsIterator = (automergeHost) => (
4348
4369
  /**
4349
4370
  * Get object data blobs from Automerge Repo by ids.
4350
4371
  * @param ids
@@ -4357,17 +4378,17 @@ var createLoadDocuments = (automergeHost) => (
4357
4378
  await warnAfterTimeout2(5e3, "to long to load doc", () => handle.whenReady());
4358
4379
  const doc = handle.docSync();
4359
4380
  const hash = getHeads(doc).join("");
4360
- yield [
4381
+ yield doc.objects?.[objectId] ? [
4361
4382
  {
4362
4383
  id,
4363
4384
  object: doc.objects[objectId],
4364
4385
  currentHash: hash
4365
4386
  }
4366
- ];
4387
+ ] : [];
4367
4388
  }
4368
4389
  }
4369
4390
  );
4370
- var createGetAllDocuments = (automergeHost) => (
4391
+ var createDocumentsIterator = (automergeHost) => (
4371
4392
  /**
4372
4393
  * Recursively get all object data blobs from Automerge Repo.
4373
4394
  * @param ids
@@ -4390,7 +4411,7 @@ var createGetAllDocuments = (automergeHost) => (
4390
4411
  objectId
4391
4412
  }),
4392
4413
  object,
4393
- currentHash: heads.at(-1)
4414
+ currentHash: heads.join("")
4394
4415
  };
4395
4416
  });
4396
4417
  }
@@ -4430,10 +4451,12 @@ function _ts_decorate6(decorators, target, key, desc) {
4430
4451
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4431
4452
  return c > 3 && r && Object.defineProperty(target, key, r), r;
4432
4453
  }
4433
- var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-context.ts";
4434
- var ServiceContext = class {
4435
- constructor(storage, networkManager, signalManager, _runtimeParams) {
4454
+ var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-context.ts";
4455
+ var ServiceContext = class extends Resource {
4456
+ constructor(storage, level, networkManager, signalManager, _runtimeParams) {
4457
+ super();
4436
4458
  this.storage = storage;
4459
+ this.level = level;
4437
4460
  this.networkManager = networkManager;
4438
4461
  this.signalManager = signalManager;
4439
4462
  this._runtimeParams = _runtimeParams;
@@ -4463,66 +4486,81 @@ var ServiceContext = class {
4463
4486
  });
4464
4487
  this.identityManager = new IdentityManager(this.metadataStore, this.keyring, this.feedStore, this.spaceManager, this._runtimeParams);
4465
4488
  this.indexMetadata = new IndexMetadataStore({
4466
- directory: storage.createDirectory("index-metadata")
4489
+ db: level.sublevel("index-metadata")
4467
4490
  });
4468
4491
  this.automergeHost = new AutomergeHost({
4469
4492
  directory: storage.createDirectory("automerge"),
4470
- metadata: this.indexMetadata
4493
+ db: level.sublevel("automerge"),
4494
+ storageCallbacks: createStorageCallbacks({
4495
+ host: () => this.automergeHost,
4496
+ metadata: this.indexMetadata
4497
+ })
4471
4498
  });
4472
4499
  this.indexer = new Indexer({
4473
4500
  indexStore: new IndexStore({
4474
- directory: storage.createDirectory("index-store")
4501
+ db: level.sublevel("index-storage")
4475
4502
  }),
4476
4503
  metadataStore: this.indexMetadata,
4477
- loadDocuments: createLoadDocuments(this.automergeHost),
4478
- getAllDocuments: createGetAllDocuments(this.automergeHost)
4504
+ loadDocuments: createSelectedDocumentsIterator(this.automergeHost),
4505
+ getAllDocuments: createDocumentsIterator(this.automergeHost)
4479
4506
  });
4480
4507
  this.invitations = new InvitationsHandler(this.networkManager);
4481
- this._handlerFactories.set(Invitation6.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => this.identityManager.identity ?? failUndefined2(), this._acceptIdentity.bind(this)));
4508
+ this.invitationsManager = new InvitationsManager(this.invitations, (invitation) => this.getInvitationHandler(invitation), this.metadataStore);
4509
+ this._handlerFactories.set(Invitation5.Kind.DEVICE, () => new DeviceInvitationProtocol(this.keyring, () => this.identityManager.identity ?? failUndefined2(), this._acceptIdentity.bind(this)));
4482
4510
  }
4483
- async open(ctx) {
4511
+ async _open(ctx) {
4484
4512
  await this._checkStorageVersion();
4485
4513
  log12("opening...", void 0, {
4486
- F: __dxlog_file15,
4487
- L: 151,
4514
+ F: __dxlog_file14,
4515
+ L: 164,
4488
4516
  S: this,
4489
4517
  C: (f, a) => f(...a)
4490
4518
  });
4491
4519
  log12.trace("dxos.sdk.service-context.open", trace8.begin({
4492
4520
  id: this._instanceId
4493
4521
  }), {
4494
- F: __dxlog_file15,
4495
- L: 152,
4522
+ F: __dxlog_file14,
4523
+ L: 165,
4496
4524
  S: this,
4497
4525
  C: (f, a) => f(...a)
4498
4526
  });
4499
4527
  await this.signalManager.open();
4500
4528
  await this.networkManager.open();
4529
+ await this.automergeHost.open();
4501
4530
  await this.metadataStore.load();
4502
4531
  await this.spaceManager.open();
4503
4532
  await this.identityManager.open(ctx);
4504
4533
  if (this.identityManager.identity) {
4505
4534
  await this._initialize(ctx);
4506
4535
  }
4507
- log12.trace("dxos.sdk.service-context.open", trace8.end({
4508
- id: this._instanceId
4536
+ const loadedInvitations = await this.invitationsManager.loadPersistentInvitations();
4537
+ log12("loaded persistent invitations", {
4538
+ count: loadedInvitations.invitations?.length
4539
+ }, {
4540
+ F: __dxlog_file14,
4541
+ L: 178,
4542
+ S: this,
4543
+ C: (f, a) => f(...a)
4544
+ });
4545
+ log12.trace("dxos.sdk.service-context.open", trace8.end({
4546
+ id: this._instanceId
4509
4547
  }), {
4510
- F: __dxlog_file15,
4511
- L: 162,
4548
+ F: __dxlog_file14,
4549
+ L: 180,
4512
4550
  S: this,
4513
4551
  C: (f, a) => f(...a)
4514
4552
  });
4515
4553
  log12("opened", void 0, {
4516
- F: __dxlog_file15,
4517
- L: 163,
4554
+ F: __dxlog_file14,
4555
+ L: 181,
4518
4556
  S: this,
4519
4557
  C: (f, a) => f(...a)
4520
4558
  });
4521
4559
  }
4522
- async close() {
4560
+ async _close() {
4523
4561
  log12("closing...", void 0, {
4524
- F: __dxlog_file15,
4525
- L: 167,
4562
+ F: __dxlog_file14,
4563
+ L: 185,
4526
4564
  S: this,
4527
4565
  C: (f, a) => f(...a)
4528
4566
  });
@@ -4539,22 +4577,22 @@ var ServiceContext = class {
4539
4577
  await this.metadataStore.close();
4540
4578
  await this.indexer.destroy();
4541
4579
  log12("closed", void 0, {
4542
- F: __dxlog_file15,
4543
- L: 180,
4580
+ F: __dxlog_file14,
4581
+ L: 198,
4544
4582
  S: this,
4545
4583
  C: (f, a) => f(...a)
4546
4584
  });
4547
4585
  }
4548
4586
  async createIdentity(params = {}) {
4549
4587
  const identity = await this.identityManager.createIdentity(params);
4550
- await this._initialize(new Context10());
4588
+ await this._initialize(new Context9());
4551
4589
  return identity;
4552
4590
  }
4553
4591
  getInvitationHandler(invitation) {
4554
4592
  const factory = this._handlerFactories.get(invitation.kind);
4555
- invariant14(factory, `Unknown invitation kind: ${invitation.kind}`, {
4556
- F: __dxlog_file15,
4557
- L: 191,
4593
+ invariant13(factory, `Unknown invitation kind: ${invitation.kind}`, {
4594
+ F: __dxlog_file14,
4595
+ L: 209,
4558
4596
  S: this,
4559
4597
  A: [
4560
4598
  "factory",
@@ -4573,20 +4611,20 @@ var ServiceContext = class {
4573
4611
  }
4574
4612
  async _acceptIdentity(params) {
4575
4613
  const identity = await this.identityManager.acceptIdentity(params);
4576
- await this._initialize(new Context10());
4614
+ await this._initialize(new Context9());
4577
4615
  return identity;
4578
4616
  }
4579
4617
  async _checkStorageVersion() {
4580
4618
  await this.metadataStore.load();
4581
- if (this.metadataStore.version !== STORAGE_VERSION2) {
4582
- throw new InvalidStorageVersionError(STORAGE_VERSION2, this.metadataStore.version);
4619
+ if (this.metadataStore.version !== STORAGE_VERSION) {
4620
+ throw new InvalidStorageVersionError(STORAGE_VERSION, this.metadataStore.version);
4583
4621
  }
4584
4622
  }
4585
4623
  // Called when identity is created.
4586
4624
  async _initialize(ctx) {
4587
4625
  log12("initializing spaces...", void 0, {
4588
- F: __dxlog_file15,
4589
- L: 222,
4626
+ F: __dxlog_file14,
4627
+ L: 240,
4590
4628
  S: this,
4591
4629
  C: (f, a) => f(...a)
4592
4630
  });
@@ -4606,10 +4644,10 @@ var ServiceContext = class {
4606
4644
  };
4607
4645
  this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.keyring, signingContext, this.feedStore, this.automergeHost, this._runtimeParams);
4608
4646
  await this.dataSpaceManager.open();
4609
- this._handlerFactories.set(Invitation6.Kind.SPACE, (invitation) => {
4610
- invariant14(this.dataSpaceManager, "dataSpaceManager not initialized yet", {
4611
- F: __dxlog_file15,
4612
- L: 246,
4647
+ this._handlerFactories.set(Invitation5.Kind.SPACE, (invitation) => {
4648
+ invariant13(this.dataSpaceManager, "dataSpaceManager not initialized yet", {
4649
+ F: __dxlog_file14,
4650
+ L: 264,
4613
4651
  S: this,
4614
4652
  A: [
4615
4653
  "this.dataSpaceManager",
@@ -4632,8 +4670,8 @@ var ServiceContext = class {
4632
4670
  log12("dataSpaceManager not initialized yet, ignoring space admission", {
4633
4671
  details: assertion
4634
4672
  }, {
4635
- F: __dxlog_file15,
4636
- L: 262,
4673
+ F: __dxlog_file14,
4674
+ L: 280,
4637
4675
  S: this,
4638
4676
  C: (f, a) => f(...a)
4639
4677
  });
@@ -4643,8 +4681,8 @@ var ServiceContext = class {
4643
4681
  log12("space already exists, ignoring space admission", {
4644
4682
  details: assertion
4645
4683
  }, {
4646
- F: __dxlog_file15,
4647
- L: 266,
4684
+ F: __dxlog_file14,
4685
+ L: 284,
4648
4686
  S: this,
4649
4687
  C: (f, a) => f(...a)
4650
4688
  });
@@ -4654,8 +4692,8 @@ var ServiceContext = class {
4654
4692
  log12("accepting space recorded in halo", {
4655
4693
  details: assertion
4656
4694
  }, {
4657
- F: __dxlog_file15,
4658
- L: 271,
4695
+ F: __dxlog_file14,
4696
+ L: 289,
4659
4697
  S: this,
4660
4698
  C: (f, a) => f(...a)
4661
4699
  });
@@ -4665,8 +4703,8 @@ var ServiceContext = class {
4665
4703
  });
4666
4704
  } catch (err) {
4667
4705
  log12.catch(err, void 0, {
4668
- F: __dxlog_file15,
4669
- L: 277,
4706
+ F: __dxlog_file14,
4707
+ L: 295,
4670
4708
  S: this,
4671
4709
  C: (f, a) => f(...a)
4672
4710
  });
@@ -4678,7 +4716,7 @@ var ServiceContext = class {
4678
4716
  };
4679
4717
  _ts_decorate6([
4680
4718
  Trace2.span()
4681
- ], ServiceContext.prototype, "open", null);
4719
+ ], ServiceContext.prototype, "_open", null);
4682
4720
  _ts_decorate6([
4683
4721
  Trace2.span()
4684
4722
  ], ServiceContext.prototype, "_initialize", null);
@@ -4711,195 +4749,271 @@ var ServiceRegistry = class {
4711
4749
  }
4712
4750
  };
4713
4751
 
4714
- // packages/sdk/client-services/src/packlets/locks/browser.ts
4715
- import { asyncTimeout as asyncTimeout2, Trigger as Trigger6 } from "@dxos/async";
4716
- import { RESOURCE_LOCK_TIMEOUT } from "@dxos/client-protocol";
4717
- import { log as log13, logInfo } from "@dxos/log";
4718
- function _ts_decorate7(decorators, target, key, desc) {
4719
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4720
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
4721
- r = Reflect.decorate(decorators, target, key, desc);
4722
- else
4723
- for (var i = decorators.length - 1; i >= 0; i--)
4724
- if (d = decorators[i])
4725
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4726
- return c > 3 && r && Object.defineProperty(target, key, r), r;
4727
- }
4728
- var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/locks/browser.ts";
4729
- var Message;
4730
- (function(Message2) {
4731
- Message2["ACQUIRING"] = "acquiring";
4732
- })(Message || (Message = {}));
4733
- var Lock = class {
4734
- constructor({ lockKey, onAcquire, onRelease }) {
4735
- this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
4736
- this._releaseTrigger = new Trigger6();
4737
- this._lockKey = lockKey;
4738
- this._onAcquire = onAcquire;
4739
- this._onRelease = onRelease;
4740
- this._broadcastChannel.onmessage = this._onMessage.bind(this);
4741
- }
4742
- get lockKey() {
4743
- return this._lockKey;
4744
- }
4745
- async acquire() {
4746
- this._broadcastChannel.postMessage({
4747
- message: "acquiring"
4748
- });
4749
- try {
4750
- log13("aquiring lock...", void 0, {
4751
- F: __dxlog_file16,
4752
- L: 42,
4753
- S: this,
4754
- C: (f, a) => f(...a)
4755
- });
4756
- await asyncTimeout2(this._requestLock(), RESOURCE_LOCK_TIMEOUT);
4757
- log13("acquired lock", void 0, {
4758
- F: __dxlog_file16,
4759
- L: 44,
4760
- S: this,
4761
- C: (f, a) => f(...a)
4762
- });
4763
- } catch {
4764
- log13("stealing lock...", void 0, {
4765
- F: __dxlog_file16,
4766
- L: 46,
4767
- S: this,
4768
- C: (f, a) => f(...a)
4769
- });
4770
- await this._requestLock(true);
4771
- log13("stolen lock", void 0, {
4772
- F: __dxlog_file16,
4773
- L: 48,
4774
- S: this,
4775
- C: (f, a) => f(...a)
4776
- });
4752
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts
4753
+ import { getFirstStreamValue } from "@dxos/codec-protobuf";
4754
+ import { credentialTypeFilter } from "@dxos/credentials";
4755
+ import { invariant as invariant14 } from "@dxos/invariant";
4756
+ import { STORAGE_VERSION as STORAGE_VERSION2 } from "@dxos/protocols";
4757
+ import { SpaceMember as SpaceMember3 } from "@dxos/protocols/proto/dxos/client/services";
4758
+ import { TRACE_PROCESSOR } from "@dxos/tracing";
4759
+
4760
+ // packages/sdk/client-services/src/version.ts
4761
+ var DXOS_VERSION = "0.4.10-main.068c3d8";
4762
+
4763
+ // packages/sdk/client-services/src/packlets/services/platform.ts
4764
+ import { Platform } from "@dxos/protocols/proto/dxos/client/services";
4765
+ var getPlatform = () => {
4766
+ if (process.browser) {
4767
+ if (typeof window !== "undefined") {
4768
+ const { userAgent } = window.navigator;
4769
+ return {
4770
+ type: Platform.PLATFORM_TYPE.BROWSER,
4771
+ userAgent,
4772
+ uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1e3)
4773
+ };
4774
+ } else {
4775
+ return {
4776
+ type: Platform.PLATFORM_TYPE.SHARED_WORKER,
4777
+ uptime: Math.floor((Date.now() - performance.timeOrigin) / 1e3)
4778
+ };
4777
4779
  }
4780
+ } else {
4781
+ const { platform: platform2, version, arch } = process;
4782
+ return {
4783
+ type: Platform.PLATFORM_TYPE.NODE,
4784
+ platform: platform2,
4785
+ arch,
4786
+ runtime: version,
4787
+ uptime: Math.floor(process.uptime()),
4788
+ memory: process.memoryUsage()
4789
+ };
4778
4790
  }
4779
- async release() {
4780
- this._releaseTrigger.wake();
4791
+ };
4792
+
4793
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts
4794
+ var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/diagnostics/diagnostics.ts";
4795
+ var DEFAULT_TIMEOUT = 1e3;
4796
+ var createDiagnostics = async (clientServices, serviceContext, config) => {
4797
+ const diagnostics = {
4798
+ created: (/* @__PURE__ */ new Date()).toISOString(),
4799
+ platform: getPlatform(),
4800
+ client: {
4801
+ version: DXOS_VERSION,
4802
+ storage: {
4803
+ version: STORAGE_VERSION2
4804
+ }
4805
+ },
4806
+ trace: TRACE_PROCESSOR.getDiagnostics()
4807
+ };
4808
+ {
4809
+ invariant14(clientServices.LoggingService, "SystemService is not available.", {
4810
+ F: __dxlog_file15,
4811
+ L: 108,
4812
+ S: void 0,
4813
+ A: [
4814
+ "clientServices.LoggingService",
4815
+ "'SystemService is not available.'"
4816
+ ]
4817
+ });
4818
+ diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {
4819
+ timeout: DEFAULT_TIMEOUT
4820
+ }).catch(() => void 0);
4781
4821
  }
4782
- _onMessage(event) {
4783
- if (event.data.message === "acquiring") {
4784
- this._releaseTrigger.wake();
4822
+ if (typeof navigator !== "undefined" && navigator.storage) {
4823
+ const map = /* @__PURE__ */ new Map();
4824
+ const dir = await navigator.storage.getDirectory();
4825
+ for await (const filename of dir?.keys()) {
4826
+ const idx = filename.indexOf("-", filename.indexOf("-") + 1);
4827
+ if (idx === -1) {
4828
+ continue;
4829
+ }
4830
+ map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);
4785
4831
  }
4832
+ diagnostics.storage = Array.from(map.entries()).sort((a, b) => b[1] - a[1]).map(([file, count]) => ({
4833
+ file,
4834
+ count
4835
+ }));
4786
4836
  }
4787
- async _requestLock(steal = false) {
4788
- log13("requesting lock...", {
4789
- steal
4790
- }, {
4791
- F: __dxlog_file16,
4792
- L: 63,
4793
- S: this,
4794
- C: (f, a) => f(...a)
4795
- });
4796
- const acquired = new Trigger6();
4797
- void navigator.locks.request(this._lockKey, {
4798
- steal
4799
- }, async () => {
4800
- await this._onAcquire?.();
4801
- acquired.wake();
4802
- this._releaseTrigger = new Trigger6();
4803
- await this._releaseTrigger.wait();
4804
- log13("releasing lock...", void 0, {
4805
- F: __dxlog_file16,
4806
- L: 72,
4807
- S: this,
4808
- C: (f, a) => f(...a)
4809
- });
4810
- await this._onRelease?.();
4811
- log13("released lock", void 0, {
4812
- F: __dxlog_file16,
4813
- L: 74,
4814
- S: this,
4815
- C: (f, a) => f(...a)
4816
- });
4817
- }).catch(async () => {
4818
- await this._onRelease?.();
4819
- });
4820
- await acquired.wait();
4821
- log13("recieved lock", {
4822
- steal
4823
- }, {
4824
- F: __dxlog_file16,
4825
- L: 81,
4826
- S: this,
4827
- C: (f, a) => f(...a)
4828
- });
4837
+ const identity = serviceContext.identityManager.identity;
4838
+ if (identity) {
4839
+ diagnostics.identity = {
4840
+ identityKey: identity.identityKey,
4841
+ spaceKey: identity.space.key,
4842
+ profile: identity.profileDocument
4843
+ };
4844
+ const { devices } = await getFirstStreamValue(clientServices.DevicesService.queryDevices(), {
4845
+ timeout: DEFAULT_TIMEOUT
4846
+ }).catch(() => void 0) ?? {};
4847
+ diagnostics.devices = devices;
4848
+ if (serviceContext.dataSpaceManager) {
4849
+ diagnostics.spaces = await Promise.all(Array.from(serviceContext.dataSpaceManager.spaces.values()).map((space) => getSpaceStats(space)) ?? []);
4850
+ }
4851
+ const { feeds = [] } = await getFirstStreamValue(clientServices.DevtoolsHost.subscribeToFeeds({}), {
4852
+ timeout: DEFAULT_TIMEOUT
4853
+ }).catch(() => void 0) ?? {};
4854
+ diagnostics.feeds = feeds.map(({ feedKey, bytes, length }) => ({
4855
+ feedKey,
4856
+ bytes,
4857
+ length
4858
+ }));
4859
+ const status = await getFirstStreamValue(clientServices.NetworkService.queryStatus(), {
4860
+ timeout: DEFAULT_TIMEOUT
4861
+ }).catch(() => void 0);
4862
+ diagnostics.networkStatus = status;
4863
+ diagnostics.swarms = serviceContext.networkManager.connectionLog?.swarms;
4829
4864
  }
4865
+ diagnostics.config = config.values;
4866
+ return diagnostics;
4830
4867
  };
4831
- _ts_decorate7([
4832
- logInfo
4833
- ], Lock.prototype, "lockKey", null);
4834
- var isLocked = (lockPath) => {
4835
- throw new Error("Not implemented");
4868
+ var getSpaceStats = async (space) => {
4869
+ const stats = {
4870
+ key: space.key,
4871
+ metrics: space.metrics,
4872
+ epochs: space.inner.spaceState.credentials.filter(credentialTypeFilter("dxos.halo.credentials.Epoch")).map((credential) => ({
4873
+ ...credential.subject.assertion,
4874
+ id: credential.id
4875
+ })),
4876
+ members: Array.from(space.inner.spaceState.members.values()).map((member) => ({
4877
+ identity: {
4878
+ identityKey: member.key,
4879
+ profile: {
4880
+ displayName: member.assertion.profile?.displayName
4881
+ }
4882
+ },
4883
+ presence: space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0 ? SpaceMember3.PresenceState.ONLINE : SpaceMember3.PresenceState.OFFLINE
4884
+ })),
4885
+ pipeline: {
4886
+ // TODO(burdon): Pick properties from credentials if needed.
4887
+ currentEpoch: space.automergeSpaceState.lastEpoch,
4888
+ appliedEpoch: space.automergeSpaceState.lastEpoch,
4889
+ controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),
4890
+ currentControlTimeframe: space.inner.controlPipeline.state.timeframe,
4891
+ targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,
4892
+ totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe
4893
+ }
4894
+ };
4895
+ if (stats.metrics) {
4896
+ const { open, ready } = stats.metrics;
4897
+ stats.metrics.startupTime = open && ready && ready.getTime() - open.getTime();
4898
+ }
4899
+ return stats;
4836
4900
  };
4837
4901
 
4838
- // packages/sdk/client-services/src/packlets/storage/storage.ts
4839
- import { DX_DATA } from "@dxos/client-protocol";
4840
- import { InvalidConfigError } from "@dxos/protocols";
4841
- import { Runtime } from "@dxos/protocols/proto/dxos/config";
4842
- import { createStorage, StorageType } from "@dxos/random-access-storage";
4843
- import { isNode as isNode2 } from "@dxos/util";
4844
- var StorageDriver = Runtime.Client.Storage.StorageDriver;
4845
- var createStorageObjects = (config) => {
4846
- const { persistent = false, keyStore, dataStore, dataRoot = isNode2() ? DX_DATA : "dxos/storage" } = config ?? {};
4847
- if (persistent && dataStore === StorageDriver.RAM) {
4848
- throw new InvalidConfigError("RAM storage cannot be used in persistent mode.");
4849
- }
4850
- if (!persistent && dataStore !== void 0 && dataStore !== StorageDriver.RAM) {
4851
- throw new InvalidConfigError("Cannot use a persistent storage in not persistent mode.");
4852
- }
4853
- if (persistent && keyStore === StorageDriver.RAM) {
4854
- throw new InvalidConfigError("RAM key storage cannot be used in persistent mode.");
4855
- }
4856
- if (!persistent && keyStore !== StorageDriver.RAM && keyStore !== void 0) {
4857
- throw new InvalidConfigError("Cannot use a persistent key storage in not persistent mode.");
4858
- }
4902
+ // packages/sdk/client-services/src/packlets/diagnostics/browser-diagnostics-broadcast.ts
4903
+ import { Trigger as Trigger6 } from "@dxos/async";
4904
+ import { log as log13 } from "@dxos/log";
4905
+ var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/diagnostics/browser-diagnostics-broadcast.ts";
4906
+ var CHANNEL_NAME = "dxos.diagnostics.broadcast";
4907
+ var MessageType;
4908
+ (function(MessageType2) {
4909
+ MessageType2["PROBE"] = "probe";
4910
+ MessageType2["PROBE_ACK"] = "probe-ack";
4911
+ MessageType2["REQUEST_DIAGNOSTICS"] = "request-diagnostics";
4912
+ MessageType2["RECEIVE_DIAGNOSTICS"] = "receive-diagnostics";
4913
+ })(MessageType || (MessageType = {}));
4914
+ var createCollectDiagnosticsBroadcastSender = () => {
4859
4915
  return {
4860
- storage: createStorage({
4861
- type: persistent ? toStorageType(dataStore) : StorageType.RAM,
4862
- root: `${dataRoot}/`
4863
- })
4916
+ broadcastDiagnosticsRequest: async () => {
4917
+ let expectedResponse = "probe-ack";
4918
+ let channel;
4919
+ try {
4920
+ const trigger = new Trigger6();
4921
+ channel = new BroadcastChannel(CHANNEL_NAME);
4922
+ channel.onmessage = (msg) => {
4923
+ if (expectedResponse === msg.data.type) {
4924
+ trigger.wake(msg.data);
4925
+ }
4926
+ };
4927
+ channel.postMessage({
4928
+ type: "probe"
4929
+ });
4930
+ await trigger.wait({
4931
+ timeout: 200
4932
+ });
4933
+ expectedResponse = "receive-diagnostics";
4934
+ trigger.reset();
4935
+ channel.postMessage({
4936
+ type: "request-diagnostics"
4937
+ });
4938
+ const diagnostics = await trigger.wait({
4939
+ timeout: 5e3
4940
+ });
4941
+ return diagnostics.payload;
4942
+ } catch (e) {
4943
+ const errorDescription = e instanceof Error ? e.message : JSON.stringify(e);
4944
+ return {
4945
+ expectedResponse,
4946
+ errorDescription
4947
+ };
4948
+ } finally {
4949
+ safeClose(channel);
4950
+ }
4951
+ }
4952
+ };
4953
+ };
4954
+ var createCollectDiagnosticsBroadcastHandler = (systemService) => {
4955
+ let channel;
4956
+ return {
4957
+ start: () => {
4958
+ channel = new BroadcastChannel(CHANNEL_NAME);
4959
+ channel.onmessage = async (message) => {
4960
+ try {
4961
+ if (message.data.type === "probe") {
4962
+ channel?.postMessage({
4963
+ type: "probe-ack"
4964
+ });
4965
+ } else if (message.data.type === "request-diagnostics") {
4966
+ const diagnostics = await systemService.getDiagnostics({});
4967
+ channel?.postMessage({
4968
+ type: "receive-diagnostics",
4969
+ payload: diagnostics
4970
+ });
4971
+ }
4972
+ } catch (error) {
4973
+ log13.catch(error, void 0, {
4974
+ F: __dxlog_file16,
4975
+ L: 77,
4976
+ S: void 0,
4977
+ C: (f, a) => f(...a)
4978
+ });
4979
+ }
4980
+ };
4981
+ },
4982
+ stop: () => {
4983
+ safeClose(channel);
4984
+ channel = void 0;
4985
+ }
4864
4986
  };
4865
4987
  };
4866
- var toStorageType = (type) => {
4867
- switch (type) {
4868
- case void 0:
4869
- return void 0;
4870
- case StorageDriver.RAM:
4871
- return StorageType.RAM;
4872
- case StorageDriver.CHROME:
4873
- return StorageType.CHROME;
4874
- case StorageDriver.FIREFOX:
4875
- return StorageType.FIREFOX;
4876
- case StorageDriver.IDB:
4877
- return StorageType.IDB;
4878
- case StorageDriver.NODE:
4879
- return StorageType.NODE;
4880
- case StorageDriver.WEBFS:
4881
- return StorageType.WEBFS;
4882
- default:
4883
- throw new Error(`Invalid storage type: ${StorageDriver[type]}`);
4988
+ var safeClose = (channel) => {
4989
+ try {
4990
+ channel?.close();
4991
+ } catch (e) {
4884
4992
  }
4885
4993
  };
4886
4994
 
4995
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics-collector.ts
4996
+ import { ConfigResource } from "@dxos/config";
4997
+ import { GetDiagnosticsRequest as GetDiagnosticsRequest2 } from "@dxos/protocols/proto/dxos/client/services";
4998
+ import { TRACE_PROCESSOR as TRACE_PROCESSOR3 } from "@dxos/tracing";
4999
+ import { jsonKeyReplacer as jsonKeyReplacer2, nonNullable } from "@dxos/util";
5000
+
4887
5001
  // packages/sdk/client-services/src/packlets/services/service-host.ts
4888
5002
  import { Event as Event9, synchronized as synchronized3 } from "@dxos/async";
4889
- import { Properties, clientServiceBundle, defaultKey } from "@dxos/client-protocol";
4890
- import { Context as Context11 } from "@dxos/context";
4891
- import { DataServiceImpl } from "@dxos/echo-pipeline";
4892
- import { getAutomergeObjectCore, getRawDoc } from "@dxos/echo-schema";
5003
+ import { clientServiceBundle, defaultKey, Properties } from "@dxos/client-protocol";
5004
+ import { Context as Context10 } from "@dxos/context";
5005
+ import { DataServiceImpl, encodeReference } from "@dxos/echo-pipeline";
5006
+ import { getTypeReference } from "@dxos/echo-schema";
4893
5007
  import { IndexServiceImpl } from "@dxos/indexing";
4894
5008
  import { invariant as invariant16 } from "@dxos/invariant";
4895
- import { PublicKey as PublicKey12 } from "@dxos/keys";
4896
- import { log as log15 } from "@dxos/log";
5009
+ import { PublicKey as PublicKey13 } from "@dxos/keys";
5010
+ import { log as log16 } from "@dxos/log";
4897
5011
  import { WebsocketSignalManager } from "@dxos/messaging";
4898
5012
  import { NetworkManager, createSimplePeerTransportFactory } from "@dxos/network-manager";
4899
5013
  import { trace as trace9 } from "@dxos/protocols";
4900
5014
  import { SystemStatus } from "@dxos/protocols/proto/dxos/client/services";
4901
5015
  import { TRACE_PROCESSOR as TRACE_PROCESSOR2, trace as Trace3 } from "@dxos/tracing";
4902
- import { assignDeep } from "@dxos/util";
5016
+ import { assignDeep as assignDeep2 } from "@dxos/util";
4903
5017
  import { WebsocketRpcClient } from "@dxos/websocket-rpc";
4904
5018
 
4905
5019
  // packages/sdk/client-services/src/packlets/devices/devices-service.ts
@@ -4984,11 +5098,135 @@ var DevicesServiceImpl = class {
4984
5098
  }
4985
5099
  };
4986
5100
 
5101
+ // packages/sdk/client-services/src/packlets/locks/browser.ts
5102
+ import { asyncTimeout as asyncTimeout2, Trigger as Trigger7 } from "@dxos/async";
5103
+ import { RESOURCE_LOCK_TIMEOUT } from "@dxos/client-protocol";
5104
+ import { log as log14, logInfo } from "@dxos/log";
5105
+ function _ts_decorate7(decorators, target, key, desc) {
5106
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5107
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
5108
+ r = Reflect.decorate(decorators, target, key, desc);
5109
+ else
5110
+ for (var i = decorators.length - 1; i >= 0; i--)
5111
+ if (d = decorators[i])
5112
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5113
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
5114
+ }
5115
+ var __dxlog_file18 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/locks/browser.ts";
5116
+ var Message;
5117
+ (function(Message2) {
5118
+ Message2["ACQUIRING"] = "acquiring";
5119
+ })(Message || (Message = {}));
5120
+ var Lock = class {
5121
+ constructor({ lockKey, onAcquire, onRelease }) {
5122
+ this._broadcastChannel = new BroadcastChannel("vault-resource-lock");
5123
+ this._releaseTrigger = new Trigger7();
5124
+ this._lockKey = lockKey;
5125
+ this._onAcquire = onAcquire;
5126
+ this._onRelease = onRelease;
5127
+ this._broadcastChannel.onmessage = this._onMessage.bind(this);
5128
+ }
5129
+ get lockKey() {
5130
+ return this._lockKey;
5131
+ }
5132
+ async acquire() {
5133
+ this._broadcastChannel.postMessage({
5134
+ message: "acquiring"
5135
+ });
5136
+ try {
5137
+ log14("aquiring lock...", void 0, {
5138
+ F: __dxlog_file18,
5139
+ L: 42,
5140
+ S: this,
5141
+ C: (f, a) => f(...a)
5142
+ });
5143
+ await asyncTimeout2(this._requestLock(), RESOURCE_LOCK_TIMEOUT);
5144
+ log14("acquired lock", void 0, {
5145
+ F: __dxlog_file18,
5146
+ L: 44,
5147
+ S: this,
5148
+ C: (f, a) => f(...a)
5149
+ });
5150
+ } catch {
5151
+ log14("stealing lock...", void 0, {
5152
+ F: __dxlog_file18,
5153
+ L: 46,
5154
+ S: this,
5155
+ C: (f, a) => f(...a)
5156
+ });
5157
+ await this._requestLock(true);
5158
+ log14("stolen lock", void 0, {
5159
+ F: __dxlog_file18,
5160
+ L: 48,
5161
+ S: this,
5162
+ C: (f, a) => f(...a)
5163
+ });
5164
+ }
5165
+ }
5166
+ async release() {
5167
+ this._releaseTrigger.wake();
5168
+ }
5169
+ _onMessage(event) {
5170
+ if (event.data.message === "acquiring") {
5171
+ this._releaseTrigger.wake();
5172
+ }
5173
+ }
5174
+ async _requestLock(steal = false) {
5175
+ log14("requesting lock...", {
5176
+ steal
5177
+ }, {
5178
+ F: __dxlog_file18,
5179
+ L: 63,
5180
+ S: this,
5181
+ C: (f, a) => f(...a)
5182
+ });
5183
+ const acquired = new Trigger7();
5184
+ void navigator.locks.request(this._lockKey, {
5185
+ steal
5186
+ }, async () => {
5187
+ await this._onAcquire?.();
5188
+ acquired.wake();
5189
+ this._releaseTrigger = new Trigger7();
5190
+ await this._releaseTrigger.wait();
5191
+ log14("releasing lock...", void 0, {
5192
+ F: __dxlog_file18,
5193
+ L: 72,
5194
+ S: this,
5195
+ C: (f, a) => f(...a)
5196
+ });
5197
+ await this._onRelease?.();
5198
+ log14("released lock", void 0, {
5199
+ F: __dxlog_file18,
5200
+ L: 74,
5201
+ S: this,
5202
+ C: (f, a) => f(...a)
5203
+ });
5204
+ }).catch(async () => {
5205
+ await this._onRelease?.();
5206
+ });
5207
+ await acquired.wait();
5208
+ log14("recieved lock", {
5209
+ steal
5210
+ }, {
5211
+ F: __dxlog_file18,
5212
+ L: 81,
5213
+ S: this,
5214
+ C: (f, a) => f(...a)
5215
+ });
5216
+ }
5217
+ };
5218
+ _ts_decorate7([
5219
+ logInfo
5220
+ ], Lock.prototype, "lockKey", null);
5221
+ var isLocked = (lockPath) => {
5222
+ throw new Error("Not implemented");
5223
+ };
5224
+
4987
5225
  // packages/sdk/client-services/src/packlets/logging/logging-service.ts
4988
5226
  import { Event as Event8 } from "@dxos/async";
4989
5227
  import { Stream as Stream12 } from "@dxos/codec-protobuf";
4990
5228
  import { PublicKey as PublicKey11 } from "@dxos/keys";
4991
- import { getContextFromEntry, log as log14 } from "@dxos/log";
5229
+ import { getContextFromEntry, log as log15 } from "@dxos/log";
4992
5230
  import { QueryLogsRequest } from "@dxos/protocols/proto/dxos/client/services";
4993
5231
  import { getDebugName, jsonify, numericalValues, tracer } from "@dxos/util";
4994
5232
  var LoggingServiceImpl = class {
@@ -5001,11 +5239,11 @@ var LoggingServiceImpl = class {
5001
5239
  };
5002
5240
  }
5003
5241
  async open() {
5004
- log14.runtimeConfig.processors.push(this._logProcessor);
5242
+ log15.runtimeConfig.processors.push(this._logProcessor);
5005
5243
  }
5006
5244
  async close() {
5007
- const index = log14.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
5008
- log14.runtimeConfig.processors.splice(index, 1);
5245
+ const index = log15.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);
5246
+ log15.runtimeConfig.processors.splice(index, 1);
5009
5247
  }
5010
5248
  async controlMetrics({ reset, record }) {
5011
5249
  if (reset) {
@@ -5090,12 +5328,12 @@ var LoggingServiceImpl = class {
5090
5328
  });
5091
5329
  }
5092
5330
  };
5093
- var matchFilter = (filter, level, path, options) => {
5331
+ var matchFilter = (filter, level, path2, options) => {
5094
5332
  switch (options) {
5095
5333
  case QueryLogsRequest.MatchingOptions.INCLUSIVE:
5096
- return level >= filter.level && (!filter.pattern || path.includes(filter.pattern));
5334
+ return level >= filter.level && (!filter.pattern || path2.includes(filter.pattern));
5097
5335
  case QueryLogsRequest.MatchingOptions.EXPLICIT:
5098
- return level === filter.level && (!filter.pattern || path.includes(filter.pattern));
5336
+ return level === filter.level && (!filter.pattern || path2.includes(filter.pattern));
5099
5337
  }
5100
5338
  };
5101
5339
  var shouldLog = (entry2, request) => {
@@ -5141,6 +5379,80 @@ var NetworkServiceImpl = class {
5141
5379
  }
5142
5380
  };
5143
5381
 
5382
+ // packages/sdk/client-services/src/packlets/storage/storage.ts
5383
+ import { InvalidConfigError } from "@dxos/protocols";
5384
+ import { Runtime as Runtime2 } from "@dxos/protocols/proto/dxos/config";
5385
+ import { createStorage, StorageType } from "@dxos/random-access-storage";
5386
+
5387
+ // packages/sdk/client-services/src/packlets/storage/util.ts
5388
+ import { DX_DATA } from "@dxos/client-protocol";
5389
+ import { Runtime } from "@dxos/protocols/proto/dxos/config";
5390
+ import { isNode as isNode2 } from "@dxos/util";
5391
+ var getRootPath = (config) => {
5392
+ const { dataRoot = isNode2() ? DX_DATA : "dxos/storage" } = config ?? {};
5393
+ return `${dataRoot}/`;
5394
+ };
5395
+ var isPersistent = (config) => {
5396
+ const { persistent = false } = config ?? {};
5397
+ return config.dataStore !== void 0 && config.dataStore !== Runtime.Client.Storage.StorageDriver.RAM || persistent;
5398
+ };
5399
+
5400
+ // packages/sdk/client-services/src/packlets/storage/storage.ts
5401
+ var StorageDriver = Runtime2.Client.Storage.StorageDriver;
5402
+ var createStorageObjects = (config) => {
5403
+ const { persistent = false, keyStore, dataStore } = config ?? {};
5404
+ if (persistent && dataStore === StorageDriver.RAM) {
5405
+ throw new InvalidConfigError("RAM storage cannot be used in persistent mode.");
5406
+ }
5407
+ if (!persistent && dataStore !== void 0 && dataStore !== StorageDriver.RAM) {
5408
+ throw new InvalidConfigError("Cannot use a persistent storage in not persistent mode.");
5409
+ }
5410
+ if (persistent && keyStore === StorageDriver.RAM) {
5411
+ throw new InvalidConfigError("RAM key storage cannot be used in persistent mode.");
5412
+ }
5413
+ if (!persistent && keyStore !== StorageDriver.RAM && keyStore !== void 0) {
5414
+ throw new InvalidConfigError("Cannot use a persistent key storage in not persistent mode.");
5415
+ }
5416
+ return {
5417
+ storage: createStorage({
5418
+ type: persistent ? toStorageType(dataStore) : StorageType.RAM,
5419
+ root: getRootPath(config)
5420
+ })
5421
+ };
5422
+ };
5423
+ var toStorageType = (type) => {
5424
+ switch (type) {
5425
+ case void 0:
5426
+ return void 0;
5427
+ case StorageDriver.RAM:
5428
+ return StorageType.RAM;
5429
+ case StorageDriver.CHROME:
5430
+ return StorageType.CHROME;
5431
+ case StorageDriver.FIREFOX:
5432
+ return StorageType.FIREFOX;
5433
+ case StorageDriver.IDB:
5434
+ return StorageType.IDB;
5435
+ case StorageDriver.NODE:
5436
+ return StorageType.NODE;
5437
+ case StorageDriver.WEBFS:
5438
+ return StorageType.WEBFS;
5439
+ default:
5440
+ throw new Error(`Invalid storage type: ${StorageDriver[type]}`);
5441
+ }
5442
+ };
5443
+
5444
+ // packages/sdk/client-services/src/packlets/storage/level.ts
5445
+ import { Level } from "level";
5446
+ import path from "@dxos/node-std/path";
5447
+ import { PublicKey as PublicKey12 } from "@dxos/keys";
5448
+ var createLevel = async (config) => {
5449
+ const persistent = isPersistent(config);
5450
+ const storagePath = persistent ? path.join(getRootPath(config), "level") : `/tmp/dxos-${PublicKey12.random().toHex()}`;
5451
+ const level = new Level(storagePath);
5452
+ await level.open();
5453
+ return level;
5454
+ };
5455
+
5144
5456
  // packages/sdk/client-services/src/packlets/system/system-service.ts
5145
5457
  import { Stream as Stream14 } from "@dxos/codec-protobuf";
5146
5458
  import { GetDiagnosticsRequest } from "@dxos/protocols/proto/dxos/client/services";
@@ -5209,13 +5521,14 @@ function _ts_decorate8(decorators, target, key, desc) {
5209
5521
  r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5210
5522
  return c > 3 && r && Object.defineProperty(target, key, r), r;
5211
5523
  }
5212
- var __dxlog_file18 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-host.ts";
5524
+ var __dxlog_file19 = "/home/runner/work/dxos/dxos/packages/sdk/client-services/src/packlets/services/service-host.ts";
5213
5525
  var ClientServicesHost = class {
5214
5526
  constructor({
5215
5527
  config,
5216
5528
  transportFactory,
5217
5529
  signalManager,
5218
5530
  storage,
5531
+ level,
5219
5532
  // TODO(wittjosiah): Turn this on by default.
5220
5533
  lockKey,
5221
5534
  callbacks,
@@ -5226,6 +5539,7 @@ var ClientServicesHost = class {
5226
5539
  this._opening = false;
5227
5540
  this._open = false;
5228
5541
  this._storage = storage;
5542
+ this._level = level;
5229
5543
  this._callbacks = callbacks;
5230
5544
  this._runtimeParams = runtimeParams;
5231
5545
  if (config) {
@@ -5240,7 +5554,7 @@ var ClientServicesHost = class {
5240
5554
  lockKey,
5241
5555
  onAcquire: () => {
5242
5556
  if (!this._opening) {
5243
- void this.open(new Context11());
5557
+ void this.open(new Context10());
5244
5558
  }
5245
5559
  },
5246
5560
  onRelease: () => this.close()
@@ -5264,6 +5578,7 @@ var ClientServicesHost = class {
5264
5578
  await this.reset();
5265
5579
  }
5266
5580
  });
5581
+ this.diagnosticsBroadcastHandler = createCollectDiagnosticsBroadcastHandler(this._systemService);
5267
5582
  this._loggingService = new LoggingServiceImpl();
5268
5583
  this._serviceRegistry = new ServiceRegistry(clientServiceBundle, {
5269
5584
  SystemService: this._systemService,
@@ -5295,24 +5610,24 @@ var ClientServicesHost = class {
5295
5610
  */
5296
5611
  initialize({ config, ...options }) {
5297
5612
  invariant16(!this._open, "service host is open", {
5298
- F: __dxlog_file18,
5299
- L: 179,
5613
+ F: __dxlog_file19,
5614
+ L: 197,
5300
5615
  S: this,
5301
5616
  A: [
5302
5617
  "!this._open",
5303
5618
  "'service host is open'"
5304
5619
  ]
5305
5620
  });
5306
- log15("initializing...", void 0, {
5307
- F: __dxlog_file18,
5308
- L: 180,
5621
+ log16("initializing...", void 0, {
5622
+ F: __dxlog_file19,
5623
+ L: 198,
5309
5624
  S: this,
5310
5625
  C: (f, a) => f(...a)
5311
5626
  });
5312
5627
  if (config) {
5313
5628
  invariant16(!this._config, "config already set", {
5314
- F: __dxlog_file18,
5315
- L: 183,
5629
+ F: __dxlog_file19,
5630
+ L: 201,
5316
5631
  S: this,
5317
5632
  A: [
5318
5633
  "!this._config",
@@ -5324,13 +5639,21 @@ var ClientServicesHost = class {
5324
5639
  this._storage = createStorageObjects(config.get("runtime.client.storage", {})).storage;
5325
5640
  }
5326
5641
  }
5642
+ if (!options.signalManager) {
5643
+ log16.warn("running signaling without telemetry metadata.", void 0, {
5644
+ F: __dxlog_file19,
5645
+ L: 209,
5646
+ S: this,
5647
+ C: (f, a) => f(...a)
5648
+ });
5649
+ }
5327
5650
  const { connectionLog = true, transportFactory = createSimplePeerTransportFactory({
5328
5651
  iceServers: this._config?.get("runtime.services.ice")
5329
5652
  }), signalManager = new WebsocketSignalManager(this._config?.get("runtime.services.signaling") ?? []) } = options;
5330
5653
  this._signalManager = signalManager;
5331
5654
  invariant16(!this._networkManager, "network manager already set", {
5332
- F: __dxlog_file18,
5333
- L: 199,
5655
+ F: __dxlog_file19,
5656
+ L: 220,
5334
5657
  S: this,
5335
5658
  A: [
5336
5659
  "!this._networkManager",
@@ -5342,9 +5665,9 @@ var ClientServicesHost = class {
5342
5665
  transportFactory,
5343
5666
  signalManager
5344
5667
  });
5345
- log15("initialized", void 0, {
5346
- F: __dxlog_file18,
5347
- L: 206,
5668
+ log16("initialized", void 0, {
5669
+ F: __dxlog_file19,
5670
+ L: 227,
5348
5671
  S: this,
5349
5672
  C: (f, a) => f(...a)
5350
5673
  });
@@ -5353,18 +5676,18 @@ var ClientServicesHost = class {
5353
5676
  if (this._open) {
5354
5677
  return;
5355
5678
  }
5356
- const traceId = PublicKey12.random().toHex();
5357
- log15.trace("dxos.client-services.host.open", trace9.begin({
5679
+ const traceId = PublicKey13.random().toHex();
5680
+ log16.trace("dxos.client-services.host.open", trace9.begin({
5358
5681
  id: traceId
5359
5682
  }), {
5360
- F: __dxlog_file18,
5361
- L: 217,
5683
+ F: __dxlog_file19,
5684
+ L: 238,
5362
5685
  S: this,
5363
5686
  C: (f, a) => f(...a)
5364
5687
  });
5365
5688
  invariant16(this._config, "config not set", {
5366
- F: __dxlog_file18,
5367
- L: 219,
5689
+ F: __dxlog_file19,
5690
+ L: 240,
5368
5691
  S: this,
5369
5692
  A: [
5370
5693
  "this._config",
@@ -5372,8 +5695,8 @@ var ClientServicesHost = class {
5372
5695
  ]
5373
5696
  });
5374
5697
  invariant16(this._storage, "storage not set", {
5375
- F: __dxlog_file18,
5376
- L: 220,
5698
+ F: __dxlog_file19,
5699
+ L: 241,
5377
5700
  S: this,
5378
5701
  A: [
5379
5702
  "this._storage",
@@ -5381,8 +5704,8 @@ var ClientServicesHost = class {
5381
5704
  ]
5382
5705
  });
5383
5706
  invariant16(this._signalManager, "signal manager not set", {
5384
- F: __dxlog_file18,
5385
- L: 221,
5707
+ F: __dxlog_file19,
5708
+ L: 242,
5386
5709
  S: this,
5387
5710
  A: [
5388
5711
  "this._signalManager",
@@ -5390,8 +5713,8 @@ var ClientServicesHost = class {
5390
5713
  ]
5391
5714
  });
5392
5715
  invariant16(this._networkManager, "network manager not set", {
5393
- F: __dxlog_file18,
5394
- L: 222,
5716
+ F: __dxlog_file19,
5717
+ L: 243,
5395
5718
  S: this,
5396
5719
  A: [
5397
5720
  "this._networkManager",
@@ -5399,21 +5722,25 @@ var ClientServicesHost = class {
5399
5722
  ]
5400
5723
  });
5401
5724
  this._opening = true;
5402
- log15("opening...", {
5725
+ log16("opening...", {
5403
5726
  lockKey: this._resourceLock?.lockKey
5404
5727
  }, {
5405
- F: __dxlog_file18,
5406
- L: 225,
5728
+ F: __dxlog_file19,
5729
+ L: 246,
5407
5730
  S: this,
5408
5731
  C: (f, a) => f(...a)
5409
5732
  });
5733
+ if (!this._level) {
5734
+ this._level = await createLevel(this._config.get("runtime.client.storage", {}));
5735
+ }
5736
+ await this._level.open();
5410
5737
  await this._resourceLock?.acquire();
5411
5738
  await this._loggingService.open();
5412
- this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._signalManager, this._runtimeParams);
5739
+ this._serviceContext = new ServiceContext(this._storage, this._level, this._networkManager, this._signalManager, this._runtimeParams);
5413
5740
  this._serviceRegistry.setServices({
5414
5741
  SystemService: this._systemService,
5415
5742
  IdentityService: new IdentityServiceImpl((params) => this._createIdentity(params), this._serviceContext.identityManager, this._serviceContext.keyring, (profile) => this._serviceContext.broadcastProfileUpdate(profile)),
5416
- InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitations, (invitation) => this._serviceContext.getInvitationHandler(invitation), this._serviceContext.metadataStore),
5743
+ InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitationsManager),
5417
5744
  DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),
5418
5745
  SpacesService: new SpacesServiceImpl(this._serviceContext.identityManager, this._serviceContext.spaceManager, async () => {
5419
5746
  await this._serviceContext.initialized.wait();
@@ -5435,24 +5762,6 @@ var ClientServicesHost = class {
5435
5762
  })
5436
5763
  });
5437
5764
  await this._serviceContext.open(ctx);
5438
- invariant16(this.serviceRegistry.services.InvitationsService, void 0, {
5439
- F: __dxlog_file18,
5440
- L: 286,
5441
- S: this,
5442
- A: [
5443
- "this.serviceRegistry.services.InvitationsService",
5444
- ""
5445
- ]
5446
- });
5447
- const loadedInvitations = await this.serviceRegistry.services.InvitationsService.loadPersistentInvitations();
5448
- log15("loaded persistent invitations", {
5449
- count: loadedInvitations.invitations?.length
5450
- }, {
5451
- F: __dxlog_file18,
5452
- L: 289,
5453
- S: this,
5454
- C: (f, a) => f(...a)
5455
- });
5456
5765
  const devtoolsProxy = this._config?.get("runtime.client.devtoolsProxy");
5457
5766
  if (devtoolsProxy) {
5458
5767
  this._devtoolsProxy = new WebsocketRpcClient({
@@ -5463,23 +5772,24 @@ var ClientServicesHost = class {
5463
5772
  });
5464
5773
  void this._devtoolsProxy.open();
5465
5774
  }
5775
+ this.diagnosticsBroadcastHandler.start();
5466
5776
  this._opening = false;
5467
5777
  this._open = true;
5468
5778
  this._statusUpdate.emit();
5469
5779
  const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;
5470
- log15("opened", {
5780
+ log16("opened", {
5471
5781
  deviceKey
5472
5782
  }, {
5473
- F: __dxlog_file18,
5474
- L: 306,
5783
+ F: __dxlog_file19,
5784
+ L: 326,
5475
5785
  S: this,
5476
5786
  C: (f, a) => f(...a)
5477
5787
  });
5478
- log15.trace("dxos.client-services.host.open", trace9.end({
5788
+ log16.trace("dxos.client-services.host.open", trace9.end({
5479
5789
  id: traceId
5480
5790
  }), {
5481
- F: __dxlog_file18,
5482
- L: 307,
5791
+ F: __dxlog_file19,
5792
+ L: 327,
5483
5793
  S: this,
5484
5794
  C: (f, a) => f(...a)
5485
5795
  });
@@ -5489,60 +5799,62 @@ var ClientServicesHost = class {
5489
5799
  return;
5490
5800
  }
5491
5801
  const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;
5492
- log15("closing...", {
5802
+ log16("closing...", {
5493
5803
  deviceKey
5494
5804
  }, {
5495
- F: __dxlog_file18,
5496
- L: 318,
5805
+ F: __dxlog_file19,
5806
+ L: 338,
5497
5807
  S: this,
5498
5808
  C: (f, a) => f(...a)
5499
5809
  });
5810
+ this.diagnosticsBroadcastHandler.stop();
5500
5811
  await this._devtoolsProxy?.close();
5501
5812
  this._serviceRegistry.setServices({
5502
5813
  SystemService: this._systemService
5503
5814
  });
5504
5815
  await this._loggingService.close();
5505
5816
  await this._serviceContext.close();
5817
+ await this._level?.close();
5506
5818
  this._open = false;
5507
5819
  this._statusUpdate.emit();
5508
- log15("closed", {
5820
+ log16("closed", {
5509
5821
  deviceKey
5510
5822
  }, {
5511
- F: __dxlog_file18,
5512
- L: 325,
5823
+ F: __dxlog_file19,
5824
+ L: 347,
5513
5825
  S: this,
5514
5826
  C: (f, a) => f(...a)
5515
5827
  });
5516
5828
  }
5517
5829
  async reset() {
5518
- const traceId = PublicKey12.random().toHex();
5519
- log15.trace("dxos.sdk.client-services-host.reset", trace9.begin({
5830
+ const traceId = PublicKey13.random().toHex();
5831
+ log16.trace("dxos.sdk.client-services-host.reset", trace9.begin({
5520
5832
  id: traceId
5521
5833
  }), {
5522
- F: __dxlog_file18,
5523
- L: 330,
5834
+ F: __dxlog_file19,
5835
+ L: 352,
5524
5836
  S: this,
5525
5837
  C: (f, a) => f(...a)
5526
5838
  });
5527
- log15("resetting...", void 0, {
5528
- F: __dxlog_file18,
5529
- L: 332,
5839
+ log16("resetting...", void 0, {
5840
+ F: __dxlog_file19,
5841
+ L: 354,
5530
5842
  S: this,
5531
5843
  C: (f, a) => f(...a)
5532
5844
  });
5533
5845
  await this._serviceContext?.close();
5534
5846
  await this._storage.reset();
5535
- log15("reset", void 0, {
5536
- F: __dxlog_file18,
5537
- L: 335,
5847
+ log16("reset", void 0, {
5848
+ F: __dxlog_file19,
5849
+ L: 357,
5538
5850
  S: this,
5539
5851
  C: (f, a) => f(...a)
5540
5852
  });
5541
- log15.trace("dxos.sdk.client-services-host.reset", trace9.end({
5853
+ log16.trace("dxos.sdk.client-services-host.reset", trace9.end({
5542
5854
  id: traceId
5543
5855
  }), {
5544
- F: __dxlog_file18,
5545
- L: 336,
5856
+ F: __dxlog_file19,
5857
+ L: 358,
5546
5858
  S: this,
5547
5859
  C: (f, a) => f(...a)
5548
5860
  });
@@ -5552,12 +5864,10 @@ var ClientServicesHost = class {
5552
5864
  const identity = await this._serviceContext.createIdentity(params);
5553
5865
  await this._serviceContext.initialized.wait();
5554
5866
  const space = await this._serviceContext.dataSpaceManager.createSpace();
5555
- const obj = new Properties(void 0);
5556
- obj[defaultKey] = identity.identityKey.toHex();
5557
5867
  const automergeIndex = space.automergeSpaceState.rootUrl;
5558
5868
  invariant16(automergeIndex, void 0, {
5559
- F: __dxlog_file18,
5560
- L: 351,
5869
+ F: __dxlog_file19,
5870
+ L: 370,
5561
5871
  S: this,
5562
5872
  A: [
5563
5873
  "automergeIndex",
@@ -5566,12 +5876,25 @@ var ClientServicesHost = class {
5566
5876
  });
5567
5877
  const document = await this._serviceContext.automergeHost.repo.find(automergeIndex);
5568
5878
  await document.whenReady();
5879
+ const properties = {
5880
+ system: {
5881
+ type: encodeReference(getTypeReference(Properties))
5882
+ },
5883
+ data: {
5884
+ [defaultKey]: identity.identityKey.toHex()
5885
+ },
5886
+ meta: {
5887
+ keys: []
5888
+ }
5889
+ };
5890
+ const propertiesId = PublicKey13.random().toHex();
5569
5891
  document.change((doc) => {
5570
- assignDeep(doc, [
5892
+ assignDeep2(doc, [
5571
5893
  "objects",
5572
- getAutomergeObjectCore(obj).id
5573
- ], getRawDoc(obj).handle.docSync());
5894
+ propertiesId
5895
+ ], properties);
5574
5896
  });
5897
+ await this._serviceContext.automergeHost.repo.flush();
5575
5898
  return identity;
5576
5899
  }
5577
5900
  };
@@ -5593,6 +5916,44 @@ ClientServicesHost = _ts_decorate8([
5593
5916
  Trace3.resource()
5594
5917
  ], ClientServicesHost);
5595
5918
 
5919
+ // packages/sdk/client-services/src/packlets/services/util.ts
5920
+ import { PublicKey as PublicKey14 } from "@dxos/keys";
5921
+ import { humanize } from "@dxos/util";
5922
+ var ClientServicesProviderResource = Symbol.for("dxos.resource.ClientServices");
5923
+
5924
+ // packages/sdk/client-services/src/packlets/diagnostics/diagnostics-collector.ts
5925
+ var DiagnosticsCollector = class {
5926
+ static {
5927
+ this.broadcastSender = createCollectDiagnosticsBroadcastSender();
5928
+ }
5929
+ static async collect(config = findConfigs(), services = findSystemServiceProvider(), options = {}) {
5930
+ const serviceDiagnostics = await services?.services?.SystemService?.getDiagnostics({
5931
+ keys: options.humanize ? GetDiagnosticsRequest2.KEY_OPTION.HUMANIZE : options.truncate ? GetDiagnosticsRequest2.KEY_OPTION.TRUNCATE : void 0
5932
+ });
5933
+ const clientDiagnostics = {
5934
+ config,
5935
+ trace: TRACE_PROCESSOR3.getDiagnostics()
5936
+ };
5937
+ const diagnostics = serviceDiagnostics != null ? {
5938
+ client: clientDiagnostics,
5939
+ services: serviceDiagnostics
5940
+ } : {
5941
+ client: clientDiagnostics,
5942
+ broadcast: await this.broadcastSender.broadcastDiagnosticsRequest()
5943
+ };
5944
+ return JSON.parse(JSON.stringify(diagnostics, jsonKeyReplacer2(options)));
5945
+ }
5946
+ };
5947
+ var findSystemServiceProvider = () => {
5948
+ const serviceProviders = TRACE_PROCESSOR3.findByAnnotation(ClientServicesProviderResource);
5949
+ const providerResource = serviceProviders.find((r) => r.instance.deref()?.services?.SystemService != null);
5950
+ return providerResource?.instance?.deref() ?? null;
5951
+ };
5952
+ var findConfigs = () => {
5953
+ const configs = TRACE_PROCESSOR3.findByAnnotation(ConfigResource);
5954
+ return configs.map((r) => r.instance.deref()).filter(nonNullable);
5955
+ };
5956
+
5596
5957
  export {
5597
5958
  Buffer,
5598
5959
  subscribeToFeeds,
@@ -5612,19 +5973,25 @@ export {
5612
5973
  IdentityServiceImpl,
5613
5974
  DeviceInvitationProtocol,
5614
5975
  InvitationsHandler,
5615
- invitationExpired,
5976
+ createAdmissionKeypair,
5616
5977
  InvitationsServiceImpl,
5617
5978
  SpaceInvitationProtocol,
5979
+ InvitationsManager,
5618
5980
  ClientRpcServer,
5619
- createDiagnostics,
5620
5981
  DataSpace,
5621
5982
  DataSpaceManager,
5622
5983
  SpacesServiceImpl,
5623
5984
  ServiceContext,
5624
5985
  ServiceRegistry,
5986
+ createDiagnostics,
5987
+ createCollectDiagnosticsBroadcastSender,
5988
+ createCollectDiagnosticsBroadcastHandler,
5989
+ DiagnosticsCollector,
5625
5990
  Lock,
5626
5991
  isLocked,
5627
5992
  createStorageObjects,
5628
- ClientServicesHost
5993
+ createLevel,
5994
+ ClientServicesHost,
5995
+ ClientServicesProviderResource
5629
5996
  };
5630
- //# sourceMappingURL=chunk-RQ33OGAG.mjs.map
5997
+ //# sourceMappingURL=chunk-U3AY6WTI.mjs.map