lody 0.115.0 → 0.116.0

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 (145) hide show
  1. package/dist/{access-Sut1_1-c.js → access-DIhEb_MP.js} +333 -314
  2. package/dist/{acp-interaction-owner-uSfNzpiU.js → acp-interaction-owner-8OMcZVET.js} +33 -33
  3. package/dist/{agent-execution-D1-dEIN6.js → agent-execution-ZTPT3A88.js} +13 -13
  4. package/dist/{analytics-events-BQIrmfJp.js → analytics-events-BNLOju7l.js} +2 -2
  5. package/dist/{app-J2sTmsZo.js → app-DzrwnZPK.js} +34 -34
  6. package/dist/{application-runtime-BPgp9fKR.js → application-runtime-4EGQJvLm.js} +2 -2
  7. package/dist/{auth-CTegS0TL.js → auth-CA7u_ijj.js} +8 -8
  8. package/dist/{automation-BL7x_nUm.js → automation-ClFKwWKg.js} +34 -34
  9. package/dist/baguette-worker.js +6 -6
  10. package/dist/chunks/{vendor-@agentclientprotocol-sdk-CpxTRW1f.js → vendor-@agentclientprotocol-sdk-54yhgJSn.js} +2 -2
  11. package/dist/chunks/{vendor-@anthropic-ai-claude-agent-sdk-B0HhZ112.js → vendor-@anthropic-ai-claude-agent-sdk-NAjHQcVv.js} +27 -3
  12. package/dist/chunks/{vendor-@better-auth-api-key-D0bKvhcn.js → vendor-@better-auth-api-key-Dy9PtbSj.js} +2 -2
  13. package/dist/chunks/{vendor-@better-auth-core-Dpzqxq_j.js → vendor-@better-auth-core-C7hql1k7.js} +8 -8
  14. package/dist/chunks/{vendor-@effect-platform-node-shared-DkrmBObz.js → vendor-@effect-platform-node-shared-DUSlMsdQ.js} +2 -2
  15. package/dist/chunks/{vendor-@loro-dev-streams-client-DPTfaXHE.js → vendor-@loro-dev-streams-client-DkeRiNAY.js} +1329 -88
  16. package/dist/chunks/{vendor-@loro-dev-streams-crdt-BOuVa3yO.js → vendor-@loro-dev-streams-crdt-CsXRvQxK.js} +861 -322
  17. package/dist/chunks/{vendor-@modelcontextprotocol-client-B_Q9G9Ku.js → vendor-@modelcontextprotocol-client-DuJtk4js.js} +3 -3
  18. package/dist/chunks/{vendor-@modelcontextprotocol-core-CW-vRGZP.js → vendor-@modelcontextprotocol-core-BkUcdvo6.js} +2 -2
  19. package/dist/chunks/{vendor-@modelcontextprotocol-node-CSCPUEbv.js → vendor-@modelcontextprotocol-node-D0s30TCx.js} +2 -2
  20. package/dist/chunks/{vendor-@modelcontextprotocol-server-BA5N3RYD.js → vendor-@modelcontextprotocol-server-C9c_OMTp.js} +3 -3
  21. package/dist/chunks/{vendor-@opencode-codemode-61MXX511.js → vendor-@opencode-codemode-DmkYINkB.js} +2 -2
  22. package/dist/chunks/{vendor-@sorbetai-artifacts-Dt9BTK8Q.js → vendor-@sorbetai-artifacts-Vz3r0uhj.js} +3 -3
  23. package/dist/chunks/{vendor-@sorbetai-context-COh8_Kmc.js → vendor-@sorbetai-context-BV7q3KwO.js} +2 -2
  24. package/dist/chunks/{vendor-@sorbetai-control-HcZa4Y-V.js → vendor-@sorbetai-control-C9pxQF9a.js} +137 -51
  25. package/dist/chunks/{vendor-@sorbetai-plugins-Bs93fyHc.js → vendor-@sorbetai-plugins-COkYjDxn.js} +3 -3
  26. package/dist/chunks/{vendor-@sorbetai-runtime-kicj4Xs_.js → vendor-@sorbetai-runtime-DKAfUiS0.js} +172 -60
  27. package/dist/chunks/{vendor-@sorbetai-schema-BYxzbt6U.js → vendor-@sorbetai-schema-D53JJ0HJ.js} +2 -2
  28. package/dist/chunks/{vendor-better-auth-PQ6PT4aF.js → vendor-better-auth-D1bP-dEy.js} +2 -2
  29. package/dist/chunks/{vendor-effect-CNM-5PoN.js → vendor-effect-BTVRmkqM.js} +418 -418
  30. package/dist/chunks/{vendor-es-toolkit-DnvFX_hl.js → vendor-es-toolkit-BDp9OdLC.js} +4 -4
  31. package/dist/chunks/{vendor-loro-repo-B1zdQ8Qd.js → vendor-loro-repo-DbOhEZ39.js} +2166 -93
  32. package/dist/chunks/{vendor-zod-DAcQjQuC.js → vendor-zod-nebGZ0VM.js} +6 -6
  33. package/dist/claude-acp.js +28 -7
  34. package/dist/{cli-platform-Cfc6A61f.js → cli-platform-qpp4fxi7.js} +6 -6
  35. package/dist/{cli-presence-application-D2Dn0fPM.js → cli-presence-application-Cw9rnD3u.js} +18 -18
  36. package/dist/{client-BsIzN-iC.js → client-09TiIsd2.js} +33 -33
  37. package/dist/{cloudflared-native-DmvSYnMb.js → cloudflared-native-Ber1sIlU.js} +4 -4
  38. package/dist/cloudflared-worker.js +7 -7
  39. package/dist/{code-collab-Cgso3Ix3.js → code-collab-DRoDl8u7.js} +3 -3
  40. package/dist/codex-acp.js +2 -1
  41. package/dist/{command-runtime-C7EPuHLe.js → command-runtime-CYs2KAyh.js} +774 -224
  42. package/dist/{const-LYLptZ7f.js → const-C9yql4zo.js} +2 -2
  43. package/dist/{control-CgRxpxvc.js → control-HMzEZJTm.js} +36 -36
  44. package/dist/{cross-workspace-D6-aE1-w.js → cross-workspace-CEB-pWmO.js} +3 -3
  45. package/dist/{daemon-runner-Bn8O9-a0.js → daemon-runner-BHgvKJ_l.js} +27 -27
  46. package/dist/{daemon-DWm2IzH9.js → daemon-s8LqFNYd.js} +30 -30
  47. package/dist/{daemon-session-tools-BSAgq4O1.js → daemon-session-tools-CrxHUVDk.js} +46 -46
  48. package/dist/{daemon-shared-NcwWGSEj.js → daemon-shared-BGfDcTED.js} +10 -10
  49. package/dist/{daemon-update-qOLnkZcv.js → daemon-update-BjGbzSFc.js} +2 -2
  50. package/dist/deepseek-acp.js +14 -2
  51. package/dist/{deepseek-harness-runtime-D6lV9pxi.js → deepseek-harness-runtime-CtfyKY7w.js} +8 -8
  52. package/dist/{deepseek-system-node-C2YpUQwp.js → deepseek-system-node-CBHH8N-Z.js} +4 -4
  53. package/dist/{device-preview-BjqAbZ9g.js → device-preview-WVdriBmC.js} +36 -11
  54. package/dist/devin-acp.js +2 -1
  55. package/dist/{diff-line-counts-ClicfZ_E.js → diff-line-counts-C7vhQioX.js} +2 -2
  56. package/dist/{diff-worker-task-BVD3EgeO.js → diff-worker-task-wwEm25bo.js} +2 -2
  57. package/dist/diff-worker.js +5 -5
  58. package/dist/{discovery-query-C_7lyBI8.js → discovery-query-6rvHO0Ax.js} +4 -4
  59. package/dist/{dsh-DVyIAYZ9.js → dsh-D8jYqbih.js} +9 -9
  60. package/dist/{dsh-plugins-Dfsqsiu7.js → dsh-plugins-BGuhIgPz.js} +15 -15
  61. package/dist/{e2ee-CslOKVIM.js → e2ee-BDxs5Gma.js} +3 -3
  62. package/dist/{e2ee-execution-intent-DYBEG410.js → e2ee-execution-intent-BTTWEaTs.js} +4 -4
  63. package/dist/{export-C-zeWP1i.js → export-BVe6KJcH.js} +40 -40
  64. package/dist/{feedback-Dde39k5W.js → feedback-8RRkLuXP.js} +34 -34
  65. package/dist/{feedback-jvl2Dz8w.js → feedback-Da3aBQ2E.js} +4 -4
  66. package/dist/{file-index-scan-core-Bta7tnbY.js → file-index-scan-core-QNHdA1nq.js} +5 -5
  67. package/dist/file-index-scan-worker.js +8 -8
  68. package/dist/{file-lock-By0YSSDw.js → file-lock-Oeerthnp.js} +9 -9
  69. package/dist/{github-BtMkInqL.js → github-B3lOSLjx.js} +33 -33
  70. package/dist/grok-acp.js +2 -1
  71. package/dist/{http-transport-C1f1XEnB.js → http-transport-3J_3rzKQ.js} +6 -6
  72. package/dist/{index-C41WZg1y.js → index-C5TYbo5p.js} +2 -2
  73. package/dist/{index-CitAbDql.js → index-CNsJ2gEh.js} +19 -6
  74. package/dist/{index-BUam8GIX.js → index-CbO2HBCx.js} +35 -35
  75. package/dist/{index-Ce9khNjj.js → index-CvTdgB45.js} +87 -75
  76. package/dist/{index-BsfKnSuo.js → index-CzJfh76P.js} +991 -964
  77. package/dist/index-DdJk9U2O.js +202 -0
  78. package/dist/{index-Dy-FYtdl.js → index-DtKSPvAx.js} +41 -41
  79. package/dist/{index-CZG5q6QS.js → index-PK9ed2VJ.js} +4 -4
  80. package/dist/{index-CwHleXV2.js → index-Z-EXLH2-.js} +2 -2
  81. package/dist/index.js +15 -15
  82. package/dist/{internal-BPOwohVc.js → internal-210PnQHj.js} +48 -48
  83. package/dist/{ios-simulator-BduF_qia.js → ios-simulator-B8Edygo_.js} +10 -10
  84. package/dist/{local-cli-host-lease-Chm4-jV0.js → local-cli-host-lease-BcOQ-7Gk.js} +3 -3
  85. package/dist/{local-ipc-B8vySppK.js → local-ipc-BNwkKO5i.js} +156 -103
  86. package/dist/{local-project-control-client-CIBpaXbo.js → local-project-control-client-BKaZlhrn.js} +5 -5
  87. package/dist/{lody-mcp-http-protocol-DBLKn7SZ.js → lody-mcp-http-protocol-C24PR-58.js} +46 -10
  88. package/dist/{lody-mcp-server-B4OeNPT4.js → lody-mcp-server-C_KUMdUq.js} +84 -39
  89. package/dist/{logger-C-G7jpWR.js → logger-zm-QQb1B.js} +2 -2
  90. package/dist/{login-Df1IkdeV.js → login-DoRU06W8.js} +18 -18
  91. package/dist/{login-shell-env-HKDW5zwx.js → login-shell-env-CFLesG20.js} +6 -6
  92. package/dist/{logout-gDuSiB0l.js → logout-4T76xG1C.js} +18 -18
  93. package/dist/{machine-bjdZ1hmy.js → machine-BFM6JQSw.js} +42 -42
  94. package/dist/{machine-identity-restore-BuoxXyiw.js → machine-identity-restore-CYjkTQcN.js} +3 -3
  95. package/dist/{machine-protocol-capabilities-DEhAj9SH.js → machine-protocol-capabilities-DcJpLvsC.js} +68 -47
  96. package/dist/{magpie-import-IrqfCF6i.js → magpie-import-CsiqaviF.js} +52 -50
  97. package/dist/{managed-daemon-forwarding-BpXhy_-O.js → managed-daemon-forwarding-D10w26x_.js} +9 -9
  98. package/dist/{managed-daemon-release-CwkvVtSj.js → managed-daemon-release-Bq0NQ5KB.js} +8 -8
  99. package/dist/{mcp-DTnh_PAT.js → mcp-CFSVE37k.js} +39 -39
  100. package/dist/{migrate-CUdZ3XBR.js → migrate-D0JGnFDi.js} +40 -38
  101. package/dist/{open-browser-3TOC7G1u.js → open-browser-CXJ_k8PZ.js} +3 -3
  102. package/dist/{operation-CzLcjV3W.js → operation-CjjYD8KR.js} +35 -35
  103. package/dist/{operation-store-rllAX2mr.js → operation-store-CjW-plfi.js} +6 -6
  104. package/dist/{presence-CZco7UQH.js → presence-DfPa6xSX.js} +95 -71
  105. package/dist/{presence-legacy-DIYBtj5j.js → presence-legacy-B7H0xyqf.js} +5 -5
  106. package/dist/{process-DrX1wZZk.js → process-BU5vWwzZ.js} +3 -3
  107. package/dist/{process-options-DNYWY_s6.js → process-options-CvxupoAj.js} +4 -4
  108. package/dist/{project-C_EZ2dLN.js → project-DbFdl-Tc.js} +41 -41
  109. package/dist/{project-path-CAQE9bes.js → project-path-BylnHhzQ.js} +11 -11
  110. package/dist/{realtime-journal-DyMe8jsR.js → realtime-journal-D5hdU6Fc.js} +2 -2
  111. package/dist/{register-VLBUVPh5.js → register-DzkfcD0R.js} +33 -33
  112. package/dist/{registry-generated-wkLapT7U.js → registry-generated-BtQFYqS0.js} +30 -30
  113. package/dist/{remote-pairing-D24xSpRh.js → remote-pairing-B-1pCVbn.js} +40 -40
  114. package/dist/{reset-identity-DVubJrt0.js → reset-identity-BKSdKzDv.js} +40 -40
  115. package/dist/{review-6aCgWEdv.js → review-DHDdCwwj.js} +9 -9
  116. package/dist/{review-viewer-CRYK94SE.js → review-viewer-DO7rhsH9.js} +3 -3
  117. package/dist/{rpc-secret-CPdan_XW.js → rpc-secret-Ds9rnsWf.js} +2 -2
  118. package/dist/{runtime-diagnostics-5l1pBD3m.js → runtime-diagnostics-BElvgU5u.js} +5 -5
  119. package/dist/{schedule-CGTbG70S.js → schedule-C-UJnfpM.js} +39 -39
  120. package/dist/{schedule-command-client-C6matZWn.js → schedule-command-client-B2k5ix1s.js} +38 -38
  121. package/dist/{schedule-command-service-2gToipBI.js → schedule-command-service-pFq9cQHf.js} +134 -58
  122. package/dist/{schedule-documents-DRc0byQm.js → schedule-documents-Di23etFx.js} +3 -3
  123. package/dist/{schedule-recurrence-BVxMRfp4.js → schedule-recurrence-D4r80Udd.js} +42 -14
  124. package/dist/{schedule-repository-dz9iwR0x.js → schedule-repository-BNUNXl15.js} +4 -4
  125. package/dist/{schedule-run-preparation-1oSQ5i-A.js → schedule-run-preparation-D2GjotJy.js} +5 -5
  126. package/dist/{schedule-types-BquxGfza.js → schedule-types-B9O0I1Ui.js} +472 -364
  127. package/dist/{service-D9xJKmI-.js → service-pb71b8fj.js} +5 -5
  128. package/dist/{session-npaRR-y3.js → session-C6dNbMjx.js} +21 -21
  129. package/dist/{session-file-blob-store-CBHDgf4e.js → session-file-blob-store-CdpmEU94.js} +4 -4
  130. package/dist/{session-image-download-DUwc2Fb4.js → session-image-download-DeZ6r1-w.js} +4 -4
  131. package/dist/{session-input-MeZheBJ0.js → session-input-Dz8R9xPL.js} +3 -3
  132. package/dist/{session-link-demCF_Y_.js → session-link-CABPzB2T.js} +51 -2
  133. package/dist/{session-link-export-BM1zZQRs.js → session-link-export-CabjkQNk.js} +3 -3
  134. package/dist/{session-operation-targets-lq3rsTnV.js → session-operation-targets-B-VimRwZ.js} +3 -3
  135. package/dist/{setting-Cq6nKJgF.js → setting-CKO-Tb-e.js} +116 -64
  136. package/dist/{start-BolVcMOA.js → start-B83c1-EW.js} +957 -297
  137. package/dist/streams-crdt-factory-CkuXGilB.js +17 -0
  138. package/dist/{subagent-emitter-DALyc5yu.js → subagent-emitter-D-zUFnS9.js} +2 -2
  139. package/dist/{subagent-events-CyFbbE20.js → subagent-events-D22OQNDm.js} +7 -2
  140. package/dist/{sync-BrDYKZ4H.js → sync-Cf_HanAI.js} +35 -35
  141. package/dist/{time-sync-D63wG9u-.js → time-sync-DjSg4eHx.js} +2 -2
  142. package/dist/{workspace-Bthb-nhu.js → workspace-BCjgp5pF.js} +36 -36
  143. package/dist/{workspace-legacy-jZ0D5Xl-.js → workspace-legacy-DJAko-Yj.js} +24 -24
  144. package/package.json +5 -5
  145. package/dist/index-BTgKuz44.js +0 -65
@@ -1,11 +1,11 @@
1
1
  import { F as Flock } from "./vendor-@loro-dev-flock-wasm-BH1ts_Xn.js";
2
- import { L as LoroDoc, V as VersionVector } from "./vendor-loro-crdt-2CFvB1HS.js";
2
+ import { L as LoroDoc, d as decodeImportBlobMeta, V as VersionVector } from "./vendor-loro-crdt-2CFvB1HS.js";
3
3
  import { randomUUID, createHash } from "node:crypto";
4
4
  import { readlinkSync, readFileSync } from "node:fs";
5
5
  import { execFile } from "node:child_process";
6
6
  import { promisify } from "node:util";
7
7
  import Database from "better-sqlite3";
8
- import { i as isValidRillId, I as InMemoryRemoteCursorStore, S as StreamsCrdt, c as createLoroDocAdapter, a as createFlockAdapter } from "./vendor-@loro-dev-streams-crdt-BOuVa3yO.js";
8
+ import { i as isValidRillId, I as InMemoryRemoteCursorStore, S as StreamsCrdt, c as createLoroDocAdapter, a as createFlockAdapter } from "./vendor-@loro-dev-streams-crdt-CsXRvQxK.js";
9
9
  function isObject(value) {
10
10
  return typeof value === "object" && value !== null && !Array.isArray(value);
11
11
  }
@@ -733,6 +733,1417 @@ function logAsyncError(context) {
733
733
  else console.error(`[loro-repo] ${context} failed with non-error reason:`, error);
734
734
  };
735
735
  }
736
+ const HOOKS_REGISTRY_SYMBOL = Symbol.for("@loro-dev/loro-repo/forwarding-hooks-registry");
737
+ function getHooksRegistry() {
738
+ const g = globalThis;
739
+ let registry = g[HOOKS_REGISTRY_SYMBOL];
740
+ if (!registry) {
741
+ registry = /* @__PURE__ */ new WeakMap();
742
+ g[HOOKS_REGISTRY_SYMBOL] = registry;
743
+ }
744
+ return registry;
745
+ }
746
+ function registerTransportForwardingHooks(adapter, hooks) {
747
+ getHooksRegistry().set(adapter, hooks);
748
+ }
749
+ function getTransportForwardingHooks(adapter) {
750
+ return getHooksRegistry().get(adapter);
751
+ }
752
+ function isHookedTransport(adapter) {
753
+ return getHooksRegistry().has(adapter);
754
+ }
755
+ function forwardingRoomKey(kind, id) {
756
+ return `${kind}\0${id}`;
757
+ }
758
+ function toLoroVersionRecord(version) {
759
+ if (!version || typeof version !== "object") return {};
760
+ if (version instanceof VersionVector) {
761
+ const out$1 = {};
762
+ for (const [peer, counter] of version.toJSON()) if (typeof counter === "number" && Number.isFinite(counter) && counter > 0) out$1[String(peer)] = counter;
763
+ return out$1;
764
+ }
765
+ if (version instanceof Map) {
766
+ const out$1 = {};
767
+ for (const [peer, counter] of version.entries()) if (typeof counter === "number" && Number.isFinite(counter) && counter > 0) out$1[String(peer)] = counter;
768
+ return out$1;
769
+ }
770
+ const out = {};
771
+ for (const [peer, counter] of Object.entries(version)) if (typeof counter === "number" && Number.isFinite(counter) && counter > 0) out[peer] = counter;
772
+ return out;
773
+ }
774
+ function mergeLoroVersionRecords(...versions) {
775
+ const merged = {};
776
+ for (const version of versions) {
777
+ if (!version) continue;
778
+ for (const [peer, counter] of Object.entries(version)) {
779
+ if (typeof counter !== "number" || !Number.isFinite(counter) || counter <= 0) continue;
780
+ merged[peer] = Math.max(merged[peer] ?? 0, counter);
781
+ }
782
+ }
783
+ return merged;
784
+ }
785
+ function toLoroVersionVector(version) {
786
+ const map = /* @__PURE__ */ new Map();
787
+ for (const [peer, counter] of Object.entries(version)) if (counter > 0) map.set(peer, counter);
788
+ return VersionVector.parseJSON(map);
789
+ }
790
+ const FAST_UPDATES_MAGIC_0 = 108;
791
+ const FAST_UPDATES_MAGIC_1 = 111;
792
+ const FAST_UPDATES_MAGIC_2 = 114;
793
+ const FAST_UPDATES_MAGIC_3 = 111;
794
+ const LORO_HEADER_LEN = 22;
795
+ const FAST_UPDATES_MODE_HI = 0;
796
+ const FAST_UPDATES_MODE_LO = 4;
797
+ function decodeExactLoroSpans(blob) {
798
+ if (blob.byteLength === 0) return [];
799
+ if (blob.byteLength >= LORO_HEADER_LEN && blob[0] === FAST_UPDATES_MAGIC_0 && blob[1] === FAST_UPDATES_MAGIC_1 && blob[2] === FAST_UPDATES_MAGIC_2 && blob[3] === FAST_UPDATES_MAGIC_3 && blob[20] === FAST_UPDATES_MODE_HI && blob[21] === FAST_UPDATES_MODE_LO) try {
800
+ const header = blob.subarray(0, LORO_HEADER_LEN);
801
+ const spans = [];
802
+ let offset = LORO_HEADER_LEN;
803
+ let valid = true;
804
+ while (offset < blob.byteLength) {
805
+ const lenStartOffset = offset;
806
+ let blockLen = 0;
807
+ let shift = 0;
808
+ let varintComplete = false;
809
+ while (offset < blob.byteLength) {
810
+ const b = blob[offset++];
811
+ if (shift >= 35) {
812
+ valid = false;
813
+ break;
814
+ }
815
+ blockLen += (b & 127) * 2 ** shift;
816
+ if ((b & 128) === 0) {
817
+ varintComplete = true;
818
+ break;
819
+ }
820
+ shift += 7;
821
+ }
822
+ if (!valid || !varintComplete || !Number.isSafeInteger(blockLen) || blockLen <= 0 || offset + blockLen > blob.byteLength) {
823
+ valid = false;
824
+ break;
825
+ }
826
+ const blockSlice = blob.subarray(lenStartOffset, offset + blockLen);
827
+ const chunk = new Uint8Array(LORO_HEADER_LEN + blockSlice.byteLength);
828
+ chunk.set(header, 0);
829
+ chunk.set(blockSlice, LORO_HEADER_LEN);
830
+ offset += blockLen;
831
+ const meta$1 = decodeImportBlobMeta(chunk, false);
832
+ const starts$1 = meta$1.partialStartVersionVector.toJSON();
833
+ for (const [peer, end] of meta$1.partialEndVersionVector.toJSON()) {
834
+ const start = starts$1.get(peer) ?? 0;
835
+ if (end > start) spans.push({
836
+ peer: String(peer),
837
+ start,
838
+ end
839
+ });
840
+ }
841
+ }
842
+ if (valid && offset === blob.byteLength) return spans;
843
+ } catch {
844
+ }
845
+ const meta = decodeImportBlobMeta(blob, false);
846
+ const starts = meta.partialStartVersionVector.toJSON();
847
+ const fallback = [];
848
+ for (const [peer, end] of meta.partialEndVersionVector.toJSON()) {
849
+ const start = starts.get(peer) ?? 0;
850
+ if (end > start) fallback.push({
851
+ peer: String(peer),
852
+ start,
853
+ end
854
+ });
855
+ }
856
+ return fallback;
857
+ }
858
+ function computeSafeContiguousLoroUpdateVersion(updates, baseVersion) {
859
+ const result = { ...baseVersion };
860
+ const byPeer = new LoroRangeSet();
861
+ for (const bytes of updates) {
862
+ if (bytes.byteLength === 0) continue;
863
+ try {
864
+ for (const span of decodeExactLoroSpans(bytes)) byPeer.add(span.peer, span.start, span.end);
865
+ } catch {
866
+ }
867
+ }
868
+ for (const peer of byPeer.peers()) {
869
+ let cursor = result[peer] ?? 0;
870
+ for (const span of byPeer.get(peer)) if (span.start <= cursor) cursor = Math.max(cursor, span.end);
871
+ else break;
872
+ if (cursor > 0) result[peer] = cursor;
873
+ }
874
+ return result;
875
+ }
876
+ function decodeLoroPendingSpans(doc) {
877
+ const set = new LoroRangeSet();
878
+ const pending2 = doc.exportPendingUpdates?.();
879
+ if (!pending2 || pending2.byteLength === 0) return set;
880
+ try {
881
+ for (const span of decodeExactLoroSpans(pending2)) set.add(span.peer, span.start, span.end);
882
+ } catch {
883
+ }
884
+ return set;
885
+ }
886
+ var LoroRangeSet = class LoroRangeSet2 {
887
+ peersMap = /* @__PURE__ */ new Map();
888
+ isEmpty() {
889
+ return this.peersMap.size === 0;
890
+ }
891
+ clear() {
892
+ this.peersMap.clear();
893
+ }
894
+ clone() {
895
+ const copy = new LoroRangeSet2();
896
+ for (const [peer, spans] of this.peersMap) copy.peersMap.set(peer, spans.map((span) => ({
897
+ start: span.start,
898
+ end: span.end
899
+ })));
900
+ return copy;
901
+ }
902
+ peers() {
903
+ return this.peersMap.keys();
904
+ }
905
+ get(peer) {
906
+ return this.peersMap.get(peer) ?? [];
907
+ }
908
+ add(peer, start, end) {
909
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return;
910
+ const list = this.peersMap.get(peer) ?? [];
911
+ list.push({
912
+ start,
913
+ end
914
+ });
915
+ list.sort((a, b) => a.start - b.start || a.end - b.end);
916
+ const merged = [];
917
+ for (const item of list) {
918
+ const last = merged[merged.length - 1];
919
+ if (!last || item.start > last.end) merged.push({
920
+ start: item.start,
921
+ end: item.end
922
+ });
923
+ else last.end = Math.max(last.end, item.end);
924
+ }
925
+ this.peersMap.set(peer, merged);
926
+ }
927
+ addSet(other) {
928
+ for (const peer of other.peers()) for (const span of other.get(peer)) this.add(peer, span.start, span.end);
929
+ }
930
+ subtract(peer, start, end) {
931
+ if (end <= start) return;
932
+ const existing = this.peersMap.get(peer);
933
+ if (!existing) return;
934
+ const next = [];
935
+ for (const span of existing) {
936
+ if (end <= span.start || start >= span.end) {
937
+ next.push(span);
938
+ continue;
939
+ }
940
+ if (span.start < start) next.push({
941
+ start: span.start,
942
+ end: start
943
+ });
944
+ if (end < span.end) next.push({
945
+ start: end,
946
+ end: span.end
947
+ });
948
+ }
949
+ if (next.length === 0) this.peersMap.delete(peer);
950
+ else this.peersMap.set(peer, next);
951
+ }
952
+ subtractUpTo(peer, end) {
953
+ if (end <= 0) return;
954
+ this.subtract(peer, 0, end);
955
+ }
956
+ subtractSet(other) {
957
+ for (const peer of other.peers()) for (const span of other.get(peer)) this.subtract(peer, span.start, span.end);
958
+ }
959
+ intersectRange(peer, start, end) {
960
+ if (end <= start) return [];
961
+ const existing = this.peersMap.get(peer);
962
+ if (!existing) return [];
963
+ const out = [];
964
+ for (const span of existing) {
965
+ const s = Math.max(start, span.start);
966
+ const e = Math.min(end, span.end);
967
+ if (e > s) out.push({
968
+ start: s,
969
+ end: e
970
+ });
971
+ }
972
+ return out;
973
+ }
974
+ foldAdjacentToZero(currentUpTo, peer) {
975
+ const existing = this.peersMap.get(peer);
976
+ if (!existing) return currentUpTo;
977
+ let nextUpTo = currentUpTo;
978
+ const remaining = [];
979
+ for (const span of existing) if (span.start <= nextUpTo) nextUpTo = Math.max(nextUpTo, span.end);
980
+ else remaining.push(span);
981
+ if (remaining.length === 0) this.peersMap.delete(peer);
982
+ else this.peersMap.set(peer, remaining);
983
+ return nextUpTo;
984
+ }
985
+ };
986
+ function resolveCausalClosure(doc, seed, confirmedContiguous, confirmedSparse) {
987
+ try {
988
+ const closure = new LoroRangeSet();
989
+ const queue = [];
990
+ for (const peer of seed.peers()) for (const span of seed.get(peer)) queue.push({
991
+ peer,
992
+ start: span.start,
993
+ end: span.end
994
+ });
995
+ const visitedChangeMaxEnd = /* @__PURE__ */ new Map();
996
+ while (queue.length > 0) {
997
+ const item = queue.pop();
998
+ const minPeer = confirmedContiguous[item.peer] ?? 0;
999
+ let pos = item.end - 1;
1000
+ while (pos >= Math.max(item.start, minPeer)) {
1001
+ const change = doc.getChangeAt({
1002
+ peer: item.peer,
1003
+ counter: pos
1004
+ });
1005
+ const chStart = change.counter;
1006
+ const needStart = Math.max(minPeer, chStart);
1007
+ const needEnd = pos + 1;
1008
+ if (needEnd > needStart) closure.add(item.peer, needStart, needEnd);
1009
+ const chKey = `${item.peer}\0${chStart}`;
1010
+ const prevMaxEnd = visitedChangeMaxEnd.get(chKey);
1011
+ if (prevMaxEnd === void 0) {
1012
+ visitedChangeMaxEnd.set(chKey, needEnd);
1013
+ for (const dep of change.deps) {
1014
+ const depPeer = String(dep.peer);
1015
+ const depConfirmed = confirmedContiguous[depPeer] ?? 0;
1016
+ if (dep.counter >= depConfirmed) queue.push({
1017
+ peer: depPeer,
1018
+ start: dep.counter,
1019
+ end: dep.counter + 1
1020
+ });
1021
+ }
1022
+ } else if (prevMaxEnd < needEnd) visitedChangeMaxEnd.set(chKey, needEnd);
1023
+ else break;
1024
+ pos = chStart - 1;
1025
+ }
1026
+ }
1027
+ closure.subtractSet(confirmedSparse);
1028
+ return closure;
1029
+ } catch {
1030
+ return;
1031
+ }
1032
+ }
1033
+ function computeContiguousExportVersion(finalRanges, lowerMap, confirmedSparse) {
1034
+ const out = {};
1035
+ for (const peer of finalRanges.peers()) {
1036
+ let cursor = lowerMap[peer] ?? 0;
1037
+ const combined = new LoroRangeSet();
1038
+ for (const span of confirmedSparse.get(peer)) combined.add(peer, span.start, span.end);
1039
+ for (const span of finalRanges.get(peer)) combined.add(peer, span.start, span.end);
1040
+ for (const span of combined.get(peer)) if (span.start <= cursor) cursor = Math.max(cursor, span.end);
1041
+ else break;
1042
+ if (cursor > 0) out[peer] = cursor;
1043
+ }
1044
+ return out;
1045
+ }
1046
+ function exportLoroRangesHoleFree(doc, finalRanges, contiguousFrom) {
1047
+ if (contiguousFrom) {
1048
+ const bytes = doc.export({
1049
+ mode: "update",
1050
+ from: toLoroVersionVector(contiguousFrom)
1051
+ });
1052
+ return bytes.byteLength > 0 ? [bytes] : [];
1053
+ }
1054
+ let maxSpansPerPeer = 0;
1055
+ for (const peer of finalRanges.peers()) maxSpansPerPeer = Math.max(maxSpansPerPeer, finalRanges.get(peer).length);
1056
+ const updates = [];
1057
+ for (let round = 0; round < maxSpansPerPeer; round += 1) {
1058
+ const spans = [];
1059
+ for (const peer of finalRanges.peers()) {
1060
+ const span = finalRanges.get(peer)[round];
1061
+ if (!span || span.end <= span.start) continue;
1062
+ spans.push({
1063
+ id: {
1064
+ peer,
1065
+ counter: span.start
1066
+ },
1067
+ len: span.end - span.start
1068
+ });
1069
+ }
1070
+ if (spans.length === 0) continue;
1071
+ const bytes = doc.export({
1072
+ mode: "updates-in-range",
1073
+ spans
1074
+ });
1075
+ if (bytes.byteLength > 0) updates.push(bytes);
1076
+ }
1077
+ return updates;
1078
+ }
1079
+ var LoroTargetForwardState = class {
1080
+ confirmedUpTo = {};
1081
+ confirmedSparse = new LoroRangeSet();
1082
+ withheld = new LoroRangeSet();
1083
+ timer;
1084
+ clearTimer() {
1085
+ if (this.timer !== void 0) {
1086
+ clearTimeout(this.timer);
1087
+ this.timer = void 0;
1088
+ }
1089
+ }
1090
+ hasPendingDelay() {
1091
+ return !this.withheld.isEmpty() || this.timer !== void 0;
1092
+ }
1093
+ reportConfirmedContiguous(version) {
1094
+ for (const [peer, end] of Object.entries(version)) {
1095
+ if (end <= 0) continue;
1096
+ let next = Math.max(this.confirmedUpTo[peer] ?? 0, end);
1097
+ next = this.confirmedSparse.foldAdjacentToZero(next, peer);
1098
+ this.confirmedUpTo[peer] = next;
1099
+ this.withheld.subtractUpTo(peer, next);
1100
+ }
1101
+ if (this.withheld.isEmpty() && this.timer !== void 0) {
1102
+ this.clearTimer();
1103
+ return true;
1104
+ }
1105
+ return false;
1106
+ }
1107
+ reportConfirmedSpan(peer, start, end) {
1108
+ if (end <= start) return false;
1109
+ const current = this.confirmedUpTo[peer] ?? 0;
1110
+ if (start <= current) {
1111
+ let next = Math.max(current, end);
1112
+ next = this.confirmedSparse.foldAdjacentToZero(next, peer);
1113
+ this.confirmedUpTo[peer] = next;
1114
+ this.withheld.subtractUpTo(peer, next);
1115
+ } else {
1116
+ this.confirmedSparse.add(peer, start, end);
1117
+ this.withheld.subtract(peer, start, end);
1118
+ }
1119
+ if (this.withheld.isEmpty() && this.timer !== void 0) {
1120
+ this.clearTimer();
1121
+ return true;
1122
+ }
1123
+ return false;
1124
+ }
1125
+ computeUncovered(ranges) {
1126
+ const temp = new LoroRangeSet();
1127
+ for (const r of ranges) {
1128
+ const base = this.confirmedUpTo[r.peer] ?? 0;
1129
+ const start = Math.max(r.start, base);
1130
+ if (r.end > start) temp.add(r.peer, start, r.end);
1131
+ }
1132
+ temp.subtractSet(this.confirmedSparse);
1133
+ const out = [];
1134
+ for (const peer of temp.peers()) for (const span of temp.get(peer)) out.push({
1135
+ peer,
1136
+ start: span.start,
1137
+ end: span.end
1138
+ });
1139
+ return out;
1140
+ }
1141
+ exportDelta(doc, extraFromVersion, excludeWithheld) {
1142
+ const docVersion = toLoroVersionRecord(doc.version());
1143
+ const lowerMap = mergeLoroVersionRecords(this.confirmedUpTo, extraFromVersion);
1144
+ const seed = new LoroRangeSet();
1145
+ for (const [peer, docEnd] of Object.entries(docVersion)) {
1146
+ const lower = lowerMap[peer] ?? 0;
1147
+ if (lower >= docEnd) continue;
1148
+ const peerSet = new LoroRangeSet();
1149
+ peerSet.add(peer, lower, docEnd);
1150
+ for (const span of this.confirmedSparse.get(peer)) peerSet.subtract(peer, span.start, span.end);
1151
+ if (excludeWithheld) for (const span of this.withheld.get(peer)) peerSet.subtract(peer, span.start, span.end);
1152
+ for (const span of peerSet.get(peer)) seed.add(peer, span.start, span.end);
1153
+ }
1154
+ if (seed.isEmpty()) return void 0;
1155
+ let finalRanges = seed;
1156
+ if (excludeWithheld && !this.withheld.isEmpty()) {
1157
+ const closure = resolveCausalClosure(doc, seed, lowerMap, this.confirmedSparse);
1158
+ if (closure) {
1159
+ finalRanges = seed.clone();
1160
+ finalRanges.addSet(closure);
1161
+ finalRanges.subtractSet(this.confirmedSparse);
1162
+ this.withheld.subtractSet(finalRanges);
1163
+ if (this.withheld.isEmpty()) this.clearTimer();
1164
+ } else {
1165
+ finalRanges = seed.clone();
1166
+ for (const peer of this.withheld.peers()) {
1167
+ const lower = lowerMap[peer] ?? 0;
1168
+ for (const span of this.withheld.get(peer)) {
1169
+ const start = Math.max(span.start, lower);
1170
+ if (span.end > start) finalRanges.add(peer, start, span.end);
1171
+ }
1172
+ }
1173
+ finalRanges.subtractSet(this.confirmedSparse);
1174
+ this.withheld.clear();
1175
+ this.clearTimer();
1176
+ }
1177
+ }
1178
+ if (finalRanges.isEmpty()) return void 0;
1179
+ let canUseContiguousUpdate = true;
1180
+ const contiguousFrom = {};
1181
+ for (const peer of finalRanges.peers()) if (docVersion[peer] === void 0) {
1182
+ canUseContiguousUpdate = false;
1183
+ break;
1184
+ }
1185
+ if (canUseContiguousUpdate) for (const [peer, docEnd] of Object.entries(docVersion)) {
1186
+ const lower = lowerMap[peer] ?? 0;
1187
+ const spans = finalRanges.get(peer);
1188
+ if (lower >= docEnd) if (spans.length === 0) contiguousFrom[peer] = docEnd;
1189
+ else {
1190
+ canUseContiguousUpdate = false;
1191
+ break;
1192
+ }
1193
+ else if (spans.length === 1 && spans[0].start === lower && spans[0].end === docEnd) contiguousFrom[peer] = lower;
1194
+ else {
1195
+ canUseContiguousUpdate = false;
1196
+ break;
1197
+ }
1198
+ }
1199
+ const updates = exportLoroRangesHoleFree(doc, finalRanges, canUseContiguousUpdate ? contiguousFrom : void 0);
1200
+ if (updates.length === 0) return void 0;
1201
+ return {
1202
+ updates,
1203
+ version: computeContiguousExportVersion(finalRanges, lowerMap, this.confirmedSparse)
1204
+ };
1205
+ }
1206
+ };
1207
+ function compareFlockClock(a, b) {
1208
+ if (a.physicalTime !== b.physicalTime) return a.physicalTime - b.physicalTime;
1209
+ return a.logicalCounter - b.logicalCounter;
1210
+ }
1211
+ function isFlockRecordAtLeast(candidate, target) {
1212
+ const cmp = compareFlockClock(candidate.entry, target.entry);
1213
+ if (cmp > 0) return true;
1214
+ if (cmp < 0) return false;
1215
+ return candidate.peerId >= target.peerId;
1216
+ }
1217
+ function isFlockRecordNewerOrSamePeer(confirmed, target) {
1218
+ const cmp = compareFlockClock(confirmed.entry, target.entry);
1219
+ if (cmp > 0) return true;
1220
+ if (cmp < 0) return false;
1221
+ return confirmed.peerId === target.peerId || confirmed.peerId > target.peerId;
1222
+ }
1223
+ function isFlockClockAfter(a, b) {
1224
+ return compareFlockClock(a, b) > 0;
1225
+ }
1226
+ function normalizeFlockVersion(version) {
1227
+ if (!version || typeof version !== "object") return {};
1228
+ const out = {};
1229
+ for (const [peer, entry] of Object.entries(version)) if (entry && typeof entry === "object" && typeof entry.physicalTime === "number" && typeof entry.logicalCounter === "number") out[peer] = {
1230
+ physicalTime: entry.physicalTime,
1231
+ logicalCounter: entry.logicalCounter
1232
+ };
1233
+ return out;
1234
+ }
1235
+ function mergeFlockVersions(...versions) {
1236
+ const merged = {};
1237
+ for (const version of versions) {
1238
+ if (!version) continue;
1239
+ for (const [peer, entry] of Object.entries(version)) {
1240
+ if (!entry) continue;
1241
+ const current = merged[peer];
1242
+ if (!current || isFlockClockAfter(entry, current)) merged[peer] = {
1243
+ physicalTime: entry.physicalTime,
1244
+ logicalCounter: entry.logicalCounter
1245
+ };
1246
+ }
1247
+ }
1248
+ return merged;
1249
+ }
1250
+ function parseFlockClockRecord(record) {
1251
+ if (typeof record?.c !== "string") return void 0;
1252
+ const firstComma = record.c.indexOf(",");
1253
+ const secondComma = record.c.indexOf(",", firstComma + 1);
1254
+ if (firstComma < 0 || secondComma < 0) return void 0;
1255
+ const physicalTime = Number(record.c.slice(0, firstComma));
1256
+ const logicalCounter = Number(record.c.slice(firstComma + 1, secondComma));
1257
+ if (!Number.isFinite(physicalTime) || !Number.isFinite(logicalCounter)) return;
1258
+ return {
1259
+ peerId: record.c.slice(secondComma + 1),
1260
+ entry: {
1261
+ physicalTime,
1262
+ logicalCounter
1263
+ }
1264
+ };
1265
+ }
1266
+ function extractFlockVersionFromBundle(bundle) {
1267
+ const out = {};
1268
+ for (const record of Object.values(bundle.entries)) {
1269
+ const parsed = parseFlockClockRecord(record);
1270
+ if (!parsed) continue;
1271
+ const current = out[parsed.peerId];
1272
+ if (!current || isFlockClockAfter(parsed.entry, current)) out[parsed.peerId] = parsed.entry;
1273
+ }
1274
+ return out;
1275
+ }
1276
+ var FlockTargetForwardState = class {
1277
+ confirmed = {};
1278
+ confirmedRecords = /* @__PURE__ */ new Map();
1279
+ withheldRecords = /* @__PURE__ */ new Map();
1280
+ unconfirmedRecords = /* @__PURE__ */ new Map();
1281
+ timer;
1282
+ clearTimer() {
1283
+ if (this.timer !== void 0) {
1284
+ clearTimeout(this.timer);
1285
+ this.timer = void 0;
1286
+ }
1287
+ }
1288
+ clearAll() {
1289
+ this.clearTimer();
1290
+ this.withheldRecords.clear();
1291
+ this.unconfirmedRecords.clear();
1292
+ this.confirmedRecords.clear();
1293
+ this.confirmed = {};
1294
+ }
1295
+ clearWithheld() {
1296
+ this.withheldRecords.clear();
1297
+ }
1298
+ hasPendingDelay() {
1299
+ return this.withheldRecords.size > 0 || this.timer !== void 0;
1300
+ }
1301
+ reportConfirmed(version) {
1302
+ this.confirmed = mergeFlockVersions(this.confirmed, version);
1303
+ for (const [key, rec] of this.withheldRecords) {
1304
+ const bound = this.confirmed[rec.peerId];
1305
+ if (bound && compareFlockClock(rec.entry, bound) <= 0) this.withheldRecords.delete(key);
1306
+ }
1307
+ for (const [key, rec] of this.unconfirmedRecords) {
1308
+ const bound = this.confirmed[rec.peerId];
1309
+ if (bound && compareFlockClock(rec.entry, bound) <= 0) this.unconfirmedRecords.delete(key);
1310
+ }
1311
+ if (this.withheldRecords.size === 0 && this.timer !== void 0) {
1312
+ this.clearTimer();
1313
+ return true;
1314
+ }
1315
+ return false;
1316
+ }
1317
+ reportConfirmedRecord(key, peerId, entry) {
1318
+ const next = {
1319
+ peerId,
1320
+ entry: {
1321
+ physicalTime: entry.physicalTime,
1322
+ logicalCounter: entry.logicalCounter
1323
+ }
1324
+ };
1325
+ const existingConf = this.confirmedRecords.get(key);
1326
+ if (!existingConf || isFlockRecordAtLeast(next, existingConf)) this.confirmedRecords.set(key, next);
1327
+ const effectiveConf = this.confirmedRecords.get(key);
1328
+ const withheld = this.withheldRecords.get(key);
1329
+ if (withheld && isFlockRecordNewerOrSamePeer(effectiveConf, withheld)) this.withheldRecords.delete(key);
1330
+ const unconfirmed = this.unconfirmedRecords.get(key);
1331
+ if (unconfirmed && isFlockRecordNewerOrSamePeer(effectiveConf, unconfirmed)) this.unconfirmedRecords.delete(key);
1332
+ if (this.withheldRecords.size === 0 && this.timer !== void 0) {
1333
+ this.clearTimer();
1334
+ return true;
1335
+ }
1336
+ return false;
1337
+ }
1338
+ isRecordCovered(key, rec) {
1339
+ const confRecord = this.confirmedRecords.get(key);
1340
+ if (confRecord && isFlockRecordNewerOrSamePeer(confRecord, rec)) return true;
1341
+ const confBound = this.confirmed[rec.peerId];
1342
+ if (confBound && compareFlockClock(rec.entry, confBound) <= 0) return true;
1343
+ return false;
1344
+ }
1345
+ trackUnconfirmedRecords(records) {
1346
+ for (const [key, rec] of records) {
1347
+ if (this.isRecordCovered(key, rec)) continue;
1348
+ this.unconfirmedRecords.set(key, rec);
1349
+ }
1350
+ }
1351
+ addUncoveredWithheld(records) {
1352
+ let added = 0;
1353
+ for (const [key, rec] of records) {
1354
+ if (this.isRecordCovered(key, rec)) continue;
1355
+ this.unconfirmedRecords.set(key, rec);
1356
+ this.withheldRecords.set(key, rec);
1357
+ added += 1;
1358
+ }
1359
+ return added;
1360
+ }
1361
+ exportBundle(flock, fromVersion, extraConfirmed, excludeWithheld) {
1362
+ const effectiveFrom = mergeFlockVersions(fromVersion, this.confirmed, extraConfirmed);
1363
+ const safeFrom = { ...effectiveFrom };
1364
+ for (const rec of this.unconfirmedRecords.values()) {
1365
+ const bound = safeFrom[rec.peerId];
1366
+ if (bound && compareFlockClock(rec.entry, bound) <= 0) delete safeFrom[rec.peerId];
1367
+ }
1368
+ if (!excludeWithheld) for (const rec of this.withheldRecords.values()) {
1369
+ const bound = safeFrom[rec.peerId];
1370
+ if (bound && compareFlockClock(rec.entry, bound) <= 0) delete safeFrom[rec.peerId];
1371
+ }
1372
+ const rawBundle = Object.keys(safeFrom).length === 0 ? flock.exportJson() : flock.exportJson(safeFrom);
1373
+ const earliestWithheldByPeer = /* @__PURE__ */ new Map();
1374
+ if (excludeWithheld) for (const rec of this.withheldRecords.values()) {
1375
+ const current = earliestWithheldByPeer.get(rec.peerId);
1376
+ if (!current || compareFlockClock(rec.entry, current) < 0) earliestWithheldByPeer.set(rec.peerId, rec.entry);
1377
+ }
1378
+ const filteredEntries = {};
1379
+ let entryCount = 0;
1380
+ for (const [key, record] of Object.entries(rawBundle.entries)) {
1381
+ const parsed = parseFlockClockRecord(record);
1382
+ if (parsed) {
1383
+ const confRecord = this.confirmedRecords.get(key);
1384
+ if (confRecord && isFlockRecordNewerOrSamePeer(confRecord, parsed)) continue;
1385
+ if (excludeWithheld) {
1386
+ const withheldRec = this.withheldRecords.get(key);
1387
+ if (withheldRec && isFlockRecordNewerOrSamePeer(withheldRec, parsed)) continue;
1388
+ const earliest = earliestWithheldByPeer.get(parsed.peerId);
1389
+ if (earliest && compareFlockClock(parsed.entry, earliest) >= 0) continue;
1390
+ }
1391
+ const unconfRec = this.unconfirmedRecords.get(key);
1392
+ const isKnownUnconfirmed = unconfRec !== void 0 && unconfRec.peerId === parsed.peerId && compareFlockClock(unconfRec.entry, parsed.entry) === 0 || !excludeWithheld && this.withheldRecords.get(key) !== void 0 && this.withheldRecords.get(key).peerId === parsed.peerId && compareFlockClock(this.withheldRecords.get(key).entry, parsed.entry) === 0;
1393
+ const lower = effectiveFrom[parsed.peerId];
1394
+ if (!isKnownUnconfirmed && lower && compareFlockClock(parsed.entry, lower) <= 0) continue;
1395
+ }
1396
+ filteredEntries[key] = record;
1397
+ entryCount += 1;
1398
+ }
1399
+ if (entryCount === 0) return void 0;
1400
+ const bundle = {
1401
+ version: rawBundle.version,
1402
+ entries: filteredEntries
1403
+ };
1404
+ return {
1405
+ bundle,
1406
+ version: extractFlockVersionFromBundle(bundle)
1407
+ };
1408
+ }
1409
+ };
1410
+ var ForwardingCoordinator = class {
1411
+ transportPolicies = /* @__PURE__ */ new Map();
1412
+ rooms = /* @__PURE__ */ new Map();
1413
+ hosts = /* @__PURE__ */ new Map();
1414
+ sourceLookup;
1415
+ destroyed = false;
1416
+ constructor(sourceLookup) {
1417
+ this.sourceLookup = sourceLookup;
1418
+ }
1419
+ getAdapterHost(transportId) {
1420
+ let host = this.hosts.get(transportId);
1421
+ if (!host) {
1422
+ host = {
1423
+ runWithRemoteImport: (room, fn) => this.runWithRemoteImport(transportId, room, fn),
1424
+ reportServerVersion: (room, version, options) => this.reportServerVersion(transportId, room, version, options),
1425
+ reportServerUpdateBytes: (room, bytes) => this.reportServerUpdateBytes(transportId, room, bytes),
1426
+ reportServerSnapshotBytes: (room, bytes) => this.reportServerSnapshotBytes(transportId, room, bytes),
1427
+ reportServerFlockBundle: (room, bundle) => this.reportServerFlockBundle(transportId, room, bundle),
1428
+ reportServerFlockSnapshotBytes: (room, bytes) => this.reportServerFlockSnapshotBytes(transportId, room, bytes),
1429
+ hasWithheld: (room) => this.hasWithheld(transportId, room),
1430
+ exportLoroUpdatesWithPolicy: (room, doc, fromVersion) => this.exportLoroUpdatesWithPolicy(transportId, room, doc, fromVersion),
1431
+ exportLoroLiveUpdatesWithPolicy: (room, doc, updates, extraConfirmed) => this.exportLoroLiveUpdatesWithPolicy(transportId, room, doc, updates, extraConfirmed),
1432
+ exportFlockBundleWithPolicy: (room, flock, fromVersion, extraConfirmed) => this.exportFlockBundleWithPolicy(transportId, room, flock, fromVersion, extraConfirmed),
1433
+ exportLoroMaturedDelta: (room, doc, extraConfirmed) => this.exportLoroMaturedDelta(transportId, room, doc, extraConfirmed),
1434
+ exportFlockMaturedDelta: (room, flock, extraConfirmed) => this.exportFlockMaturedDelta(transportId, room, flock, extraConfirmed),
1435
+ registerTargetHandler: (room, handler) => this.registerTargetHandler(transportId, room, handler)
1436
+ };
1437
+ this.hosts.set(transportId, host);
1438
+ }
1439
+ return host;
1440
+ }
1441
+ setTransportPolicy(transportId, policy) {
1442
+ if (policy && hasPositiveDelayInPolicy(policy)) this.transportPolicies.set(transportId, policy);
1443
+ else this.transportPolicies.delete(transportId);
1444
+ for (const record of this.rooms.values()) this.refreshPassiveObserver(record);
1445
+ }
1446
+ removeTransport(transportId) {
1447
+ this.transportPolicies.delete(transportId);
1448
+ for (const record of this.rooms.values()) {
1449
+ this.clearTargetState(record, transportId);
1450
+ this.refreshPassiveObserver(record);
1451
+ }
1452
+ }
1453
+ setRoomRoute(room, route, routePolicies) {
1454
+ const record = this.getOrCreateRecord(room);
1455
+ record.route = [...route];
1456
+ record.routePolicies = routePolicies;
1457
+ for (const targetId of [...record.loroTargets.keys(), ...record.flockTargets.keys()]) if (!record.route.includes(targetId)) this.clearTargetState(record, targetId);
1458
+ this.refreshPassiveObserver(record);
1459
+ }
1460
+ registerLoroReplica(room, doc) {
1461
+ if (this.destroyed) return;
1462
+ const record = this.getOrCreateRecord(room);
1463
+ if (record.replicaKind === "loro" && record.doc === doc) {
1464
+ this.refreshPassiveObserver(record);
1465
+ return;
1466
+ }
1467
+ this.resetReplicaState(record);
1468
+ record.replicaKind = "loro";
1469
+ record.doc = doc;
1470
+ record.flock = void 0;
1471
+ this.refreshPassiveObserver(record);
1472
+ }
1473
+ registerFlockReplica(room, flock) {
1474
+ if (this.destroyed) return;
1475
+ const record = this.getOrCreateRecord(room);
1476
+ if (record.replicaKind === "flock" && record.flock === flock) {
1477
+ this.refreshPassiveObserver(record);
1478
+ return;
1479
+ }
1480
+ this.resetReplicaState(record);
1481
+ record.replicaKind = "flock";
1482
+ record.flock = flock;
1483
+ record.doc = void 0;
1484
+ this.refreshPassiveObserver(record);
1485
+ }
1486
+ detachRoomTransport(room, transportId) {
1487
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1488
+ if (!record) return;
1489
+ this.clearTargetState(record, transportId);
1490
+ }
1491
+ clearRoom(room) {
1492
+ const key = forwardingRoomKey(room.kind, room.id);
1493
+ const record = this.rooms.get(key);
1494
+ if (!record) return;
1495
+ this.resetReplicaState(record);
1496
+ this.rooms.delete(key);
1497
+ }
1498
+ destroy() {
1499
+ if (this.destroyed) return;
1500
+ this.destroyed = true;
1501
+ for (const record of this.rooms.values()) this.resetReplicaState(record);
1502
+ this.rooms.clear();
1503
+ this.transportPolicies.clear();
1504
+ }
1505
+ hasPolicyForRoom(room, route, routePolicies) {
1506
+ if (routePolicies) {
1507
+ for (const policy of Object.values(routePolicies)) if (hasPositiveDelayInPolicy(policy)) return true;
1508
+ }
1509
+ for (const targetId of route) if (hasPositiveDelayInPolicy(this.transportPolicies.get(targetId))) return true;
1510
+ const existing = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1511
+ if (existing?.routePolicies) {
1512
+ for (const policy of Object.values(existing.routePolicies)) if (hasPositiveDelayInPolicy(policy)) return true;
1513
+ }
1514
+ return false;
1515
+ }
1516
+ isTransportCoveredByPolicyForRoom(room, route, transportId, routePolicies) {
1517
+ const existing = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1518
+ const effectiveRoutePolicies = routePolicies ?? existing?.routePolicies;
1519
+ const candidateTargets = new Set(route);
1520
+ if (effectiveRoutePolicies) for (const tid of Object.keys(effectiveRoutePolicies)) candidateTargets.add(tid);
1521
+ const resolveEffectiveDelay = (targetId, sourceId) => {
1522
+ if (targetId === sourceId) return void 0;
1523
+ const routePolicy = effectiveRoutePolicies?.[targetId];
1524
+ const ms = routePolicy?.delayFromTransports !== void 0 && Object.prototype.hasOwnProperty.call(routePolicy.delayFromTransports, sourceId) ? routePolicy?.delayFromTransports?.[sourceId] : this.transportPolicies.get(targetId)?.delayFromTransports?.[sourceId];
1525
+ return isPositiveDelayMs(ms) ? ms : void 0;
1526
+ };
1527
+ const targetSources = new Set(route);
1528
+ const rMap = effectiveRoutePolicies?.[transportId]?.delayFromTransports;
1529
+ if (rMap) for (const src of Object.keys(rMap)) targetSources.add(src);
1530
+ const tMap = this.transportPolicies.get(transportId)?.delayFromTransports;
1531
+ if (tMap) for (const src of Object.keys(tMap)) targetSources.add(src);
1532
+ for (const src of targetSources) if (resolveEffectiveDelay(transportId, src) !== void 0) return true;
1533
+ for (const targetId of candidateTargets) if (resolveEffectiveDelay(targetId, transportId) !== void 0) return true;
1534
+ return false;
1535
+ }
1536
+ hasPendingDelaysForRoom(room, targetTransportId) {
1537
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1538
+ if (!record) return false;
1539
+ if (targetTransportId !== void 0) {
1540
+ if (record.loroTargets.get(targetTransportId)?.hasPendingDelay()) return true;
1541
+ if (record.flockTargets.get(targetTransportId)?.hasPendingDelay()) return true;
1542
+ return false;
1543
+ }
1544
+ for (const t of record.loroTargets.values()) if (t.hasPendingDelay()) return true;
1545
+ for (const t of record.flockTargets.values()) if (t.hasPendingDelay()) return true;
1546
+ return false;
1547
+ }
1548
+ /**
1549
+ * Matures withheld updates for `(room, targetTransportId)` (or all targets
1550
+ * in `room` when `targetTransportId` is omitted) and invokes registered live
1551
+ * handlers to push uncovered delta immediately. Returns promises from any
1552
+ * target handlers that provide `awaitSynced`.
1553
+ */
1554
+ async flushRoomDelayedForwards(room, targetTransportId) {
1555
+ if (this.destroyed) return;
1556
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1557
+ if (!record) return;
1558
+ const targetIds = targetTransportId !== void 0 ? [targetTransportId] : Array.from(/* @__PURE__ */ new Set([
1559
+ ...record.loroTargets.keys(),
1560
+ ...record.flockTargets.keys(),
1561
+ ...record.targetHandlers.keys()
1562
+ ]));
1563
+ const waits = [];
1564
+ for (const tid of targetIds) waits.push(this.flushTargetDelayedForwards(record, tid));
1565
+ if (waits.length > 0) await Promise.all(waits);
1566
+ }
1567
+ async flushTargetDelayedForwards(record, tid) {
1568
+ await this.sourceLookup.awaitPendingAttach?.(record.room, tid);
1569
+ if (this.destroyed || this.rooms.get(record.key) !== record) return;
1570
+ if (!this.hasPendingDelaysForRoom(record.room, tid)) return;
1571
+ const handler = record.targetHandlers.get(tid);
1572
+ if (!handler) return;
1573
+ if (handler.isReadyForPush && !handler.isReadyForPush(record.room)) {
1574
+ await handler.awaitSynced?.(record.room);
1575
+ if (this.destroyed || this.rooms.get(record.key) !== record) return;
1576
+ if (!this.hasPendingDelaysForRoom(record.room, tid)) return;
1577
+ const refreshedHandler = record.targetHandlers.get(tid);
1578
+ if (!refreshedHandler) return;
1579
+ if (refreshedHandler.isReadyForPush && !refreshedHandler.isReadyForPush(record.room)) return;
1580
+ this.matureTargetWithoutPush(record, tid);
1581
+ if (refreshedHandler.pushMaturedDelta?.(record.room) !== false && refreshedHandler.awaitSynced) await refreshedHandler.awaitSynced(record.room);
1582
+ return;
1583
+ }
1584
+ this.matureTargetWithoutPush(record, tid);
1585
+ if (handler.pushMaturedDelta?.(record.room) !== false && handler.awaitSynced) await handler.awaitSynced(record.room);
1586
+ }
1587
+ async flushAllDelayedForwards() {
1588
+ if (this.destroyed) return;
1589
+ const waits = [];
1590
+ for (const record of [...this.rooms.values()]) {
1591
+ const targetIds = /* @__PURE__ */ new Set([...record.loroTargets.keys(), ...record.flockTargets.keys()]);
1592
+ for (const tid of targetIds) {
1593
+ if (!this.hasPendingDelaysForRoom(record.room, tid)) continue;
1594
+ waits.push(this.flushTargetDelayedForwards(record, tid));
1595
+ }
1596
+ }
1597
+ if (waits.length > 0) await Promise.all(waits);
1598
+ }
1599
+ registerTargetHandler(targetTransportId, room, handler) {
1600
+ const record = this.getOrCreateRecord(room);
1601
+ record.targetHandlers.set(targetTransportId, handler);
1602
+ return () => {
1603
+ if (record.targetHandlers.get(targetTransportId) === handler) record.targetHandlers.delete(targetTransportId);
1604
+ };
1605
+ }
1606
+ runWithRemoteImport(sourceTransportId, room, fn) {
1607
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1608
+ if (!record || this.destroyed) return fn();
1609
+ if (!this.hasActivePolicyForRoom(record)) return fn();
1610
+ if (record.replicaKind === "loro" && record.doc) {
1611
+ const doc = record.doc;
1612
+ const beforeApplied = toLoroVersionRecord(doc.version());
1613
+ const beforePending = decodeLoroPendingSpans(doc);
1614
+ if (record.activeImportDepth === 0) this.syncUnhandledPendingBeforeImport(record, beforePending);
1615
+ record.activeImportDepth += 1;
1616
+ try {
1617
+ return fn();
1618
+ } finally {
1619
+ record.activeImportDepth -= 1;
1620
+ const afterApplied = toLoroVersionRecord(doc.version());
1621
+ const afterPending = decodeLoroPendingSpans(doc);
1622
+ this.attributeLoroImport(record, sourceTransportId, beforeApplied, afterApplied, beforePending, afterPending);
1623
+ }
1624
+ }
1625
+ if (record.replicaKind === "flock" && record.flock) {
1626
+ const flock = record.flock;
1627
+ normalizeFlockVersion(flock.inclusiveVersion());
1628
+ const importedRecords = /* @__PURE__ */ new Map();
1629
+ const unsubscribeImport = flock.subscribe((batch) => {
1630
+ if (batch.source === "local") return;
1631
+ for (const ev of batch.events) {
1632
+ const entry = flock.getEntry(ev.key);
1633
+ if (!entry) continue;
1634
+ importedRecords.set(JSON.stringify(ev.key), {
1635
+ peerId: entry.clock.peerId,
1636
+ entry: {
1637
+ physicalTime: entry.clock.physicalTime,
1638
+ logicalCounter: entry.clock.logicalCounter
1639
+ }
1640
+ });
1641
+ }
1642
+ });
1643
+ record.activeImportDepth += 1;
1644
+ try {
1645
+ return fn();
1646
+ } finally {
1647
+ record.activeImportDepth -= 1;
1648
+ unsubscribeImport();
1649
+ const after = normalizeFlockVersion(flock.inclusiveVersion());
1650
+ this.attributeFlockImport(record, sourceTransportId, importedRecords, after);
1651
+ }
1652
+ }
1653
+ return fn();
1654
+ }
1655
+ syncUnhandledPendingBeforeImport(record, currentPending) {
1656
+ if (currentPending.isEmpty()) {
1657
+ record.loroPendingObserved = currentPending;
1658
+ return;
1659
+ }
1660
+ const newlyPending = currentPending.clone();
1661
+ newlyPending.subtractSet(record.loroPendingObserved);
1662
+ record.loroPendingObserved = currentPending;
1663
+ if (newlyPending.isEmpty()) return;
1664
+ const sourceId = this.findUnambiguousUnhookedDelayedSource(record);
1665
+ if (!sourceId) return;
1666
+ let srcSet = record.loroPendingBySource.get(sourceId);
1667
+ if (!srcSet) {
1668
+ srcSet = new LoroRangeSet();
1669
+ record.loroPendingBySource.set(sourceId, srcSet);
1670
+ }
1671
+ srcSet.addSet(newlyPending);
1672
+ }
1673
+ reportServerVersion(targetTransportId, room, version, options) {
1674
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1675
+ if (!record || this.destroyed) return;
1676
+ if (record.replicaKind === "loro") {
1677
+ if (!this.isDelayedTargetForRoom(record, targetTransportId) && !record.loroTargets.has(targetTransportId)) return;
1678
+ const parsed = toLoroVersionRecord(version);
1679
+ if (Object.keys(parsed).length === 0) return;
1680
+ this.ensureLoroTarget(record, targetTransportId).reportConfirmedContiguous(parsed);
1681
+ } else if (record.replicaKind === "flock") {
1682
+ if (!this.isDelayedTargetForRoom(record, targetTransportId) && !record.flockTargets.has(targetTransportId)) return;
1683
+ const parsed = normalizeFlockVersion(version);
1684
+ if (Object.keys(parsed).length === 0) return;
1685
+ this.ensureFlockTarget(record, targetTransportId).reportConfirmed(parsed);
1686
+ }
1687
+ }
1688
+ reportServerFlockBundle(targetTransportId, room, bundle) {
1689
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1690
+ if (!record || this.destroyed || record.replicaKind !== "flock") return;
1691
+ if (!this.isDelayedTargetForRoom(record, targetTransportId) && !record.flockTargets.has(targetTransportId)) return;
1692
+ const entries = bundle?.entries;
1693
+ if (!entries || Object.keys(entries).length === 0) return;
1694
+ const target = this.ensureFlockTarget(record, targetTransportId);
1695
+ for (const [key, rawRec] of Object.entries(entries)) {
1696
+ const parsed = parseFlockClockRecord(rawRec);
1697
+ if (!parsed) continue;
1698
+ target.reportConfirmedRecord(key, parsed.peerId, parsed.entry);
1699
+ }
1700
+ }
1701
+ reportServerFlockSnapshotBytes(targetTransportId, room, bytes) {
1702
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1703
+ if (!record || this.destroyed || record.replicaKind !== "flock") return;
1704
+ if (!this.isDelayedTargetForRoom(record, targetTransportId) && !record.flockTargets.has(targetTransportId)) return;
1705
+ if (bytes.byteLength === 0) return;
1706
+ try {
1707
+ const rows = Flock.fromFile(bytes, "forwarding-snapshot-scan").scan({ includeRaw: true });
1708
+ if (rows.length === 0) return;
1709
+ const target = this.ensureFlockTarget(record, targetTransportId);
1710
+ for (const row of rows) {
1711
+ const parsed = parseFlockClockRecord(row.raw);
1712
+ if (!parsed) continue;
1713
+ target.reportConfirmedRecord(JSON.stringify(row.key), parsed.peerId, parsed.entry);
1714
+ }
1715
+ } catch {
1716
+ }
1717
+ }
1718
+ reportServerUpdateBytes(targetTransportId, room, bytes) {
1719
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1720
+ if (!record || this.destroyed || record.replicaKind !== "loro") return;
1721
+ if (!this.isDelayedTargetForRoom(record, targetTransportId) && !record.loroTargets.has(targetTransportId)) return;
1722
+ if (bytes.byteLength === 0) return;
1723
+ try {
1724
+ const spans = decodeExactLoroSpans(bytes);
1725
+ if (spans.length === 0) return;
1726
+ const target = this.ensureLoroTarget(record, targetTransportId);
1727
+ for (const span of spans) target.reportConfirmedSpan(span.peer, span.start, span.end);
1728
+ } catch {
1729
+ }
1730
+ }
1731
+ reportServerSnapshotBytes(targetTransportId, room, bytes) {
1732
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1733
+ if (!record || this.destroyed || record.replicaKind !== "loro") return;
1734
+ if (!this.isDelayedTargetForRoom(record, targetTransportId) && !record.loroTargets.has(targetTransportId)) return;
1735
+ if (bytes.byteLength === 0) return;
1736
+ try {
1737
+ const endVersion = toLoroVersionRecord(decodeImportBlobMeta(bytes, false).partialEndVersionVector);
1738
+ if (Object.keys(endVersion).length > 0) this.ensureLoroTarget(record, targetTransportId).reportConfirmedContiguous(endVersion);
1739
+ } catch {
1740
+ }
1741
+ }
1742
+ hasWithheld(targetTransportId, room) {
1743
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1744
+ if (!record) return false;
1745
+ if (record.replicaKind === "loro") {
1746
+ const target = record.loroTargets.get(targetTransportId);
1747
+ return target !== void 0 && !target.withheld.isEmpty();
1748
+ }
1749
+ if (record.replicaKind === "flock") {
1750
+ const target = record.flockTargets.get(targetTransportId);
1751
+ return target !== void 0 && target.withheldRecords.size > 0;
1752
+ }
1753
+ return false;
1754
+ }
1755
+ exportLoroUpdatesWithPolicy(targetTransportId, room, doc, fromVersion) {
1756
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1757
+ const target = record ? this.ensureLoroTarget(record, targetTransportId) : void 0;
1758
+ if (!target) return void 0;
1759
+ return target.exportDelta(doc, fromVersion, true);
1760
+ }
1761
+ exportLoroLiveUpdatesWithPolicy(targetTransportId, room, doc, updates, extraConfirmed) {
1762
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1763
+ if (!record) return void 0;
1764
+ const target = record.loroTargets.get(targetTransportId);
1765
+ if (!target || target.withheld.isEmpty()) return void 0;
1766
+ const seed = new LoroRangeSet();
1767
+ for (const bytes of updates) {
1768
+ if (bytes.byteLength === 0) continue;
1769
+ try {
1770
+ for (const span of decodeExactLoroSpans(bytes)) seed.add(span.peer, span.start, span.end);
1771
+ } catch {
1772
+ return;
1773
+ }
1774
+ }
1775
+ if (seed.isEmpty()) return void 0;
1776
+ const lowerMap = mergeLoroVersionRecords(target.confirmedUpTo, extraConfirmed);
1777
+ const closure = resolveCausalClosure(doc, seed, lowerMap, target.confirmedSparse);
1778
+ let finalRanges;
1779
+ if (closure) {
1780
+ const extra = closure.clone();
1781
+ extra.subtractSet(seed);
1782
+ if (extra.isEmpty()) return void 0;
1783
+ finalRanges = seed.clone();
1784
+ finalRanges.addSet(closure);
1785
+ finalRanges.subtractSet(target.confirmedSparse);
1786
+ target.withheld.subtractSet(finalRanges);
1787
+ if (target.withheld.isEmpty()) target.clearTimer();
1788
+ } else {
1789
+ finalRanges = seed.clone();
1790
+ for (const peer of target.withheld.peers()) {
1791
+ const lower = lowerMap[peer] ?? 0;
1792
+ for (const span of target.withheld.get(peer)) {
1793
+ const start = Math.max(span.start, lower);
1794
+ if (span.end > start) finalRanges.add(peer, start, span.end);
1795
+ }
1796
+ }
1797
+ finalRanges.subtractSet(target.confirmedSparse);
1798
+ target.withheld.clear();
1799
+ target.clearTimer();
1800
+ }
1801
+ const exportedUpdates = exportLoroRangesHoleFree(doc, finalRanges);
1802
+ if (exportedUpdates.length === 0) return void 0;
1803
+ return {
1804
+ updates: exportedUpdates,
1805
+ version: computeContiguousExportVersion(finalRanges, lowerMap, target.confirmedSparse)
1806
+ };
1807
+ }
1808
+ exportLoroMaturedDelta(targetTransportId, room, doc, extraConfirmed) {
1809
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1810
+ const target = record ? this.ensureLoroTarget(record, targetTransportId) : void 0;
1811
+ if (!target) return void 0;
1812
+ return target.exportDelta(doc, extraConfirmed, true);
1813
+ }
1814
+ exportFlockBundleWithPolicy(targetTransportId, room, flock, fromVersion, extraConfirmed) {
1815
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1816
+ const target = record ? this.ensureFlockTarget(record, targetTransportId) : void 0;
1817
+ if (!target) return void 0;
1818
+ return target.exportBundle(flock, fromVersion, extraConfirmed, true);
1819
+ }
1820
+ exportFlockMaturedDelta(targetTransportId, room, flock, extraConfirmed) {
1821
+ const record = this.rooms.get(forwardingRoomKey(room.kind, room.id));
1822
+ const target = record ? this.ensureFlockTarget(record, targetTransportId) : void 0;
1823
+ if (!target) return void 0;
1824
+ return target.exportBundle(flock, void 0, extraConfirmed, true);
1825
+ }
1826
+ getOrCreateRecord(room) {
1827
+ const key = forwardingRoomKey(room.kind, room.id);
1828
+ let record = this.rooms.get(key);
1829
+ if (!record) {
1830
+ record = {
1831
+ room,
1832
+ key,
1833
+ route: [],
1834
+ activeImportDepth: 0,
1835
+ loroObserved: {},
1836
+ loroPendingObserved: new LoroRangeSet(),
1837
+ loroPendingBySource: /* @__PURE__ */ new Map(),
1838
+ flockObserved: {},
1839
+ loroTargets: /* @__PURE__ */ new Map(),
1840
+ flockTargets: /* @__PURE__ */ new Map(),
1841
+ targetHandlers: /* @__PURE__ */ new Map()
1842
+ };
1843
+ this.rooms.set(key, record);
1844
+ }
1845
+ return record;
1846
+ }
1847
+ resetReplicaState(record) {
1848
+ record.passiveUnsubscribe?.();
1849
+ record.passiveUnsubscribe = void 0;
1850
+ for (const target of record.loroTargets.values()) {
1851
+ target.clearTimer();
1852
+ target.withheld.clear();
1853
+ target.confirmedSparse.clear();
1854
+ }
1855
+ record.loroTargets.clear();
1856
+ for (const target of record.flockTargets.values()) target.clearAll();
1857
+ record.flockTargets.clear();
1858
+ record.loroPendingBySource.clear();
1859
+ record.loroPendingObserved.clear();
1860
+ record.loroObserved = {};
1861
+ record.flockObserved = {};
1862
+ record.replicaKind = void 0;
1863
+ record.doc = void 0;
1864
+ record.flock = void 0;
1865
+ }
1866
+ clearTargetState(record, targetTransportId) {
1867
+ const loroTarget = record.loroTargets.get(targetTransportId);
1868
+ if (loroTarget) {
1869
+ loroTarget.clearTimer();
1870
+ loroTarget.withheld.clear();
1871
+ loroTarget.confirmedSparse.clear();
1872
+ record.loroTargets.delete(targetTransportId);
1873
+ }
1874
+ const flockTarget = record.flockTargets.get(targetTransportId);
1875
+ if (flockTarget) {
1876
+ flockTarget.clearAll();
1877
+ record.flockTargets.delete(targetTransportId);
1878
+ }
1879
+ record.targetHandlers.delete(targetTransportId);
1880
+ }
1881
+ matureTargetWithoutPush(record, targetTransportId) {
1882
+ let matured = false;
1883
+ const loroTarget = record.loroTargets.get(targetTransportId);
1884
+ if (loroTarget) {
1885
+ if (loroTarget.hasPendingDelay()) matured = true;
1886
+ loroTarget.clearTimer();
1887
+ loroTarget.withheld.clear();
1888
+ }
1889
+ const flockTarget = record.flockTargets.get(targetTransportId);
1890
+ if (flockTarget) {
1891
+ if (flockTarget.hasPendingDelay()) matured = true;
1892
+ flockTarget.clearTimer();
1893
+ flockTarget.clearWithheld();
1894
+ }
1895
+ return matured;
1896
+ }
1897
+ isDelayedTargetForRoom(record, targetTransportId) {
1898
+ const routeMap = record.routePolicies?.[targetTransportId]?.delayFromTransports;
1899
+ if (routeMap) {
1900
+ for (const [sourceId, delayMs] of Object.entries(routeMap)) if (sourceId !== targetTransportId && isPositiveDelayMs(delayMs)) return true;
1901
+ }
1902
+ const transportMap = this.transportPolicies.get(targetTransportId)?.delayFromTransports;
1903
+ if (transportMap) for (const [sourceId, delayMs] of Object.entries(transportMap)) {
1904
+ if (sourceId === targetTransportId) continue;
1905
+ if (routeMap && Object.prototype.hasOwnProperty.call(routeMap, sourceId)) continue;
1906
+ if (isPositiveDelayMs(delayMs)) return true;
1907
+ }
1908
+ return false;
1909
+ }
1910
+ hasActivePolicyForRoom(record) {
1911
+ if (record.routePolicies) {
1912
+ for (const targetId of Object.keys(record.routePolicies)) if (this.isDelayedTargetForRoom(record, targetId)) return true;
1913
+ }
1914
+ for (const transportId of record.route) if (this.isDelayedTargetForRoom(record, transportId)) return true;
1915
+ return false;
1916
+ }
1917
+ resolveDelayMs(record, targetTransportId, sourceTransportId) {
1918
+ if (targetTransportId === sourceTransportId) return void 0;
1919
+ const transportDelay = this.transportPolicies.get(targetTransportId)?.delayFromTransports?.[sourceTransportId];
1920
+ const routePolicy = record.routePolicies?.[targetTransportId];
1921
+ const delayMs = routePolicy?.delayFromTransports !== void 0 && Object.prototype.hasOwnProperty.call(routePolicy.delayFromTransports, sourceTransportId) ? routePolicy?.delayFromTransports?.[sourceTransportId] : transportDelay;
1922
+ if (typeof delayMs !== "number" || !Number.isFinite(delayMs) || delayMs <= 0) return;
1923
+ return delayMs;
1924
+ }
1925
+ resolveTargetIdsForSource(record, sourceTransportId) {
1926
+ const candidates = new Set(record.route);
1927
+ if (record.routePolicies) for (const tid of Object.keys(record.routePolicies)) candidates.add(tid);
1928
+ const targets = [];
1929
+ for (const targetTransportId of candidates) {
1930
+ const delayMs = this.resolveDelayMs(record, targetTransportId, sourceTransportId);
1931
+ if (delayMs !== void 0) targets.push({
1932
+ targetTransportId,
1933
+ delayMs
1934
+ });
1935
+ }
1936
+ return targets;
1937
+ }
1938
+ findUnambiguousUnhookedDelayedSource(record) {
1939
+ const candidates = new Set(record.route);
1940
+ if (record.routePolicies) for (const [tid, policy] of Object.entries(record.routePolicies)) {
1941
+ candidates.add(tid);
1942
+ if (policy.delayFromTransports) for (const src of Object.keys(policy.delayFromTransports)) candidates.add(src);
1943
+ }
1944
+ for (const [tid, policy] of this.transportPolicies) {
1945
+ candidates.add(tid);
1946
+ if (policy.delayFromTransports) for (const src of Object.keys(policy.delayFromTransports)) candidates.add(src);
1947
+ }
1948
+ const attachedUnhooked = [];
1949
+ const routedUnhooked = [];
1950
+ for (const id of candidates) {
1951
+ if (!this.sourceLookup.isAttachedOrRouted(record.room, id)) continue;
1952
+ const adapter = this.sourceLookup.getAdapter(id);
1953
+ if (adapter && isHookedTransport(adapter)) continue;
1954
+ routedUnhooked.push(id);
1955
+ if (this.sourceLookup.isAttached?.(record.room, id)) attachedUnhooked.push(id);
1956
+ }
1957
+ const pool = attachedUnhooked.length > 0 ? attachedUnhooked : routedUnhooked;
1958
+ let soleSource;
1959
+ if (pool.length === 1) soleSource = pool[0];
1960
+ else if (pool.length > 1) {
1961
+ const connected = pool.filter((id) => this.sourceLookup.getAdapter(id)?.isConnected?.() === true);
1962
+ if (connected.length === 1) soleSource = connected[0];
1963
+ }
1964
+ if (!soleSource) return;
1965
+ return this.resolveTargetIdsForSource(record, soleSource).length > 0 ? soleSource : void 0;
1966
+ }
1967
+ refreshPassiveObserver(record) {
1968
+ if (!(!this.destroyed && this.hasActivePolicyForRoom(record) && record.replicaKind !== void 0)) {
1969
+ record.passiveUnsubscribe?.();
1970
+ record.passiveUnsubscribe = void 0;
1971
+ return;
1972
+ }
1973
+ if (record.passiveUnsubscribe) return;
1974
+ if (record.replicaKind === "loro" && record.doc) {
1975
+ const doc = record.doc;
1976
+ record.loroObserved = mergeLoroVersionRecords(record.loroObserved, toLoroVersionRecord(doc.version()));
1977
+ record.loroPendingObserved = decodeLoroPendingSpans(doc);
1978
+ record.passiveUnsubscribe = doc.subscribe((event) => {
1979
+ if (this.destroyed || record.doc !== doc) return;
1980
+ if (record.activeImportDepth > 0) return;
1981
+ const current = toLoroVersionRecord(doc.version());
1982
+ if (event.by !== "import") {
1983
+ record.loroObserved = mergeLoroVersionRecords(record.loroObserved, current);
1984
+ return;
1985
+ }
1986
+ const sourceId = this.findUnambiguousUnhookedDelayedSource(record);
1987
+ const before = record.loroObserved;
1988
+ const currentPending = decodeLoroPendingSpans(doc);
1989
+ if (sourceId) this.attributeLoroImport(record, sourceId, before, current, record.loroPendingObserved, currentPending);
1990
+ else {
1991
+ record.loroObserved = mergeLoroVersionRecords(before, current);
1992
+ record.loroPendingObserved = currentPending;
1993
+ }
1994
+ });
1995
+ } else if (record.replicaKind === "flock" && record.flock) {
1996
+ const flock = record.flock;
1997
+ record.flockObserved = mergeFlockVersions(record.flockObserved, normalizeFlockVersion(flock.inclusiveVersion()));
1998
+ record.passiveUnsubscribe = flock.subscribe((batch) => {
1999
+ if (this.destroyed || record.flock !== flock) return;
2000
+ if (record.activeImportDepth > 0) return;
2001
+ const current = normalizeFlockVersion(flock.inclusiveVersion());
2002
+ if (batch.source === "local") {
2003
+ record.flockObserved = mergeFlockVersions(record.flockObserved, current);
2004
+ return;
2005
+ }
2006
+ const importedRecords = /* @__PURE__ */ new Map();
2007
+ for (const ev of batch.events) {
2008
+ const entry = flock.getEntry(ev.key);
2009
+ if (!entry) continue;
2010
+ importedRecords.set(JSON.stringify(ev.key), {
2011
+ peerId: entry.clock.peerId,
2012
+ entry: {
2013
+ physicalTime: entry.clock.physicalTime,
2014
+ logicalCounter: entry.clock.logicalCounter
2015
+ }
2016
+ });
2017
+ }
2018
+ const sourceId = this.findUnambiguousUnhookedDelayedSource(record);
2019
+ if (sourceId) this.attributeFlockImport(record, sourceId, importedRecords, current);
2020
+ else {
2021
+ record.flockObserved = mergeFlockVersions(record.flockObserved, current);
2022
+ for (const target of record.flockTargets.values()) target.trackUnconfirmedRecords(importedRecords);
2023
+ }
2024
+ });
2025
+ }
2026
+ }
2027
+ attributeLoroImport(record, sourceTransportId, beforeApplied, afterApplied, beforePending, afterPending) {
2028
+ record.loroObserved = mergeLoroVersionRecords(record.loroObserved, afterApplied);
2029
+ record.loroPendingObserved = afterPending;
2030
+ if (!afterPending.isEmpty()) {
2031
+ const newlyPending = new LoroRangeSet();
2032
+ for (const peer of afterPending.peers()) for (const span of afterPending.get(peer)) newlyPending.add(peer, span.start, span.end);
2033
+ newlyPending.subtractSet(beforePending);
2034
+ if (!newlyPending.isEmpty()) {
2035
+ let srcSet = record.loroPendingBySource.get(sourceTransportId);
2036
+ if (!srcSet) {
2037
+ srcSet = new LoroRangeSet();
2038
+ record.loroPendingBySource.set(sourceTransportId, srcSet);
2039
+ }
2040
+ for (const peer of newlyPending.peers()) for (const span of newlyPending.get(peer)) srcSet.add(peer, span.start, span.end);
2041
+ }
2042
+ }
2043
+ const bySource = /* @__PURE__ */ new Map();
2044
+ for (const [peer, end] of Object.entries(afterApplied)) {
2045
+ const start = beforeApplied[peer] ?? 0;
2046
+ if (end <= start) continue;
2047
+ const remainingForCurrentSource = new LoroRangeSet();
2048
+ remainingForCurrentSource.add(peer, start, end);
2049
+ for (const [prevSource, prevPendingSet] of record.loroPendingBySource) {
2050
+ const overlaps = prevPendingSet.intersectRange(peer, start, end);
2051
+ if (overlaps.length === 0) continue;
2052
+ let list = bySource.get(prevSource);
2053
+ if (!list) {
2054
+ list = [];
2055
+ bySource.set(prevSource, list);
2056
+ }
2057
+ for (const ov of overlaps) {
2058
+ list.push({
2059
+ peer,
2060
+ start: ov.start,
2061
+ end: ov.end
2062
+ });
2063
+ prevPendingSet.subtract(peer, ov.start, ov.end);
2064
+ remainingForCurrentSource.subtract(peer, ov.start, ov.end);
2065
+ }
2066
+ if (prevPendingSet.isEmpty()) record.loroPendingBySource.delete(prevSource);
2067
+ }
2068
+ for (const rest of remainingForCurrentSource.get(peer)) {
2069
+ let list = bySource.get(sourceTransportId);
2070
+ if (!list) {
2071
+ list = [];
2072
+ bySource.set(sourceTransportId, list);
2073
+ }
2074
+ list.push({
2075
+ peer,
2076
+ start: rest.start,
2077
+ end: rest.end
2078
+ });
2079
+ }
2080
+ }
2081
+ for (const [attributedSource, ranges] of bySource) {
2082
+ if (ranges.length === 0) continue;
2083
+ const targets = this.resolveTargetIdsForSource(record, attributedSource);
2084
+ for (const { targetTransportId, delayMs } of targets) {
2085
+ const target = this.ensureLoroTarget(record, targetTransportId);
2086
+ const uncovered = target.computeUncovered(ranges);
2087
+ if (uncovered.length === 0) continue;
2088
+ for (const u of uncovered) target.withheld.add(u.peer, u.start, u.end);
2089
+ this.rescheduleTargetTimer(record, targetTransportId, target, delayMs);
2090
+ }
2091
+ }
2092
+ }
2093
+ attributeFlockImport(record, sourceTransportId, importedRecords, after) {
2094
+ record.flockObserved = mergeFlockVersions(record.flockObserved, after);
2095
+ if (importedRecords.size === 0) return;
2096
+ const targets = this.resolveTargetIdsForSource(record, sourceTransportId);
2097
+ const delayedTargetIds = /* @__PURE__ */ new Set();
2098
+ for (const { targetTransportId, delayMs } of targets) {
2099
+ delayedTargetIds.add(targetTransportId);
2100
+ const target = this.ensureFlockTarget(record, targetTransportId);
2101
+ if (target.addUncoveredWithheld(importedRecords) === 0) continue;
2102
+ this.rescheduleTargetTimer(record, targetTransportId, target, delayMs);
2103
+ }
2104
+ for (const [targetTransportId, target] of record.flockTargets) {
2105
+ if (targetTransportId === sourceTransportId) continue;
2106
+ if (delayedTargetIds.has(targetTransportId)) continue;
2107
+ target.trackUnconfirmedRecords(importedRecords);
2108
+ }
2109
+ }
2110
+ rescheduleTargetTimer(record, targetTransportId, target, delayMs) {
2111
+ target.clearTimer();
2112
+ target.timer = setTimeout(() => {
2113
+ target.timer = void 0;
2114
+ if (this.destroyed) return;
2115
+ if (this.rooms.get(record.key) !== record) return;
2116
+ if (target instanceof LoroTargetForwardState) target.withheld.clear();
2117
+ else target.clearWithheld();
2118
+ record.targetHandlers.get(targetTransportId)?.pushMaturedDelta?.(record.room);
2119
+ }, delayMs);
2120
+ }
2121
+ ensureLoroTarget(record, targetTransportId) {
2122
+ let target = record.loroTargets.get(targetTransportId);
2123
+ if (!target) {
2124
+ target = new LoroTargetForwardState();
2125
+ record.loroTargets.set(targetTransportId, target);
2126
+ }
2127
+ return target;
2128
+ }
2129
+ ensureFlockTarget(record, targetTransportId) {
2130
+ let target = record.flockTargets.get(targetTransportId);
2131
+ if (!target) {
2132
+ target = new FlockTargetForwardState();
2133
+ record.flockTargets.set(targetTransportId, target);
2134
+ }
2135
+ return target;
2136
+ }
2137
+ };
2138
+ function isPositiveDelayMs(delayMs) {
2139
+ return typeof delayMs === "number" && Number.isFinite(delayMs) && delayMs > 0;
2140
+ }
2141
+ function hasPositiveDelayInPolicy(policy) {
2142
+ const map = policy?.delayFromTransports;
2143
+ if (!map) return false;
2144
+ for (const delayMs of Object.values(map)) if (isPositiveDelayMs(delayMs)) return true;
2145
+ return false;
2146
+ }
736
2147
  function configureFlockDebounce(flock, config) {
737
2148
  const debounceMs = config.debounceMs;
738
2149
  if (debounceMs !== void 0 && debounceMs > 0) {
@@ -874,6 +2285,10 @@ var DocManager = class {
874
2285
  isLoaded(docId) {
875
2286
  return this.docs.has(docId);
876
2287
  }
2288
+ /** Returns the currently cached replica for `docId`, if loaded. */
2289
+ getLoadedDoc(docId) {
2290
+ return this.docs.get(docId);
2291
+ }
877
2292
  async openPersistedDoc(docId) {
878
2293
  return this.ensureDoc(docId);
879
2294
  }
@@ -1461,6 +2876,10 @@ var FlockDocManager = class {
1461
2876
  isLoaded(flockDocId) {
1462
2877
  return this.flocks.has(flockDocId);
1463
2878
  }
2879
+ /** Returns the currently cached Flock replica for `flockDocId`, if loaded. */
2880
+ getLoadedFlockDoc(flockDocId) {
2881
+ return this.flocks.get(flockDocId);
2882
+ }
1464
2883
  async openFlockDoc(flockDocId) {
1465
2884
  return this.ensureFlockDoc(flockDocId);
1466
2885
  }
@@ -2646,18 +4065,26 @@ var RoomTransportBinding = class {
2646
4065
  finish(done("detached"));
2647
4066
  return;
2648
4067
  }
2649
- const source = phase === "pending-upload-empty" ? base.waitUntilSynced() : base.firstSyncedWithRemote;
2650
- Promise.resolve(source).then(async () => {
4068
+ const run = async () => {
4069
+ if (phase === "pending-upload-empty") await this.hooks.beforePendingFlush?.();
4070
+ if (settled) return;
4071
+ if (options.flushDelayedForwards) await this.hooks.flushDelayedForwards?.();
4072
+ if (settled) return;
4073
+ const activeBase = this.base ?? base;
4074
+ await (phase === "pending-upload-empty" ? activeBase.waitUntilSynced() : activeBase.firstSyncedWithRemote);
2651
4075
  if (settled) return;
2652
4076
  if (phase !== "restored") await this.hooks.afterSynced?.();
2653
4077
  finish(done("complete"));
2654
- }).catch((error) => finish(done("error", error)));
4078
+ };
4079
+ run().catch((error) => finish(done("error", error)));
2655
4080
  });
2656
4081
  };
2657
- waitUntilSynced = async () => {
4082
+ waitUntilSynced = async (options) => {
2658
4083
  const base = this.base;
2659
4084
  if (!base) throw new Error(`Transport "${this.transportId}" is not attached to this room`);
2660
- await base.waitUntilSynced();
4085
+ await this.hooks.beforePendingFlush?.();
4086
+ if (options?.flushDelayedForwards) await this.hooks.flushDelayedForwards?.();
4087
+ await (this.base ?? base).waitUntilSynced();
2661
4088
  await this.hooks.afterSynced?.();
2662
4089
  };
2663
4090
  rejoin = async () => {
@@ -2840,6 +4267,7 @@ var SyncRunner = class {
2840
4267
  externalMetadata;
2841
4268
  getMetaFlock;
2842
4269
  flushMeta;
4270
+ forwarding;
2843
4271
  rooms = /* @__PURE__ */ new Map();
2844
4272
  unsubscribeMetaFlock;
2845
4273
  metaHydrationQueue = Promise.resolve();
@@ -2864,10 +4292,39 @@ var SyncRunner = class {
2864
4292
  this.externalMetadata = options.externalMetadata === true;
2865
4293
  this.getMetaFlock = options.getMetaFlock;
2866
4294
  this.flushMeta = options.flushMeta;
2867
- if (options.transportAdapter) this.transports.set(this.defaultTransportId, {
2868
- adapter: options.transportAdapter,
2869
- options: {}
4295
+ this.forwarding = new ForwardingCoordinator({
4296
+ isAttached: (room, transportId) => {
4297
+ const record = this.rooms.get(this.roomKey(room.kind, room.id));
4298
+ if (!record || record.closed) return false;
4299
+ return record.attachments.has(transportId);
4300
+ },
4301
+ isAttachedOrRouted: (room, transportId) => {
4302
+ const record = this.rooms.get(this.roomKey(room.kind, room.id));
4303
+ if (!record || record.closed) return false;
4304
+ return record.route.includes(transportId) || record.attachments.has(transportId);
4305
+ },
4306
+ getAdapter: (transportId) => this.transports.get(transportId)?.adapter,
4307
+ awaitPendingAttach: async (room, transportId) => {
4308
+ const pending2 = this.rooms.get(this.roomKey(room.kind, room.id))?.pendingAttaches.get(transportId);
4309
+ if (pending2) await pending2.run.catch(() => {
4310
+ });
4311
+ }
2870
4312
  });
4313
+ if (options.transportAdapter) {
4314
+ this.transports.set(this.defaultTransportId, {
4315
+ adapter: options.transportAdapter,
4316
+ options: {}
4317
+ });
4318
+ this.bindForwardingHooks(this.defaultTransportId, options.transportAdapter, {});
4319
+ }
4320
+ }
4321
+ bindForwardingHooks(transportId, adapter, options) {
4322
+ this.forwarding.setTransportPolicy(transportId, options.forwardingPolicy);
4323
+ getTransportForwardingHooks(adapter)?.bindHost(transportId, this.forwarding.getAdapterHost(transportId));
4324
+ }
4325
+ unbindForwardingHooks(transportId, adapter) {
4326
+ getTransportForwardingHooks(adapter)?.unbindHost(transportId, this.forwarding.getAdapterHost(transportId));
4327
+ this.forwarding.removeTransport(transportId);
2871
4328
  }
2872
4329
  hasTransports() {
2873
4330
  return this.transports.size > 0;
@@ -2889,6 +4346,7 @@ var SyncRunner = class {
2889
4346
  adapter,
2890
4347
  options
2891
4348
  });
4349
+ this.bindForwardingHooks(transportId, adapter, options);
2892
4350
  return this.refreshTransportRoutes();
2893
4351
  }
2894
4352
  async removeTransport(transportId, options = {}) {
@@ -2897,6 +4355,7 @@ var SyncRunner = class {
2897
4355
  this.transports.delete(transportId);
2898
4356
  try {
2899
4357
  for (const record of this.rooms.values()) this.detachRoomTransport(record, transportId);
4358
+ this.unbindForwardingHooks(transportId, entry.adapter);
2900
4359
  await this.refreshTransportRoutes();
2901
4360
  } finally {
2902
4361
  const current = this.transports.get(transportId);
@@ -2918,7 +4377,12 @@ var SyncRunner = class {
2918
4377
  for (const record of [...this.rooms.values()]) {
2919
4378
  if (record.closed) continue;
2920
4379
  try {
2921
- record.route = this.resolveRoute(record.kind, record.id);
4380
+ const routeInfo = this.resolveRouteInfo(record.kind, record.id);
4381
+ record.route = routeInfo.transportIds;
4382
+ this.forwarding.setRoomRoute({
4383
+ kind: record.kind,
4384
+ id: record.id
4385
+ }, routeInfo.transportIds, routeInfo.forwardingPolicy);
2922
4386
  } catch (error) {
2923
4387
  logAsyncError(`resolve transports for ${record.kind} room ${record.id}`)(error);
2924
4388
  }
@@ -3186,17 +4650,100 @@ var SyncRunner = class {
3186
4650
  * no-op rather than a double `close()` on each adapter.
3187
4651
  */
3188
4652
  async closeAllTransports() {
3189
- const entries = [...this.transports.values()];
4653
+ const entries = [...this.transports.entries()];
3190
4654
  this.transports.clear();
3191
4655
  let firstError;
3192
- for (const entry of entries) try {
3193
- await entry.adapter.close();
3194
- } catch (error) {
3195
- firstError ??= error;
4656
+ for (const [transportId, entry] of entries) {
4657
+ this.unbindForwardingHooks(transportId, entry.adapter);
4658
+ try {
4659
+ await entry.adapter.close();
4660
+ } catch (error) {
4661
+ firstError ??= error;
4662
+ }
3196
4663
  }
3197
4664
  if (firstError !== void 0) throw firstError;
3198
4665
  }
4666
+ hasForwardingPolicy(kind, id) {
4667
+ const route = this.resolveRouteInfo(kind, id);
4668
+ return this.forwarding.hasPolicyForRoom({
4669
+ kind,
4670
+ id
4671
+ }, route.transportIds, route.forwardingPolicy);
4672
+ }
4673
+ isTransportCoveredByPolicy(kind, id, transportId) {
4674
+ const route = this.resolveRouteInfo(kind, id);
4675
+ return this.forwarding.isTransportCoveredByPolicyForRoom({
4676
+ kind,
4677
+ id
4678
+ }, route.transportIds, transportId, route.forwardingPolicy);
4679
+ }
4680
+ async flushDelayedForwards() {
4681
+ await this.forwarding.flushAllDelayedForwards();
4682
+ }
4683
+ async syncDocOnce(docId, options = {}) {
4684
+ const skipHealthyLiveMode = options.force === true || options.skipHealthyLive === false ? "none" : options.skipHealthyLive === true ? "all" : this.hasForwardingPolicy("doc", docId) ? "policy" : "none";
4685
+ return this.runSync({
4686
+ scope: "doc",
4687
+ docIds: [docId],
4688
+ force: options.force,
4689
+ flushDelayedForwards: options.flushDelayedForwards,
4690
+ signal: options.signal
4691
+ }, { skipHealthyLiveMode });
4692
+ }
4693
+ async syncFlockDocOnce(flockDocId, options = {}) {
4694
+ const skipHealthyLiveMode = options.force === true || options.skipHealthyLive === false ? "none" : options.skipHealthyLive === true ? "all" : this.hasForwardingPolicy("flock-doc", flockDocId) ? "policy" : "none";
4695
+ return this.runSync({
4696
+ scope: "doc",
4697
+ flockDocIds: [flockDocId],
4698
+ force: options.force,
4699
+ flushDelayedForwards: options.flushDelayedForwards,
4700
+ signal: options.signal
4701
+ }, { skipHealthyLiveMode });
4702
+ }
4703
+ isHealthyLiveRoom(kind, id, transportId) {
4704
+ const entry = this.transports.get(transportId);
4705
+ if (!entry || !entry.adapter.isConnected()) return false;
4706
+ const record = this.rooms.get(this.roomKey(kind, id));
4707
+ if (!record || record.closed) return false;
4708
+ if (!record.route.includes(transportId)) return false;
4709
+ if (!record.attachments.has(transportId)) return false;
4710
+ return record.bindings.get(transportId)?.status === "joined";
4711
+ }
4712
+ async awaitSkippedLiveBinding(kind, id, transportId, options) {
4713
+ throwIfAborted(options.signal);
4714
+ const binding = this.rooms.get(this.roomKey(kind, id))?.bindings.get(transportId);
4715
+ if (!binding) throw new Error(`Live room ${kind}:${id} is not bound to transport "${transportId}"`);
4716
+ const assertComplete = (result) => {
4717
+ if (result.status === "complete") return;
4718
+ if (result.status === "aborted") {
4719
+ throwIfAborted(options.signal);
4720
+ throw new Error(`Live room sync aborted for ${kind}:${id} on transport "${transportId}"`);
4721
+ }
4722
+ if (result.status === "error") throw result.error instanceof Error ? result.error : new Error(String(result.error ?? `Live room sync failed for ${kind}:${id} on transport "${transportId}"`));
4723
+ throw new Error(`Live room ${kind}:${id} on transport "${transportId}" became ${result.status} before converging`);
4724
+ };
4725
+ assertComplete(await binding.waitFor({
4726
+ phase: "caught-up",
4727
+ signal: options.signal
4728
+ }));
4729
+ assertComplete(await binding.waitFor({
4730
+ phase: "pending-upload-empty",
4731
+ flushDelayedForwards: options.flushDelayedForwards,
4732
+ signal: options.signal
4733
+ }));
4734
+ if (kind === "doc") {
4735
+ const loadedDoc = this.docManager.getLoadedDoc(id);
4736
+ if (loadedDoc) await this.docManager.persistDocChanges(id, loadedDoc);
4737
+ } else if (kind === "flock-doc") {
4738
+ const loadedFlock = this.flockDocManager.getLoadedFlockDoc(id);
4739
+ if (loadedFlock) await this.flockDocManager.persistFlockDocChanges(id, loadedFlock);
4740
+ }
4741
+ }
3199
4742
  async sync(options = {}) {
4743
+ const skipHealthyLiveMode = options.force === true ? "none" : options.skipHealthyLive === true ? "all" : "none";
4744
+ return this.runSync(options, { skipHealthyLiveMode });
4745
+ }
4746
+ async runSync(options = {}, internal = {}) {
3200
4747
  const { signal } = options;
3201
4748
  throwIfAborted(signal);
3202
4749
  const required = options.requireTransports ?? [];
@@ -3237,6 +4784,14 @@ var SyncRunner = class {
3237
4784
  const scope = effectiveSyncScope(options);
3238
4785
  const metaRoute = !this.externalMetadata && (scope === "meta" || scope === "full") ? this.resolveRoute("meta", META_ROOM_ID) : [];
3239
4786
  const explicitFlockIds = options.flockDocIds !== void 0;
4787
+ const skipHealthyLiveMode = internal.skipHealthyLiveMode ?? "none";
4788
+ const shouldSkipHealthyLive = (kind, id, transportId) => {
4789
+ if (skipHealthyLiveMode === "none") return false;
4790
+ if (!this.isHealthyLiveRoom(kind, id, transportId)) return false;
4791
+ if (skipHealthyLiveMode === "all") return true;
4792
+ return this.isTransportCoveredByPolicy(kind, id, transportId);
4793
+ };
4794
+ const flushDelayedForwards = options.flushDelayedForwards === true;
3240
4795
  const entries = [...this.transports.entries()];
3241
4796
  const pipelines = entries.map(([transportId, entry]) => async () => {
3242
4797
  let connected = false;
@@ -3247,7 +4802,22 @@ var SyncRunner = class {
3247
4802
  };
3248
4803
  if (metaRoute.includes(transportId)) {
3249
4804
  attempted.add(transportId);
3250
- try {
4805
+ const metaRoom = {
4806
+ kind: "meta",
4807
+ id: META_ROOM_ID
4808
+ };
4809
+ if (shouldSkipHealthyLive("meta", META_ROOM_ID, transportId)) try {
4810
+ await this.awaitSkippedLiveBinding("meta", META_ROOM_ID, transportId, {
4811
+ flushDelayedForwards,
4812
+ signal
4813
+ });
4814
+ } catch (error) {
4815
+ if (signal?.aborted) throw error;
4816
+ recordFailure(transportId, "meta", void 0, error);
4817
+ return;
4818
+ }
4819
+ else try {
4820
+ if (flushDelayedForwards) await this.forwarding.flushRoomDelayedForwards(metaRoom, transportId);
3251
4821
  await connect();
3252
4822
  await this.syncMetaWith(entry.adapter, signal);
3253
4823
  } catch (error) {
@@ -3258,10 +4828,45 @@ var SyncRunner = class {
3258
4828
  }
3259
4829
  throwIfAborted(signal);
3260
4830
  const plan = await this.buildSyncPlan(options);
3261
- const docIds = plan.docIds.filter((docId) => this.resolveRoute("doc", docId).includes(transportId));
3262
- let flockDocIds = plan.flockDocIds.filter((flockDocId) => this.resolveRoute("flock-doc", flockDocId).includes(transportId) && (explicitFlockIds || entry.adapter.syncFlockDoc !== void 0));
3263
- if (docIds.length === 0 && flockDocIds.length === 0) return;
4831
+ const routedDocIds = plan.docIds.filter((docId) => this.resolveRoute("doc", docId).includes(transportId));
4832
+ const routedFlockDocIds = plan.flockDocIds.filter((flockDocId) => this.resolveRoute("flock-doc", flockDocId).includes(transportId) && (explicitFlockIds || entry.adapter.syncFlockDoc !== void 0));
4833
+ if (routedDocIds.length === 0 && routedFlockDocIds.length === 0) return;
3264
4834
  attempted.add(transportId);
4835
+ const docIds = [];
4836
+ const skippedLiveDocIds = [];
4837
+ for (const docId of routedDocIds) if (shouldSkipHealthyLive("doc", docId, transportId)) skippedLiveDocIds.push(docId);
4838
+ else docIds.push(docId);
4839
+ let flockDocIds = [];
4840
+ const skippedLiveFlockDocIds = [];
4841
+ for (const flockDocId of routedFlockDocIds) if (shouldSkipHealthyLive("flock-doc", flockDocId, transportId)) skippedLiveFlockDocIds.push(flockDocId);
4842
+ else flockDocIds.push(flockDocId);
4843
+ for (const docId of skippedLiveDocIds) {
4844
+ throwIfAborted(signal);
4845
+ try {
4846
+ await this.awaitSkippedLiveBinding("doc", docId, transportId, {
4847
+ flushDelayedForwards,
4848
+ signal
4849
+ });
4850
+ } catch (error) {
4851
+ if (signal?.aborted) throw error;
4852
+ recordFailure(transportId, "doc", docId, error);
4853
+ return;
4854
+ }
4855
+ }
4856
+ for (const flockDocId of skippedLiveFlockDocIds) {
4857
+ throwIfAborted(signal);
4858
+ try {
4859
+ await this.awaitSkippedLiveBinding("flock-doc", flockDocId, transportId, {
4860
+ flushDelayedForwards,
4861
+ signal
4862
+ });
4863
+ } catch (error) {
4864
+ if (signal?.aborted) throw error;
4865
+ recordFailure(transportId, "flock-doc", flockDocId, error);
4866
+ return;
4867
+ }
4868
+ }
4869
+ if (docIds.length === 0 && flockDocIds.length === 0) return;
3265
4870
  try {
3266
4871
  await connect();
3267
4872
  } catch (error) {
@@ -3276,6 +4881,10 @@ var SyncRunner = class {
3276
4881
  for (const docId of docIds) {
3277
4882
  throwIfAborted(signal);
3278
4883
  try {
4884
+ if (flushDelayedForwards) await this.forwarding.flushRoomDelayedForwards({
4885
+ kind: "doc",
4886
+ id: docId
4887
+ }, transportId);
3279
4888
  const wasLoaded = this.docManager.isLoaded(docId);
3280
4889
  const acquired = await this.docManager.acquireDoc(docId, "room", `sync:doc:${docId}`);
3281
4890
  const doc = acquired.doc;
@@ -3304,6 +4913,10 @@ var SyncRunner = class {
3304
4913
  for (const flockDocId of flockDocIds) {
3305
4914
  throwIfAborted(signal);
3306
4915
  try {
4916
+ if (flushDelayedForwards) await this.forwarding.flushRoomDelayedForwards({
4917
+ kind: "flock-doc",
4918
+ id: flockDocId
4919
+ }, transportId);
3307
4920
  const wasLoaded = this.flockDocManager.isLoaded(flockDocId);
3308
4921
  const acquired = await this.flockDocManager.acquireFlockDoc(flockDocId, "room", `sync:flock-doc:${flockDocId}`);
3309
4922
  const flock = acquired.flock;
@@ -3435,6 +5048,7 @@ var SyncRunner = class {
3435
5048
  this.activeMetaSyncCount += 1;
3436
5049
  try {
3437
5050
  throwIfAborted(signal);
5051
+ this.metaFlock.commit();
3438
5052
  const result = await adapter.syncMeta(this.metaFlock, signal ? { signal } : void 0);
3439
5053
  throwIfAborted(signal);
3440
5054
  if (!result.ok) throw result.error ?? /* @__PURE__ */ new Error("Metadata sync failed");
@@ -3501,12 +5115,16 @@ var SyncRunner = class {
3501
5115
  return this.createRoomLease(existing, generation$1);
3502
5116
  }
3503
5117
  if (existing) {
3504
- const route$1 = this.resolveRoute(kind, id);
5118
+ const routeInfo$1 = this.resolveRouteInfo(kind, id);
3505
5119
  existing.generation += 1;
3506
5120
  const generation$1 = existing.generation;
3507
5121
  existing.refCount = 1;
3508
5122
  existing.params = params;
3509
- existing.route = route$1;
5123
+ existing.route = routeInfo$1.transportIds;
5124
+ this.forwarding.setRoomRoute({
5125
+ kind,
5126
+ id
5127
+ }, routeInfo$1.transportIds, routeInfo$1.forwardingPolicy);
3510
5128
  for (const transportId of [...existing.attachments.keys()]) this.detachRoomTransport(existing, transportId);
3511
5129
  const rejoinAttach = this.attachRoutedForJoin(existing);
3512
5130
  existing.initialAttach = rejoinAttach;
@@ -3521,13 +5139,17 @@ var SyncRunner = class {
3521
5139
  this.syncClassicForwarder(existing);
3522
5140
  return this.createRoomLease(existing, generation$1);
3523
5141
  }
3524
- const route = this.resolveRoute(kind, id);
5142
+ const routeInfo = this.resolveRouteInfo(kind, id);
3525
5143
  const record = new RoomRecord(kind, id, params);
3526
5144
  record.refCount = 1;
3527
- record.route = route;
5145
+ record.route = routeInfo.transportIds;
3528
5146
  const generation = record.generation;
3529
5147
  this.acquireRoomResource(record);
3530
5148
  this.rooms.set(key, record);
5149
+ this.forwarding.setRoomRoute({
5150
+ kind,
5151
+ id
5152
+ }, routeInfo.transportIds, routeInfo.forwardingPolicy);
3531
5153
  const initialAttach = this.attachRoutedForJoin(record);
3532
5154
  record.initialAttach = initialAttach;
3533
5155
  try {
@@ -3548,18 +5170,24 @@ var SyncRunner = class {
3548
5170
  record.refCount = Math.max(0, record.refCount - 1);
3549
5171
  if (record.refCount === 0) this.teardownRoom(record);
3550
5172
  }
3551
- resolveRoute(kind, id) {
3552
- if (kind === "flock-doc" && this.flockDocManager.isExternal(id)) return [];
3553
- if (kind === "doc" && this.docManager.isExternal(id)) return [];
5173
+ resolveRouteInfo(kind, id) {
5174
+ if (kind === "flock-doc" && this.flockDocManager.isExternal(id)) return { transportIds: [] };
5175
+ if (kind === "doc" && this.docManager.isExternal(id)) return { transportIds: [] };
3554
5176
  const resolver = this.resolveRoomTransports;
3555
- if (!resolver) return [...this.transports.keys()];
5177
+ if (!resolver) return { transportIds: [...this.transports.keys()] };
3556
5178
  const route = resolver({
3557
5179
  kind,
3558
5180
  id
3559
5181
  });
3560
5182
  const transportIds = [];
3561
5183
  for (const transportId of route.transportIds) if (!transportIds.includes(transportId)) transportIds.push(transportId);
3562
- return transportIds;
5184
+ return {
5185
+ transportIds,
5186
+ forwardingPolicy: route.forwardingPolicy
5187
+ };
5188
+ }
5189
+ resolveRoute(kind, id) {
5190
+ return this.resolveRouteInfo(kind, id).transportIds;
3563
5191
  }
3564
5192
  /**
3565
5193
  * Join-path attach semantics: resolves as soon as ONE routed registered
@@ -3660,15 +5288,27 @@ var SyncRunner = class {
3660
5288
  if (record.kind === "meta") {
3661
5289
  await this.ensureMetaLiveMonitor();
3662
5290
  if (stale()) return;
5291
+ this.forwarding.registerFlockReplica({
5292
+ kind: "meta",
5293
+ id: META_ROOM_ID
5294
+ }, this.metaFlock);
3663
5295
  base = entry.adapter.joinMetaRoom(this.metaFlock, params);
3664
5296
  } else if (record.kind === "doc") {
3665
5297
  const doc = await this.docManager.ensureDoc(record.id);
3666
5298
  if (stale()) return;
5299
+ this.forwarding.registerLoroReplica({
5300
+ kind: "doc",
5301
+ id: record.id
5302
+ }, doc);
3667
5303
  base = entry.adapter.joinDocRoom(record.id, doc, params);
3668
5304
  } else {
3669
5305
  if (!entry.adapter.joinFlockDocRoom) throw new Error("Transport adapter does not support Flock docs");
3670
5306
  const flock = await this.flockDocManager.ensureFlockDoc(record.id);
3671
5307
  if (stale()) return;
5308
+ this.forwarding.registerFlockReplica({
5309
+ kind: "flock-doc",
5310
+ id: record.id
5311
+ }, flock);
3672
5312
  base = entry.adapter.joinFlockDocRoom(record.id, flock, params);
3673
5313
  }
3674
5314
  if (stale() || record.attachments.has(transportId)) {
@@ -3688,6 +5328,10 @@ var SyncRunner = class {
3688
5328
  }
3689
5329
  detachRoomTransport(record, transportId) {
3690
5330
  record.bindings.get(transportId)?.detach();
5331
+ this.forwarding.detachRoomTransport({
5332
+ kind: record.kind,
5333
+ id: record.id
5334
+ }, transportId);
3691
5335
  const base = record.attachments.get(transportId);
3692
5336
  if (!base) return;
3693
5337
  record.attachments.delete(transportId);
@@ -3701,7 +5345,12 @@ var SyncRunner = class {
3701
5345
  let binding = record.bindings.get(transportId);
3702
5346
  if (!binding) {
3703
5347
  binding = new RoomTransportBinding(transportId, {
5348
+ beforePendingFlush: record.kind === "meta" ? this.beforeMetaPendingFlush : void 0,
3704
5349
  afterSynced: record.kind === "meta" ? this.afterMetaSynced : void 0,
5350
+ flushDelayedForwards: () => this.forwarding.flushRoomDelayedForwards({
5351
+ kind: record.kind,
5352
+ id: record.id
5353
+ }, transportId),
3705
5354
  reattach: async () => {
3706
5355
  if (record.closed || this.destroyed) return false;
3707
5356
  if (!record.route.includes(transportId)) return false;
@@ -3714,6 +5363,10 @@ var SyncRunner = class {
3714
5363
  }
3715
5364
  return binding;
3716
5365
  }
5366
+ beforeMetaPendingFlush = () => {
5367
+ if (this.destroyed) return;
5368
+ this.metaFlock.commit();
5369
+ };
3717
5370
  afterMetaSynced = async () => {
3718
5371
  if (this.destroyed) return;
3719
5372
  this.metaFlock.commit();
@@ -3840,10 +5493,10 @@ var SyncRunner = class {
3840
5493
  const results = await Promise.all(bindings.map((binding) => binding.waitFor(options)));
3841
5494
  return results.find((result) => result.status !== "complete") ?? results[0];
3842
5495
  },
3843
- waitUntilSynced: () => {
5496
+ waitUntilSynced: (waitOptions) => {
3844
5497
  const target = classicTarget();
3845
5498
  if (!target) throw new Error(`Room "${record.id}" has no routed transports; use subscription(transportId) for per-transport state`);
3846
- return target.waitUntilSynced();
5499
+ return target.waitUntilSynced(waitOptions);
3847
5500
  },
3848
5501
  rejoin: async () => {
3849
5502
  let firstError;
@@ -3933,6 +5586,10 @@ var SyncRunner = class {
3933
5586
  record.classicBinding = void 0;
3934
5587
  for (const transportId of [...record.attachments.keys()]) this.detachRoomTransport(record, transportId);
3935
5588
  for (const binding of record.bindings.values()) binding.close();
5589
+ this.forwarding.clearRoom({
5590
+ kind: record.kind,
5591
+ id: record.id
5592
+ });
3936
5593
  this.rooms.delete(this.roomKey(record.kind, record.id));
3937
5594
  }
3938
5595
  roomKey(kind, id) {
@@ -3943,6 +5600,7 @@ var SyncRunner = class {
3943
5600
  this.destroyed = true;
3944
5601
  this.suppressMetaLiveMonitor = true;
3945
5602
  this.leaveRooms();
5603
+ this.forwarding.destroy();
3946
5604
  await this.metaHydrationQueue.catch(() => {
3947
5605
  });
3948
5606
  let firstError;
@@ -4000,6 +5658,10 @@ var SyncRunner = class {
4000
5658
  record.classicBinding = void 0;
4001
5659
  for (const transportId of [...record.attachments.keys()]) this.detachRoomTransport(record, transportId);
4002
5660
  for (const binding of record.bindings.values()) binding.detach();
5661
+ this.forwarding.clearRoom({
5662
+ kind: record.kind,
5663
+ id: record.id
5664
+ });
4003
5665
  }
4004
5666
  this.rooms.clear();
4005
5667
  this.unsubscribeMetaFlock?.();
@@ -5100,14 +6762,15 @@ var LoroRepo = class LoroRepo2 {
5100
6762
  await lease?.release();
5101
6763
  return {
5102
6764
  doc,
5103
- syncOnce: () => this.docManager.isExternal(docId) ? this.persistDocNow(docId, doc).then(() => ({
5104
- ok: true,
5105
- outcome: "no-route",
5106
- transports: []
5107
- })) : this.sync({
5108
- scope: "doc",
5109
- docIds: [docId]
5110
- }),
6765
+ syncOnce: (options) => this.docManager.isExternal(docId) ? (async () => {
6766
+ throwIfAborted(options?.signal);
6767
+ await this.persistDocNow(docId, doc);
6768
+ return {
6769
+ ok: true,
6770
+ outcome: "no-route",
6771
+ transports: []
6772
+ };
6773
+ })() : this.syncRunner.syncDocOnce(docId, options),
5111
6774
  joinRoom: (auth) => this.joinDocRoom(docId, { auth })
5112
6775
  };
5113
6776
  }
@@ -5117,14 +6780,15 @@ var LoroRepo = class LoroRepo2 {
5117
6780
  await lease?.release();
5118
6781
  return {
5119
6782
  flock,
5120
- syncOnce: () => this.flockDocManager.isExternal(flockDocId) ? this.persistFlockDocNow(flockDocId, flock).then(() => ({
5121
- ok: true,
5122
- outcome: "no-route",
5123
- transports: []
5124
- })) : this.sync({
5125
- scope: "doc",
5126
- flockDocIds: [flockDocId]
5127
- }),
6783
+ syncOnce: (options) => this.flockDocManager.isExternal(flockDocId) ? (async () => {
6784
+ throwIfAborted(options?.signal);
6785
+ await this.persistFlockDocNow(flockDocId, flock);
6786
+ return {
6787
+ ok: true,
6788
+ outcome: "no-route",
6789
+ transports: []
6790
+ };
6791
+ })() : this.syncRunner.syncFlockDocOnce(flockDocId, options),
5128
6792
  joinRoom: (auth) => this.joinFlockDocRoom(flockDocId, { auth })
5129
6793
  };
5130
6794
  }
@@ -5388,11 +7052,12 @@ var LoroRepo = class LoroRepo2 {
5388
7052
  async persistFlockDocNow(flockDocId, flock) {
5389
7053
  await this.flockDocManager.persistFlockDocChanges(flockDocId, flock, { requireCurrent: true });
5390
7054
  }
5391
- async flush() {
7055
+ async flush(options = {}) {
5392
7056
  if (this.externalMetadata) {
5393
7057
  const results$1 = await Promise.allSettled([this.docManager.flush(), this.flockDocManager.flush()]);
5394
7058
  const meta$1 = await Promise.allSettled([this.externalMetadata.flush()]);
5395
7059
  for (const result of [...results$1, ...meta$1]) if (result.status === "rejected") throw result.reason;
7060
+ if (options.flushDelayedForwards) await this.syncRunner.flushDelayedForwards();
5396
7061
  return;
5397
7062
  }
5398
7063
  const batch = this.writer.batch();
@@ -5413,6 +7078,7 @@ var LoroRepo = class LoroRepo2 {
5413
7078
  for (const result of results) if (result.status === "rejected") throw result.reason;
5414
7079
  this.metaFlock.commit();
5415
7080
  await this.metaPersister?.flushNow();
7081
+ if (options.flushDelayedForwards) await this.syncRunner.flushDelayedForwards();
5416
7082
  }
5417
7083
  get destroyed() {
5418
7084
  return this._destroyed;
@@ -6891,32 +8557,36 @@ const createDebugLogger = (namespace) => {
6891
8557
  };
6892
8558
  };
6893
8559
  const safeTransportErrors = /* @__PURE__ */ new WeakSet();
8560
+ const streamsTextEncoder = new TextEncoder();
8561
+ const streamsTextDecoder = new TextDecoder();
6894
8562
  const debug = createDebugLogger("transport:streams");
6895
8563
  function shouldRejoinRoom(status) {
6896
8564
  return status === "disconnected" || status === "error" || status === "reconnecting";
6897
8565
  }
6898
- function patchFlockExportJson(flock) {
6899
- const orig = flock.exportJson.bind(flock);
6900
- flock.exportJson = (arg, pruneTombstonesBefore) => {
6901
- if (arg && typeof arg === "object" && "from" in arg) {
6902
- const from = arg.from;
6903
- if (from != null && typeof from === "object" && Object.keys(from).length === 0) {
6904
- const { from: _from, ...rest } = arg;
6905
- if (Object.keys(rest).length === 0) return orig();
6906
- return orig(rest, pruneTombstonesBefore);
6907
- }
6908
- }
6909
- return arg === void 0 ? orig() : orig(arg, pruneTombstonesBefore);
6910
- };
6911
- return flock;
6912
- }
6913
- function createPersistentFlockAdapter(flock) {
6914
- const adapter = createFlockAdapter(patchFlockExportJson(flock));
6915
- return {
6916
- ...adapter,
6917
- applySnapshot: (snapshot) => receiveFlockPayloads(flock, [snapshot], () => adapter.applySnapshot(snapshot)),
6918
- applyRemoteUpdates: (updates, version) => receiveFlockPayloads(flock, updates, () => adapter.applyRemoteUpdates(updates, version))
6919
- };
8566
+ function createScopedFlockForExport(flock, getSubscribeFloor) {
8567
+ return new Proxy(flock, { get(target, prop) {
8568
+ if (prop === "exportJson") return (arg, pruneTombstonesBefore) => {
8569
+ if (arg && typeof arg === "object" && "from" in arg) {
8570
+ let from = arg.from;
8571
+ if (getSubscribeFloor && "peerId" in arg) {
8572
+ const floor = getSubscribeFloor();
8573
+ if (Object.keys(floor).length > 0) from = mergeFlockVersions(normalizeFlockVersion(from), floor);
8574
+ }
8575
+ if (from != null && typeof from === "object" && Object.keys(from).length === 0) {
8576
+ const { from: _from, ...rest } = arg;
8577
+ if (Object.keys(rest).length === 0) return target.exportJson();
8578
+ return target.exportJson(rest, pruneTombstonesBefore);
8579
+ }
8580
+ if (from !== arg.from) return target.exportJson({
8581
+ ...arg,
8582
+ from
8583
+ }, pruneTombstonesBefore);
8584
+ }
8585
+ return arg === void 0 ? target.exportJson() : target.exportJson(arg, pruneTombstonesBefore);
8586
+ };
8587
+ const value = Reflect.get(target, prop, target);
8588
+ return typeof value === "function" ? value.bind(target) : value;
8589
+ } });
6920
8590
  }
6921
8591
  function classifyStreamsErrorCode(code) {
6922
8592
  switch (code) {
@@ -7133,6 +8803,9 @@ var StreamsTransportAdapter = class {
7133
8803
  restartingRooms = /* @__PURE__ */ new Set();
7134
8804
  connectionStatus = "disconnected";
7135
8805
  connectionStatusListeners = /* @__PURE__ */ new Set();
8806
+ forwardingBinding;
8807
+ roomTargetRegistrars = /* @__PURE__ */ new Map();
8808
+ roomTargetUnregisters = /* @__PURE__ */ new Map();
7136
8809
  constructor(options) {
7137
8810
  if (options.uploadTransport !== void 0 && (!("uploadTransportVersion" in StreamsCrdt) || StreamsCrdt.uploadTransportVersion !== 1)) throw new TypeError("uploadTransport requires StreamsCrdt upload transport capability version 1");
7138
8811
  this.options = options;
@@ -7154,6 +8827,25 @@ var StreamsTransportAdapter = class {
7154
8827
  this.persistFlockDoc = options.onPersistFlockDoc;
7155
8828
  this.cursorsAreDurable = persistence?.mode !== "ephemeral" && options.remoteCursorStore !== void 0 && !(options.remoteCursorStore instanceof InMemoryRemoteCursorStore);
7156
8829
  }
8830
+ registerTransportForwardingHooks(this, {
8831
+ bindHost: (transportId, host) => {
8832
+ this.forwardingBinding = {
8833
+ transportId,
8834
+ host
8835
+ };
8836
+ for (const [key, register] of this.roomTargetRegistrars) {
8837
+ this.roomTargetUnregisters.get(key)?.();
8838
+ this.roomTargetUnregisters.set(key, register(host));
8839
+ }
8840
+ },
8841
+ unbindHost: (transportId, host) => {
8842
+ if (this.forwardingBinding?.transportId === transportId && this.forwardingBinding.host === host) {
8843
+ this.forwardingBinding = void 0;
8844
+ for (const unregister of this.roomTargetUnregisters.values()) unregister();
8845
+ this.roomTargetUnregisters.clear();
8846
+ }
8847
+ }
8848
+ });
7157
8849
  }
7158
8850
  /**
7159
8851
  * Provisions the backing stream for a room without joining it.
@@ -7234,7 +8926,7 @@ var StreamsTransportAdapter = class {
7234
8926
  const target = resolveStreamsCrdtTarget(room.kind === "meta" ? this.getStreamAddress(this.options.metaStreamId ?? "repo-meta") : room.kind === "doc" ? this.getStreamAddress(this.options.docStreamId?.(room.docId) ?? room.docId) : this.getFlockDocStreamAddress(room.flockDocId));
7235
8927
  const stream = this.createRoomStream({
7236
8928
  ...target,
7237
- adapter: room.kind === "doc" ? createLoroDocAdapter(new LoroDoc()) : createFlockAdapter(patchFlockExportJson(new Flock())),
8929
+ adapter: room.kind === "doc" ? createLoroDocAdapter(new LoroDoc()) : createFlockAdapter(createScopedFlockForExport(new Flock())),
7238
8930
  auth: this.resolveAuth(),
7239
8931
  reconnectConfig: this.options.reconnectConfig,
7240
8932
  remoteCursorStore: new InMemoryRemoteCursorStore(),
@@ -8487,6 +10179,8 @@ var StreamsTransportAdapter = class {
8487
10179
  teardownMetaSession(session) {
8488
10180
  if (session.teardownPromise) return session.teardownPromise;
8489
10181
  session.closed = true;
10182
+ session.cleanupForwarding?.();
10183
+ session.cleanupForwarding = void 0;
8490
10184
  session.teardownPromise = (async () => {
8491
10185
  session.subscription?.unsubscribe();
8492
10186
  session.subscription = void 0;
@@ -8503,6 +10197,8 @@ var StreamsTransportAdapter = class {
8503
10197
  teardownDocSession(docId, session) {
8504
10198
  if (session.teardownPromise) return session.teardownPromise;
8505
10199
  session.closed = true;
10200
+ session.cleanupForwarding?.();
10201
+ session.cleanupForwarding = void 0;
8506
10202
  session.teardownPromise = (async () => {
8507
10203
  session.subscription?.unsubscribe();
8508
10204
  session.subscription = void 0;
@@ -8519,6 +10215,8 @@ var StreamsTransportAdapter = class {
8519
10215
  teardownFlockDocSession(flockDocId, session) {
8520
10216
  if (session.teardownPromise) return session.teardownPromise;
8521
10217
  session.closed = true;
10218
+ session.cleanupForwarding?.();
10219
+ session.cleanupForwarding = void 0;
8522
10220
  session.teardownPromise = (async () => {
8523
10221
  session.subscription?.unsubscribe();
8524
10222
  session.subscription = void 0;
@@ -8552,9 +10250,341 @@ var StreamsTransportAdapter = class {
8552
10250
  throw sanitizeStreamsRoomError(error, createPayloadProtectionConfigurationError);
8553
10251
  }
8554
10252
  }
10253
+ getForwardingHost() {
10254
+ return this.forwardingBinding?.host;
10255
+ }
10256
+ registerSessionTargetHandler(room, pushMaturedDelta, awaitSynced, isReadyForPush) {
10257
+ const key = forwardingRoomKey(room.kind, room.id);
10258
+ const register = (host) => host.registerTargetHandler(room, {
10259
+ ...isReadyForPush ? { isReadyForPush: () => isReadyForPush() } : {},
10260
+ pushMaturedDelta: () => pushMaturedDelta(),
10261
+ awaitSynced: () => awaitSynced()
10262
+ });
10263
+ const bind = () => {
10264
+ this.roomTargetRegistrars.set(key, register);
10265
+ this.roomTargetUnregisters.get(key)?.();
10266
+ const host = this.getForwardingHost();
10267
+ if (host) this.roomTargetUnregisters.set(key, register(host));
10268
+ };
10269
+ bind();
10270
+ return {
10271
+ unregister: () => {
10272
+ if (this.roomTargetRegistrars.get(key) === register) {
10273
+ this.roomTargetRegistrars.delete(key);
10274
+ this.roomTargetUnregisters.get(key)?.();
10275
+ this.roomTargetUnregisters.delete(key);
10276
+ }
10277
+ },
10278
+ rebind: () => {
10279
+ bind();
10280
+ }
10281
+ };
10282
+ }
10283
+ wrapRemoteCursorStore(store, room, onServerVersion) {
10284
+ return {
10285
+ load: async (streamUrl) => {
10286
+ const cursor = await store.load(streamUrl);
10287
+ if (cursor && cursor.serverLowerBoundVersion !== void 0) {
10288
+ onServerVersion(cursor.serverLowerBoundVersion);
10289
+ this.getForwardingHost()?.reportServerVersion(room, cursor.serverLowerBoundVersion);
10290
+ }
10291
+ return cursor;
10292
+ },
10293
+ save: async (cursor) => {
10294
+ await store.save(cursor);
10295
+ },
10296
+ ...store.delete ? { delete: (streamUrl) => store.delete(streamUrl) } : {}
10297
+ };
10298
+ }
10299
+ async waitForSessionSynced(session) {
10300
+ if (!session || session.closed) return;
10301
+ if (session.subscription) {
10302
+ await session.subscription.waitUntilSynced();
10303
+ return;
10304
+ }
10305
+ if (session.joinPromise) {
10306
+ const sub = await session.joinPromise;
10307
+ if (!session.closed) await sub.waitUntilSynced();
10308
+ }
10309
+ }
10310
+ wrapLoroAdapterWithForwarding(room, doc, awaitSynced) {
10311
+ const inner = createLoroDocAdapter(doc);
10312
+ const localUpdateListeners = /* @__PURE__ */ new Set();
10313
+ let lastKnownServerVersion = {};
10314
+ let emittedVersion = {};
10315
+ const serverConfirmedUpTo = {};
10316
+ const serverConfirmedSparse = /* @__PURE__ */ new Map();
10317
+ let destroyed = false;
10318
+ const foldServerSparse = (peerId) => {
10319
+ let upTo = serverConfirmedUpTo[peerId] ?? 0;
10320
+ const spans = serverConfirmedSparse.get(peerId);
10321
+ if (!spans || spans.length === 0) return;
10322
+ spans.sort((a, b) => a.start - b.start || a.end - b.end);
10323
+ let idx = 0;
10324
+ while (idx < spans.length) {
10325
+ const span = spans[idx];
10326
+ if (span.end <= upTo) {
10327
+ idx += 1;
10328
+ continue;
10329
+ }
10330
+ if (span.start <= upTo) {
10331
+ upTo = Math.max(upTo, span.end);
10332
+ idx += 1;
10333
+ continue;
10334
+ }
10335
+ break;
10336
+ }
10337
+ serverConfirmedUpTo[peerId] = upTo;
10338
+ if (idx > 0) spans.splice(0, idx);
10339
+ if (spans.length === 0) serverConfirmedSparse.delete(peerId);
10340
+ };
10341
+ const confirmServerContiguous = (version) => {
10342
+ for (const [peerId, counter] of Object.entries(version)) if (counter > (serverConfirmedUpTo[peerId] ?? 0)) {
10343
+ serverConfirmedUpTo[peerId] = counter;
10344
+ foldServerSparse(peerId);
10345
+ }
10346
+ };
10347
+ const confirmServerSpan = (peerId, start, end) => {
10348
+ if (end <= start) return;
10349
+ const upTo = serverConfirmedUpTo[peerId] ?? 0;
10350
+ if (start <= upTo) {
10351
+ if (end > upTo) {
10352
+ serverConfirmedUpTo[peerId] = end;
10353
+ foldServerSparse(peerId);
10354
+ }
10355
+ return;
10356
+ }
10357
+ const spans = serverConfirmedSparse.get(peerId) ?? [];
10358
+ spans.push({
10359
+ start,
10360
+ end
10361
+ });
10362
+ serverConfirmedSparse.set(peerId, spans);
10363
+ };
10364
+ const confirmServerBytes = (bytes, isSnapshot) => {
10365
+ if (bytes.byteLength === 0) return;
10366
+ try {
10367
+ if (isSnapshot) {
10368
+ confirmServerContiguous(toLoroVersionRecord(decodeImportBlobMeta(bytes, false).partialEndVersionVector));
10369
+ return;
10370
+ }
10371
+ for (const span of decodeExactLoroSpans(bytes)) confirmServerSpan(span.peer, span.start, span.end);
10372
+ } catch {
10373
+ }
10374
+ };
10375
+ const targetRegistration = this.registerSessionTargetHandler(room, () => {
10376
+ if (destroyed || localUpdateListeners.size === 0) return false;
10377
+ const host = this.getForwardingHost();
10378
+ if (!host) return false;
10379
+ const extraConfirmed = mergeLoroVersionRecords(lastKnownServerVersion, emittedVersion);
10380
+ const delta = host.exportLoroMaturedDelta(room, doc, extraConfirmed);
10381
+ if (!delta || delta.updates.length === 0) return true;
10382
+ emittedVersion = mergeLoroVersionRecords(emittedVersion, delta.version);
10383
+ for (const listener of Array.from(localUpdateListeners)) listener(delta);
10384
+ return true;
10385
+ }, awaitSynced, () => !destroyed && localUpdateListeners.size > 0);
10386
+ return {
10387
+ adapter: {
10388
+ ...inner,
10389
+ applySnapshot: (snapshot) => {
10390
+ const sanitizeSnapshotOutcome = (resolved) => {
10391
+ if (snapshot.byteLength > 0) {
10392
+ confirmServerBytes(snapshot, true);
10393
+ this.getForwardingHost()?.reportServerSnapshotBytes(room, snapshot);
10394
+ }
10395
+ const safeVersion = { ...serverConfirmedUpTo };
10396
+ lastKnownServerVersion = safeVersion;
10397
+ if (resolved && typeof resolved === "object" && "version" in resolved && "complete" in resolved) return {
10398
+ ...resolved,
10399
+ version: safeVersion
10400
+ };
10401
+ return safeVersion;
10402
+ };
10403
+ const host = this.getForwardingHost();
10404
+ const outcome = host ? host.runWithRemoteImport(room, () => inner.applySnapshot(snapshot)) : inner.applySnapshot(snapshot);
10405
+ if (outcome instanceof Promise) return outcome.then((resolved) => sanitizeSnapshotOutcome(resolved));
10406
+ return sanitizeSnapshotOutcome(outcome);
10407
+ },
10408
+ applyRemoteUpdates: (updates, remoterVersion) => {
10409
+ const sanitizeUpdateOutcome = (resolved) => {
10410
+ confirmServerContiguous(toLoroVersionRecord(remoterVersion));
10411
+ const activeHost = this.getForwardingHost();
10412
+ for (const bytes of updates) {
10413
+ confirmServerBytes(bytes, false);
10414
+ activeHost?.reportServerUpdateBytes(room, bytes);
10415
+ }
10416
+ const safeVersion = { ...serverConfirmedUpTo };
10417
+ lastKnownServerVersion = safeVersion;
10418
+ if (resolved && typeof resolved === "object" && "version" in resolved && "complete" in resolved) return {
10419
+ ...resolved,
10420
+ version: safeVersion
10421
+ };
10422
+ return safeVersion;
10423
+ };
10424
+ const host = this.getForwardingHost();
10425
+ const outcome = host ? host.runWithRemoteImport(room, () => inner.applyRemoteUpdates(updates, remoterVersion)) : inner.applyRemoteUpdates(updates, remoterVersion);
10426
+ if (outcome instanceof Promise) return outcome.then((resolved) => sanitizeUpdateOutcome(resolved));
10427
+ return sanitizeUpdateOutcome(outcome);
10428
+ },
10429
+ exportUpdates: (fromVersion) => {
10430
+ const fromRec = toLoroVersionRecord(fromVersion);
10431
+ lastKnownServerVersion = mergeLoroVersionRecords(lastKnownServerVersion, fromRec);
10432
+ emittedVersion = fromRec;
10433
+ const host = this.getForwardingHost();
10434
+ if (host?.hasWithheld(room)) {
10435
+ const exported$1 = host.exportLoroUpdatesWithPolicy(room, doc, fromRec);
10436
+ if (!exported$1 || exported$1.updates.length === 0) return void 0;
10437
+ emittedVersion = mergeLoroVersionRecords(emittedVersion, exported$1.version);
10438
+ return exported$1;
10439
+ }
10440
+ const exported = inner.exportUpdates(fromVersion);
10441
+ if (exported) emittedVersion = mergeLoroVersionRecords(emittedVersion, toLoroVersionRecord(exported.version));
10442
+ return exported;
10443
+ },
10444
+ subscribeLocalUpdates: (listener) => {
10445
+ localUpdateListeners.add(listener);
10446
+ const unsubInner = inner.subscribeLocalUpdates((batch) => {
10447
+ const host = this.getForwardingHost();
10448
+ let effectiveBatch = batch;
10449
+ let expandedApplied = false;
10450
+ const knownFloor = mergeLoroVersionRecords(lastKnownServerVersion, emittedVersion);
10451
+ if (host?.hasWithheld(room)) {
10452
+ const expanded = host.exportLoroLiveUpdatesWithPolicy(room, doc, batch.updates, knownFloor);
10453
+ if (expanded && expanded.updates.length > 0) {
10454
+ effectiveBatch = expanded;
10455
+ expandedApplied = true;
10456
+ }
10457
+ }
10458
+ emittedVersion = expandedApplied ? mergeLoroVersionRecords(emittedVersion, toLoroVersionRecord(effectiveBatch.version)) : mergeLoroVersionRecords(emittedVersion, computeSafeContiguousLoroUpdateVersion(effectiveBatch.updates, knownFloor));
10459
+ listener(effectiveBatch);
10460
+ });
10461
+ return () => {
10462
+ localUpdateListeners.delete(listener);
10463
+ unsubInner();
10464
+ };
10465
+ }
10466
+ },
10467
+ reportCursorVersion: (version) => {
10468
+ confirmServerContiguous(toLoroVersionRecord(version));
10469
+ lastKnownServerVersion = mergeLoroVersionRecords(lastKnownServerVersion, serverConfirmedUpTo);
10470
+ },
10471
+ cleanup: () => {
10472
+ destroyed = true;
10473
+ targetRegistration.unregister();
10474
+ },
10475
+ rebindTarget: () => {
10476
+ if (!destroyed) targetRegistration.rebind();
10477
+ }
10478
+ };
10479
+ }
10480
+ wrapFlockAdapterWithForwarding(room, flock, awaitSynced) {
10481
+ let localSubscribeFloor = {};
10482
+ const base = createFlockAdapter(createScopedFlockForExport(flock, () => localSubscribeFloor));
10483
+ const localUpdateListeners = /* @__PURE__ */ new Set();
10484
+ let lastKnownServerVersion = {};
10485
+ let emittedVersion = {};
10486
+ let destroyed = false;
10487
+ const targetRegistration = this.registerSessionTargetHandler(room, () => {
10488
+ if (destroyed || localUpdateListeners.size === 0) return false;
10489
+ const host = this.getForwardingHost();
10490
+ if (!host) return false;
10491
+ const extraConfirmed = mergeFlockVersions(lastKnownServerVersion, emittedVersion);
10492
+ const delta = host.exportFlockMaturedDelta(room, flock, extraConfirmed);
10493
+ if (!delta || Object.keys(delta.bundle.entries).length === 0) return true;
10494
+ emittedVersion = mergeFlockVersions(emittedVersion, delta.version);
10495
+ localSubscribeFloor = mergeFlockVersions(localSubscribeFloor, delta.version);
10496
+ const batch = {
10497
+ updates: [streamsTextEncoder.encode(JSON.stringify(delta.bundle))],
10498
+ version: delta.version
10499
+ };
10500
+ for (const listener of Array.from(localUpdateListeners)) listener(batch);
10501
+ return true;
10502
+ }, awaitSynced, () => !destroyed && localUpdateListeners.size > 0);
10503
+ return {
10504
+ adapter: {
10505
+ ...base,
10506
+ applySnapshot: async (snapshot) => {
10507
+ const version = await receiveFlockPayloads(flock, [snapshot], () => {
10508
+ const host = this.getForwardingHost();
10509
+ return host ? host.runWithRemoteImport(room, () => base.applySnapshot(snapshot)) : base.applySnapshot(snapshot);
10510
+ });
10511
+ const normalized = normalizeFlockVersion(version);
10512
+ lastKnownServerVersion = mergeFlockVersions(lastKnownServerVersion, normalized);
10513
+ this.getForwardingHost()?.reportServerFlockSnapshotBytes(room, snapshot);
10514
+ return version;
10515
+ },
10516
+ applyRemoteUpdates: async (updates, version) => {
10517
+ const nextVersion = await receiveFlockPayloads(flock, updates, () => {
10518
+ const host = this.getForwardingHost();
10519
+ return host ? host.runWithRemoteImport(room, () => base.applyRemoteUpdates(updates, version)) : base.applyRemoteUpdates(updates, version);
10520
+ });
10521
+ const normalized = normalizeFlockVersion(nextVersion);
10522
+ lastKnownServerVersion = mergeFlockVersions(lastKnownServerVersion, normalized);
10523
+ const activeHost = this.getForwardingHost();
10524
+ if (activeHost) for (const bytes of updates) {
10525
+ if (bytes.byteLength === 0) continue;
10526
+ try {
10527
+ const parsed = JSON.parse(streamsTextDecoder.decode(bytes));
10528
+ if (parsed && typeof parsed === "object" && parsed.entries) activeHost.reportServerFlockBundle(room, parsed);
10529
+ } catch {
10530
+ }
10531
+ }
10532
+ return nextVersion;
10533
+ },
10534
+ exportUpdates: (fromVersion) => {
10535
+ const fromVec = normalizeFlockVersion(fromVersion);
10536
+ lastKnownServerVersion = mergeFlockVersions(lastKnownServerVersion, fromVec);
10537
+ emittedVersion = fromVec;
10538
+ localSubscribeFloor = fromVec;
10539
+ const host = this.getForwardingHost();
10540
+ if (host?.hasWithheld(room)) {
10541
+ const exported$1 = host.exportFlockBundleWithPolicy(room, flock, fromVec);
10542
+ if (!exported$1 || Object.keys(exported$1.bundle.entries).length === 0) return;
10543
+ emittedVersion = mergeFlockVersions(emittedVersion, exported$1.version);
10544
+ localSubscribeFloor = mergeFlockVersions(localSubscribeFloor, exported$1.version);
10545
+ return {
10546
+ updates: [streamsTextEncoder.encode(JSON.stringify(exported$1.bundle))],
10547
+ version: exported$1.version
10548
+ };
10549
+ }
10550
+ const exported = base.exportUpdates(fromVersion);
10551
+ if (exported) {
10552
+ const normalizedExported = normalizeFlockVersion(exported.version);
10553
+ emittedVersion = mergeFlockVersions(emittedVersion, normalizedExported);
10554
+ localSubscribeFloor = mergeFlockVersions(localSubscribeFloor, normalizedExported);
10555
+ }
10556
+ return exported;
10557
+ },
10558
+ subscribeLocalUpdates: (listener) => {
10559
+ localUpdateListeners.add(listener);
10560
+ const unsubInner = base.subscribeLocalUpdates((batch) => {
10561
+ const normalizedBatch = normalizeFlockVersion(batch.version);
10562
+ emittedVersion = mergeFlockVersions(emittedVersion, normalizedBatch);
10563
+ localSubscribeFloor = mergeFlockVersions(localSubscribeFloor, normalizedBatch);
10564
+ listener(batch);
10565
+ });
10566
+ return () => {
10567
+ localUpdateListeners.delete(listener);
10568
+ unsubInner();
10569
+ };
10570
+ }
10571
+ },
10572
+ reportCursorVersion: (version) => {
10573
+ lastKnownServerVersion = mergeFlockVersions(lastKnownServerVersion, normalizeFlockVersion(version));
10574
+ },
10575
+ cleanup: () => {
10576
+ destroyed = true;
10577
+ targetRegistration.unregister();
10578
+ },
10579
+ rebindTarget: () => {
10580
+ if (!destroyed) targetRegistration.rebind();
10581
+ }
10582
+ };
10583
+ }
8555
10584
  async ensureMetaSession(flock, joinAuth) {
8556
10585
  if (this.metaSession && !this.metaSession.closed && this.metaSession.flock === flock) {
8557
10586
  debug("reusing meta session");
10587
+ this.metaSession.rebindTarget?.();
8558
10588
  return this.metaSession;
8559
10589
  }
8560
10590
  const target = resolveStreamsCrdtTarget(this.getStreamAddress(this.options.metaStreamId ?? "repo-meta"));
@@ -8565,17 +10595,23 @@ var StreamsTransportAdapter = class {
8565
10595
  if (!this.cursorStoreFor) await this.remoteCursorStore.delete?.(streamUrl);
8566
10596
  }
8567
10597
  debug("creating meta StreamsCrdt", { streamUrl });
8568
- const adapter = createPersistentFlockAdapter(flock);
10598
+ const metaRoom = {
10599
+ kind: "meta",
10600
+ id: META_ROOM_ID
10601
+ };
10602
+ let session;
10603
+ const wrapped = this.wrapFlockAdapterWithForwarding(metaRoom, flock, () => this.waitForSessionSynced(session));
8569
10604
  const persistMeta = this.persistMeta;
8570
- const session = {
8571
- stream: this.createRoomStream({
10605
+ let stream;
10606
+ try {
10607
+ stream = this.createRoomStream({
8572
10608
  ...target,
8573
- adapter,
10609
+ adapter: wrapped.adapter,
8574
10610
  auth: this.resolveAuth(joinAuth),
8575
- remoteCursorStore: this.cursorStoreFor?.({
10611
+ remoteCursorStore: this.wrapRemoteCursorStore(this.cursorStoreFor?.({
8576
10612
  kind: "meta",
8577
10613
  flock
8578
- }) ?? this.remoteCursorStore,
10614
+ }) ?? this.remoteCursorStore, metaRoom, wrapped.reportCursorVersion),
8579
10615
  createStreamIfMissing: this.options.createStreamIfMissing ?? true,
8580
10616
  snapshotCodec: this.options.snapshotCodec,
8581
10617
  snapshotUpload: this.options.snapshotUpload,
@@ -8586,11 +10622,19 @@ var StreamsTransportAdapter = class {
8586
10622
  beforeRemoteCursorSave: persistMeta ? async () => {
8587
10623
  await persistMeta(flock);
8588
10624
  } : void 0
8589
- }),
10625
+ });
10626
+ } catch (error) {
10627
+ wrapped.cleanup();
10628
+ throw error;
10629
+ }
10630
+ session = {
10631
+ stream,
8590
10632
  flock,
8591
10633
  closed: false,
8592
10634
  refCount: 0,
8593
10635
  activeSyncCount: 0,
10636
+ cleanupForwarding: wrapped.cleanup,
10637
+ rebindTarget: wrapped.rebindTarget,
8594
10638
  statusEmitter: createStatusEmitter("connecting"),
8595
10639
  retirement: createSessionRetirement()
8596
10640
  };
@@ -8601,6 +10645,7 @@ var StreamsTransportAdapter = class {
8601
10645
  const existing = this.docSessions.get(docId);
8602
10646
  if (existing && !existing.closed && existing.doc === doc) {
8603
10647
  debug("reusing doc session", { docId });
10648
+ existing.rebindTarget?.();
8604
10649
  return existing;
8605
10650
  }
8606
10651
  const target = resolveStreamsCrdtTarget(this.getStreamAddress(this.options.docStreamId?.(docId) ?? docId));
@@ -8618,15 +10663,20 @@ var StreamsTransportAdapter = class {
8618
10663
  docId,
8619
10664
  streamUrl
8620
10665
  });
8621
- const adapter = createLoroDocAdapter(doc);
8622
- const persistDoc = this.persistDoc;
10666
+ const docRoom = {
10667
+ kind: "doc",
10668
+ id: docId
10669
+ };
8623
10670
  let session;
8624
- session = {
8625
- stream: this.createRoomStream({
10671
+ const wrapped = this.wrapLoroAdapterWithForwarding(docRoom, doc, () => this.waitForSessionSynced(session));
10672
+ const persistDoc = this.persistDoc;
10673
+ let stream;
10674
+ try {
10675
+ stream = this.createRoomStream({
8626
10676
  ...target,
8627
- adapter,
10677
+ adapter: wrapped.adapter,
8628
10678
  auth: this.resolveAuth(joinAuth),
8629
- remoteCursorStore: this.remoteCursorStore,
10679
+ remoteCursorStore: this.wrapRemoteCursorStore(this.remoteCursorStore, docRoom, wrapped.reportCursorVersion),
8630
10680
  createStreamIfMissing: this.options.createStreamIfMissing ?? true,
8631
10681
  snapshotCodec: this.options.snapshotCodec,
8632
10682
  snapshotUpload: this.options.snapshotUpload,
@@ -8641,12 +10691,20 @@ var StreamsTransportAdapter = class {
8641
10691
  docId
8642
10692
  }),
8643
10693
  beforeRemoteCursorSave: persistDoc ? this.retireOnStaleReplica(() => persistDoc(docId, doc), () => this.retireDocSession(session)) : void 0
8644
- }),
10694
+ });
10695
+ } catch (error) {
10696
+ wrapped.cleanup();
10697
+ throw error;
10698
+ }
10699
+ session = {
10700
+ stream,
8645
10701
  doc,
8646
10702
  docId,
8647
10703
  closed: false,
8648
10704
  refCount: 0,
8649
10705
  activeSyncCount: 0,
10706
+ cleanupForwarding: wrapped.cleanup,
10707
+ rebindTarget: wrapped.rebindTarget,
8650
10708
  statusEmitter: createStatusEmitter("connecting"),
8651
10709
  retirement: createSessionRetirement()
8652
10710
  };
@@ -8657,6 +10715,7 @@ var StreamsTransportAdapter = class {
8657
10715
  const existing = this.flockDocSessions.get(flockDocId);
8658
10716
  if (existing && !existing.closed && existing.flock === flock) {
8659
10717
  debug("reusing flock doc session", { flockDocId });
10718
+ existing.rebindTarget?.();
8660
10719
  return existing;
8661
10720
  }
8662
10721
  const target = resolveStreamsCrdtTarget(this.getFlockDocStreamAddress(flockDocId));
@@ -8674,18 +10733,22 @@ var StreamsTransportAdapter = class {
8674
10733
  flockDocId,
8675
10734
  streamUrl
8676
10735
  });
8677
- const adapter = createPersistentFlockAdapter(flock);
8678
- const persistFlockDoc = this.persistFlockDoc;
10736
+ const flockRoom = {
10737
+ kind: "flock-doc",
10738
+ id: flockDocId
10739
+ };
8679
10740
  let session;
10741
+ const wrapped = this.wrapFlockAdapterWithForwarding(flockRoom, flock, () => this.waitForSessionSynced(session));
10742
+ const persistFlockDoc = this.persistFlockDoc;
8680
10743
  const streamOptions = {
8681
10744
  ...target,
8682
- adapter,
10745
+ adapter: wrapped.adapter,
8683
10746
  auth: this.resolveAuth(joinAuth),
8684
- remoteCursorStore: this.cursorStoreFor?.({
10747
+ remoteCursorStore: this.wrapRemoteCursorStore(this.cursorStoreFor?.({
8685
10748
  kind: "flock",
8686
10749
  flockDocId,
8687
10750
  flock
8688
- }) ?? this.remoteCursorStore,
10751
+ }) ?? this.remoteCursorStore, flockRoom, wrapped.reportCursorVersion),
8689
10752
  createStreamIfMissing: this.options.createStreamIfMissing ?? true,
8690
10753
  streamTtlSeconds: this.resolveFlockDocStreamTtlSeconds(flockDocId),
8691
10754
  snapshotCodec: this.options.snapshotCodec,
@@ -8702,13 +10765,22 @@ var StreamsTransportAdapter = class {
8702
10765
  }),
8703
10766
  beforeRemoteCursorSave: persistFlockDoc ? this.retireOnStaleReplica(() => persistFlockDoc(flockDocId, flock), () => this.retireFlockDocSession(session)) : void 0
8704
10767
  };
10768
+ let stream;
10769
+ try {
10770
+ stream = this.createRoomStream(streamOptions);
10771
+ } catch (error) {
10772
+ wrapped.cleanup();
10773
+ throw error;
10774
+ }
8705
10775
  session = {
8706
- stream: this.createRoomStream(streamOptions),
10776
+ stream,
8707
10777
  flock,
8708
10778
  flockDocId,
8709
10779
  closed: false,
8710
10780
  refCount: 0,
8711
10781
  activeSyncCount: 0,
10782
+ cleanupForwarding: wrapped.cleanup,
10783
+ rebindTarget: wrapped.rebindTarget,
8712
10784
  statusEmitter: createStatusEmitter("connecting"),
8713
10785
  retirement: createSessionRetirement()
8714
10786
  };
@@ -8795,8 +10867,9 @@ export {
8795
10867
  RepoTransportError as R,
8796
10868
  SqliteRepoStore as S,
8797
10869
  RepoSyncError as a,
8798
- StreamsTransportAdapter as b,
10870
+ ResourceBusyError as b,
8799
10871
  createRepoStreamsPersistence as c,
10872
+ StreamsTransportAdapter as d,
8800
10873
  encodeStreamsRoomAdditionalData as e
8801
10874
  };
8802
- //# sourceMappingURL=vendor-loro-repo-B1zdQ8Qd.js.map
10875
+ //# sourceMappingURL=vendor-loro-repo-DbOhEZ39.js.map