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,4 +1,4 @@
1
- import { a2 as gen, a3 as make, o as addFinalizer, d as sync, a4 as provide, a5 as make$1, a6 as make$2, a7 as cached, a8 as run, a9 as exit, aa as close, ab as void_, ac as tap, ad as isFailure, ae as combine, af as andThen, ag as succeed, ah as asVoid, ai as empty, aj as doneUnsafe, v as void_$1, _ as fail, ak as isPromise, q as suspend, al as interrupt, B as tryPromise, am as catchIf, an as add, ao as isSuccess, ap as hasInterruptsOnly, b as flatMap, aq as join, ar as forEach, as as _await, at as isDoneUnsafe, au as interruptible, av as TaggedError, aw as Service, ax as succeed$1, s as succeed$2, ay as uninterruptibleMask, az as onInterrupt, R as fnUntraced, aA as Clock, aB as die, aC as make$3, j as fail$1, aD as make$4, r as raceFirst, aE as sleep$1, aF as mapError, aG as promise, aH as makeUnsafe, aI as timeoutOrElse, c as callback, aJ as all, aK as ensuring, aL as addFinalizer$1, E as orDie, aM as catchCause, p as fail$2, aN as done, aO as failCause, aP as onExit, aQ as acquireUseRelease, C as acquireRelease, aR as await_, aS as annotateCurrentSpan, aT as withSpan, aU as failCause$1, aV as findErrorOption, aW as make$5, aX as setHeaders, aY as bearerToken, aZ as setHeader, a_ as provideService, a$ as TracerDisabledWhen, b0 as Reference, b1 as fromWeb, b2 as HttpClientError, b3 as TransportError } from "./vendor-effect-CNM-5PoN.js";
1
+ import { g as gen, m as make, a as addFinalizer, s as sync, p as provide, b as make$1, c as make$2, d as cached, r as run, e as exit, f as close, v as void_, t as tap, i as isFailure, h as combine, j as andThen, k as succeed, l as asVoid, n as empty, o as doneUnsafe, q as void_$1, u as fail, w as isPromise, x as suspend, y as interrupt, z as tryPromise, A as catchIf, B as add, C as isSuccess, D as hasInterruptsOnly, E as flatMap, F as join, G as forEach, _ as _await, H as isDoneUnsafe, I as interruptible, T as TaggedError, S as Service, J as succeed$1, K as succeed$2, L as uninterruptibleMask, M as onInterrupt, N as fnUntraced, O as Clock, P as die, Q as make$3, R as fail$1, U as make$4, V as promise, W as raceFirst, X as sleep$1, Y as mapError, Z as makeUnsafe, $ as timeoutOrElse, a0 as callback, a1 as all, a2 as ensuring, a3 as addFinalizer$1, a4 as orDie, a5 as catchCause, a6 as fail$2, a7 as done, a8 as failCause, a9 as onExit, aa as acquireUseRelease, ab as acquireRelease, ac as await_, ad as annotateCurrentSpan, ae as withSpan, af as failCause$1, ag as findErrorOption, ah as make$5, ai as setHeaders, aj as bearerToken, ak as setHeader, al as provideService, am as TracerDisabledWhen, an as Reference, ao as fromWeb, ap as HttpClientError, aq as TransportError } from "./vendor-effect-BTVRmkqM.js";
2
2
  const NETWORK_CODES = /* @__PURE__ */ new Set([
3
3
  "ENOTFOUND",
4
4
  "EAI_AGAIN",
@@ -646,6 +646,7 @@ function decodeBase64Bytes(encoded) {
646
646
  throw new Error("base64 decoding is unavailable");
647
647
  }
648
648
  const DS_WS_SUBPROTOCOL = "loro-ds-v1";
649
+ const DS_WS_SUBPROTOCOL_V1_1 = "loro-ds-v1.1";
649
650
  const DS_WS_MAX_FRAME_BYTES = 262144;
650
651
  const DS_WS_MAX_PRODUCER_INT = (1n << 53n) - 1n;
651
652
  const U32_MAX$1 = 4294967295;
@@ -863,6 +864,16 @@ const EXT_IS_CAS = 4;
863
864
  const EXT_CREATE_IF_NOT_FOUND = 8;
864
865
  const EXT_HAS_CUSTOM_CT = 16;
865
866
  const EXT_HAS_STREAM_SEQ = 32;
867
+ const JOIN_HAS_EXT = 8;
868
+ const JOIN_EXT_CREATE_IF_NOT_FOUND = 1;
869
+ const JOIN_EXT_HAS_CONTENT_TYPE = 2;
870
+ const JOIN_EXT_HAS_TTL = 4;
871
+ const JOIN_EXT_HAS_MAX_INLINE_BYTES = 8;
872
+ const JOIN_EXT_HEAD_ONLY = 16;
873
+ const JOIN_OK_EXT_HAS_TAIL_OFFSET = 1;
874
+ const JOIN_OK_EXT_HAS_SNAPSHOT_OFFSET = 2;
875
+ const JOIN_OK_EXT_HAS_SNAPSHOT_BYTES = 4;
876
+ const JOIN_OK_EXT_RESERVED = 248;
866
877
  const CT_OCTET = "application/octet-stream";
867
878
  const CT_JSON = "application/json";
868
879
  const CT_TEXT = "text/plain";
@@ -882,7 +893,7 @@ const META_UVAR_KEYS = /* @__PURE__ */ new Set([
882
893
  4
883
894
  ]);
884
895
  const META_STR_KEYS = /* @__PURE__ */ new Set([5, 6]);
885
- function encodeClientFrame(frame) {
896
+ function encodeClientFrame(frame, v11 = false) {
886
897
  const w = new Writer();
887
898
  switch (frame.type) {
888
899
  case "ping":
@@ -897,13 +908,20 @@ function encodeClientFrame(frame) {
897
908
  break;
898
909
  case "join": {
899
910
  const mode = frame.offsetMode === "numeric" ? 0 : frame.offsetMode === "start" ? 1 : 2;
900
- w.u8(byte0(T_JOIN, mode | (frame.noEcho ? 4 : 0)));
911
+ const ext = v11 ? (frame.createIfNotFound ? JOIN_EXT_CREATE_IF_NOT_FOUND : 0) | (frame.contentType !== void 0 ? JOIN_EXT_HAS_CONTENT_TYPE : 0) | (frame.ttlSeconds !== void 0 ? JOIN_EXT_HAS_TTL : 0) | (frame.maxInlineBytes !== void 0 ? JOIN_EXT_HAS_MAX_INLINE_BYTES : 0) | (frame.headOnly ? JOIN_EXT_HEAD_ONLY : 0) : 0;
912
+ w.u8(byte0(T_JOIN, mode | (frame.noEcho ? 4 : 0) | (ext !== 0 ? JOIN_HAS_EXT : 0)));
901
913
  w.u32(frame.alias);
902
914
  w.str(frame.stream);
903
915
  if (frame.offsetMode === "numeric") {
904
916
  if (frame.offset === void 0) throw new RangeError("numeric JOIN requires offset");
905
917
  w.u64(frame.offset);
906
918
  }
919
+ if (ext !== 0) {
920
+ w.u8(ext);
921
+ if (frame.contentType !== void 0) w.str(frame.contentType);
922
+ if (frame.ttlSeconds !== void 0) w.u64(frame.ttlSeconds);
923
+ if (frame.maxInlineBytes !== void 0) w.u64(frame.maxInlineBytes);
924
+ }
907
925
  break;
908
926
  }
909
927
  case "leave":
@@ -968,7 +986,7 @@ function encodeAppend(w, a) {
968
986
  }
969
987
  w.bytes(a.payload);
970
988
  }
971
- function decodeServerFrame(buf) {
989
+ function decodeServerFrame(buf, v11 = false) {
972
990
  const [ty, flags] = header(buf);
973
991
  const r = new Reader(buf, 1);
974
992
  let frame;
@@ -1004,12 +1022,25 @@ function decodeServerFrame(buf) {
1004
1022
  const fmt = flags >> 1 & 3;
1005
1023
  if (fmt === 2) throw new WsProtocolError("reserved JOIN_OK.CONTENT_FMT");
1006
1024
  const contentType = fmt === 0 ? CT_OCTET : fmt === 1 ? CT_JSON : r.str();
1025
+ let tailOffset;
1026
+ let snapshotOffset;
1027
+ let snapshotBytes;
1028
+ if (v11) {
1029
+ const ext = r.u8();
1030
+ if (ext & JOIN_OK_EXT_RESERVED) throw new WsProtocolError("reserved JOIN_OK ext_flags bit set");
1031
+ if (bit(ext, JOIN_OK_EXT_HAS_TAIL_OFFSET)) tailOffset = r.u64();
1032
+ if (bit(ext, JOIN_OK_EXT_HAS_SNAPSHOT_OFFSET)) snapshotOffset = r.u64();
1033
+ if (bit(ext, JOIN_OK_EXT_HAS_SNAPSHOT_BYTES)) snapshotBytes = r.u64();
1034
+ }
1007
1035
  frame = {
1008
1036
  type: "join_ok",
1009
1037
  alias,
1010
1038
  startOffset,
1011
1039
  streamClosed: bit(flags, 1),
1012
- contentType
1040
+ contentType,
1041
+ ...tailOffset === void 0 ? {} : { tailOffset },
1042
+ ...snapshotOffset === void 0 ? {} : { snapshotOffset },
1043
+ ...snapshotBytes === void 0 ? {} : { snapshotBytes }
1013
1044
  };
1014
1045
  break;
1015
1046
  }
@@ -1223,10 +1254,12 @@ async function probeDsWebSocket(url, options = {}) {
1223
1254
  response.body?.cancel().catch(() => {
1224
1255
  });
1225
1256
  const protocols = (response.headers.get("sec-websocket-protocol") ?? "").split(",").map((p) => p.trim());
1257
+ const protocol = protocols.includes("loro-ds-v1.1") ? DS_WS_SUBPROTOCOL_V1_1 : protocols.includes("loro-ds-v1") ? DS_WS_SUBPROTOCOL : void 0;
1226
1258
  return {
1227
- supported: response.status === 426 && protocols.includes("loro-ds-v1"),
1259
+ supported: response.status === 426 && protocol !== void 0,
1228
1260
  status: response.status,
1229
- retryable: response.status === 429 || response.status >= 500 && response.status !== 501
1261
+ retryable: response.status === 429 || response.status >= 500 && response.status !== 501,
1262
+ ...protocol !== void 0 ? { protocol } : {}
1230
1263
  };
1231
1264
  } catch {
1232
1265
  return {
@@ -1256,16 +1289,67 @@ function acquireDurableWsMultiplexer(options) {
1256
1289
  "unsupported",
1257
1290
  "terminated"
1258
1291
  ].includes(e.mux.state));
1259
- let entry = entries.find((e) => Math.max(e.mux.subscriptionCount, e.refs) < 256);
1292
+ let entry = entries.find((e) => Math.max(e.mux.subscriptionCount, e.leases.size) < 256);
1260
1293
  if (!entry) {
1294
+ const leases = /* @__PURE__ */ new Set();
1261
1295
  entry = {
1262
- mux: new DurableWsMultiplexer(options),
1263
- refs: 0
1296
+ mux: new DurableWsMultiplexer({
1297
+ ...options,
1298
+ onEvent: (event) => {
1299
+ for (const lease of [...leases]) if (lease.onEvent) safeCall(() => lease.onEvent(event));
1300
+ },
1301
+ httpAppend: async (request) => {
1302
+ let lastHttpRequired;
1303
+ for (const lease of [...leases].reverse()) {
1304
+ if (!lease.httpAppend) continue;
1305
+ try {
1306
+ return await lease.httpAppend(request);
1307
+ } catch (error) {
1308
+ if (error instanceof DsWsError && error.code === "http_required") {
1309
+ lastHttpRequired = error;
1310
+ continue;
1311
+ }
1312
+ throw error;
1313
+ }
1314
+ }
1315
+ throw lastHttpRequired ?? new DsWsError("http_required", "APPEND exceeds max_frame_bytes; send it over HTTP", {
1316
+ source: "local",
1317
+ operation: "append",
1318
+ retryable: false
1319
+ }, { notExecuted: true });
1320
+ },
1321
+ httpEphemeralPublish: async (request) => {
1322
+ let lastHttpRequired;
1323
+ for (const lease of [...leases].reverse()) {
1324
+ if (!lease.httpEphemeralPublish) continue;
1325
+ try {
1326
+ return await lease.httpEphemeralPublish(request);
1327
+ } catch (error) {
1328
+ if (error instanceof DsWsError && error.code === "http_required") {
1329
+ lastHttpRequired = error;
1330
+ continue;
1331
+ }
1332
+ throw error;
1333
+ }
1334
+ }
1335
+ throw lastHttpRequired ?? new DsWsError("http_required", "EPH_PUB exceeds max_frame_bytes; send it over HTTP", {
1336
+ source: "local",
1337
+ operation: "eph-pub",
1338
+ retryable: false
1339
+ }, { notExecuted: true });
1340
+ }
1341
+ }),
1342
+ leases
1264
1343
  };
1265
1344
  entries.push(entry);
1266
1345
  }
1346
+ const leaseRecord = {
1347
+ ...options.onEvent !== void 0 ? { onEvent: options.onEvent } : {},
1348
+ ...options.httpAppend !== void 0 ? { httpAppend: options.httpAppend } : {},
1349
+ ...options.httpEphemeralPublish !== void 0 ? { httpEphemeralPublish: options.httpEphemeralPublish } : {}
1350
+ };
1267
1351
  pool.set(key, entries);
1268
- entry.refs += 1;
1352
+ entry.leases.add(leaseRecord);
1269
1353
  const held = entry;
1270
1354
  let released = false;
1271
1355
  return {
@@ -1273,8 +1357,8 @@ function acquireDurableWsMultiplexer(options) {
1273
1357
  release() {
1274
1358
  if (released) return;
1275
1359
  released = true;
1276
- held.refs -= 1;
1277
- if (held.refs <= 0) {
1360
+ held.leases.delete(leaseRecord);
1361
+ if (held.leases.size <= 0) {
1278
1362
  const remaining = (pool.get(key) ?? []).filter((e) => e !== held);
1279
1363
  if (remaining.length) pool.set(key, remaining);
1280
1364
  else pool.delete(key);
@@ -1308,25 +1392,29 @@ var SubBase = class {
1308
1392
  var DurableSub = class extends SubBase {
1309
1393
  initial;
1310
1394
  handlers;
1395
+ options;
1311
1396
  kind = "durable";
1312
1397
  lastCheckpoint;
1313
1398
  startOffset;
1314
1399
  streamClosedSeen = false;
1315
1400
  catchupTimes = [];
1316
- constructor(owner, stream, initial, handlers) {
1401
+ constructor(owner, stream, initial, handlers, options = {}) {
1317
1402
  super(owner, stream);
1318
1403
  this.initial = initial;
1319
1404
  this.handlers = handlers;
1405
+ this.options = options;
1320
1406
  }
1321
1407
  };
1322
1408
  var EphSub = class extends SubBase {
1323
1409
  channel;
1324
1410
  handlers;
1411
+ options;
1325
1412
  kind = "ephemeral";
1326
- constructor(owner, stream, channel, handlers) {
1413
+ constructor(owner, stream, channel, handlers, options = {}) {
1327
1414
  super(owner, stream);
1328
1415
  this.channel = channel;
1329
1416
  this.handlers = handlers;
1417
+ this.options = options;
1330
1418
  }
1331
1419
  };
1332
1420
  function toBytes(data) {
@@ -1418,17 +1506,20 @@ var DurableWsMultiplexer = class {
1418
1506
  await new Promise((resolve) => setTimeout(resolve, this.backoffDelay(this.initialFailures - 1)));
1419
1507
  }
1420
1508
  }
1421
- joinDurable(stream, offset, handlers) {
1509
+ joinDurable(stream, offset, handlers, options = {}) {
1422
1510
  this.assertStream(stream, "join");
1423
1511
  if (typeof offset === "bigint" && (offset < 0n || offset >= 1n << 64n)) throw this.invalid("join", "JOIN offset out of range");
1424
- const sub = new DurableSub(this, stream, offset, handlers);
1512
+ if (options.ttlSeconds !== void 0 && (options.ttlSeconds < 0n || options.ttlSeconds >= 1n << 64n)) throw this.invalid("join", "JOIN ttlSeconds out of range");
1513
+ if (options.maxInlineBytes !== void 0 && (options.maxInlineBytes < 0n || options.maxInlineBytes >= 1n << 64n)) throw this.invalid("join", "JOIN maxInlineBytes out of range");
1514
+ if (options.headOnly === true && options.createIfNotFound === true) throw this.invalid("join", "headOnly and createIfNotFound are mutually exclusive");
1515
+ const sub = new DurableSub(this, stream, offset, handlers, options);
1425
1516
  this.addSub(sub);
1426
1517
  return sub;
1427
1518
  }
1428
- joinEphemeral(stream, channel, handlers) {
1519
+ joinEphemeral(stream, channel, handlers, options = {}) {
1429
1520
  this.assertStream(stream, "eph-join");
1430
1521
  if (channel.length === 0) throw this.invalid("eph-join", "channel must be non-empty");
1431
- const sub = new EphSub(this, stream, channel, handlers);
1522
+ const sub = new EphSub(this, stream, channel, handlers, options);
1432
1523
  this.addSub(sub);
1433
1524
  return sub;
1434
1525
  }
@@ -1649,22 +1740,33 @@ var DurableWsMultiplexer = class {
1649
1740
  alias,
1650
1741
  stream: sub.stream,
1651
1742
  channel: sub.channel,
1652
- noEcho: false
1743
+ noEcho: sub.options.noEcho ?? false
1653
1744
  };
1654
1745
  const at = this.rejoinOffset(sub);
1746
+ const noEcho = sub.options.noEcho ?? false;
1747
+ const allowCreate = sub.options.createIfNotFound === true && sub.startOffset === void 0 && sub.lastCheckpoint === void 0 && (at === "start" || at === "tail" || at === 0n);
1748
+ const ext = {
1749
+ ...allowCreate ? { createIfNotFound: true } : {},
1750
+ ...allowCreate && sub.options.contentType !== void 0 ? { contentType: sub.options.contentType } : {},
1751
+ ...allowCreate && sub.options.ttlSeconds !== void 0 ? { ttlSeconds: sub.options.ttlSeconds } : {},
1752
+ ...sub.options.maxInlineBytes !== void 0 ? { maxInlineBytes: sub.options.maxInlineBytes } : {},
1753
+ ...sub.options.headOnly ? { headOnly: true } : {}
1754
+ };
1655
1755
  if (at === "start") return {
1656
1756
  type: "join",
1657
1757
  alias,
1658
1758
  stream: sub.stream,
1659
1759
  offsetMode: "start",
1660
- noEcho: false
1760
+ noEcho,
1761
+ ...ext
1661
1762
  };
1662
1763
  if (at === "tail") return {
1663
1764
  type: "join",
1664
1765
  alias,
1665
1766
  stream: sub.stream,
1666
1767
  offsetMode: "tail",
1667
- noEcho: false
1768
+ noEcho,
1769
+ ...ext
1668
1770
  };
1669
1771
  return {
1670
1772
  type: "join",
@@ -1672,7 +1774,8 @@ var DurableWsMultiplexer = class {
1672
1774
  stream: sub.stream,
1673
1775
  offsetMode: "numeric",
1674
1776
  offset: at,
1675
- noEcho: false
1777
+ noEcho,
1778
+ ...ext
1676
1779
  };
1677
1780
  }
1678
1781
  rejoinOffset(sub) {
@@ -1682,9 +1785,20 @@ var DurableWsMultiplexer = class {
1682
1785
  }
1683
1786
  sendJoin(conn, sub) {
1684
1787
  if (sub.ended || sub.alias !== void 0) return;
1788
+ if (sub.kind === "durable" && !conn.v11) {
1789
+ const at = this.rejoinOffset(sub);
1790
+ if (sub.options.createIfNotFound === true && sub.startOffset === void 0 && sub.lastCheckpoint === void 0 && (at === "start" || at === "tail" || at === 0n) || sub.options.headOnly === true) {
1791
+ this.fallbackSub(sub, "ws_unavailable");
1792
+ return;
1793
+ }
1794
+ }
1685
1795
  const alias = this.allocAlias(conn);
1686
1796
  const frame = this.joinFrame(alias, sub);
1687
- const size = encodeClientFrame(frame).length;
1797
+ const size = encodeClientFrame(frame, conn.v11).length;
1798
+ if (size > this.maxFrame) {
1799
+ this.fallbackSub(sub, "ws_unavailable");
1800
+ return;
1801
+ }
1688
1802
  if (!conn.authed && size > 16384) {
1689
1803
  conn.deferredJoins.push(sub);
1690
1804
  return;
@@ -1754,7 +1868,7 @@ var DurableWsMultiplexer = class {
1754
1868
  try {
1755
1869
  const headers = authMode === "header" && token !== void 0 ? { Authorization: `Bearer ${token}` } : void 0;
1756
1870
  socket = (this.opts.webSocketFactory ?? defaultWebSocketFactory)(this.wsUrl, {
1757
- protocols: [DS_WS_SUBPROTOCOL],
1871
+ protocols: [DS_WS_SUBPROTOCOL_V1_1, DS_WS_SUBPROTOCOL],
1758
1872
  ...headers ? { headers } : {}
1759
1873
  });
1760
1874
  } catch (error) {
@@ -1772,6 +1886,7 @@ var DurableWsMultiplexer = class {
1772
1886
  socket.binaryType = "arraybuffer";
1773
1887
  const conn = {
1774
1888
  socket,
1889
+ v11: false,
1775
1890
  authed: false,
1776
1891
  lastToken: token,
1777
1892
  aliases: /* @__PURE__ */ new Map(),
@@ -1797,10 +1912,11 @@ var DurableWsMultiplexer = class {
1797
1912
  onOpen(conn, firstFrameToken) {
1798
1913
  if (conn !== this.conn || this.status !== "connecting") return;
1799
1914
  const protocol = conn.socket.protocol;
1800
- if (typeof protocol === "string" && protocol !== "loro-ds-v1") {
1915
+ if (typeof protocol === "string" && protocol !== "loro-ds-v1" && protocol !== "loro-ds-v1.1") {
1801
1916
  this.protocolViolation(conn, "server did not select loro-ds-v1", 1002);
1802
1917
  return;
1803
1918
  }
1919
+ conn.v11 = protocol === DS_WS_SUBPROTOCOL_V1_1;
1804
1920
  this.status = "open";
1805
1921
  this.emit({ type: "open" });
1806
1922
  if (firstFrameToken !== void 0) {
@@ -1852,7 +1968,7 @@ var DurableWsMultiplexer = class {
1852
1968
  }
1853
1969
  let frame;
1854
1970
  try {
1855
- frame = decodeServerFrame(bytes);
1971
+ frame = decodeServerFrame(bytes, conn.v11);
1856
1972
  } catch (error) {
1857
1973
  this.protocolViolation(conn, error instanceof WsProtocolError ? "malformed frame" : "undecodable frame", 1002);
1858
1974
  return;
@@ -2034,10 +2150,10 @@ var DurableWsMultiplexer = class {
2034
2150
  if (sub && sub.alias === alias) sub.alias = void 0;
2035
2151
  }
2036
2152
  if (!sub || sub.ended) return;
2037
- if (sub.kind === "durable") this.enqueue(sub, () => this.durableFrame(sub, frame));
2153
+ if (sub.kind === "durable") this.enqueue(sub, () => this.durableFrame(sub, frame, conn.v11));
2038
2154
  else this.enqueue(sub, () => this.ephFrame(sub, frame));
2039
2155
  }
2040
- async durableFrame(sub, frame) {
2156
+ async durableFrame(sub, frame, v11) {
2041
2157
  const h = sub.handlers;
2042
2158
  switch (frame.type) {
2043
2159
  case "join_ok":
@@ -2046,7 +2162,11 @@ var DurableWsMultiplexer = class {
2046
2162
  await h.onJoined?.({
2047
2163
  startOffset: frame.startOffset,
2048
2164
  contentType: frame.contentType,
2049
- streamClosed: frame.streamClosed
2165
+ streamClosed: frame.streamClosed,
2166
+ ...frame.tailOffset === void 0 ? {} : { tailOffset: frame.tailOffset },
2167
+ ...frame.snapshotOffset === void 0 ? {} : { snapshotOffset: frame.snapshotOffset },
2168
+ ...frame.snapshotBytes === void 0 ? {} : { snapshotBytes: frame.snapshotBytes },
2169
+ v11
2050
2170
  });
2051
2171
  return;
2052
2172
  case "data":
@@ -2067,6 +2187,11 @@ var DurableWsMultiplexer = class {
2067
2187
  await this.catchup(sub, frame.resumeOffset);
2068
2188
  return;
2069
2189
  }
2190
+ if (frame.reason === void 0 && sub.options.headOnly === true) {
2191
+ this.endSub(sub);
2192
+ safeCall(() => h.onEnd?.({ reason: "head_only" }));
2193
+ return;
2194
+ }
2070
2195
  if (frame.reason === void 0 && sub.streamClosedSeen) {
2071
2196
  this.endSub(sub);
2072
2197
  safeCall(() => h.onEnd?.({ reason: "stream_closed" }));
@@ -2082,17 +2207,18 @@ var DurableWsMultiplexer = class {
2082
2207
  }
2083
2208
  }
2084
2209
  async checkpoint(sub, offset, upToDate, streamClosed) {
2085
- sub.lastCheckpoint = offset;
2086
- sub.retries = 0;
2087
- if (streamClosed) sub.streamClosedSeen = true;
2088
2210
  await sub.handlers.onCheckpoint?.({
2089
2211
  offset,
2090
2212
  upToDate,
2091
2213
  streamClosed
2092
2214
  });
2215
+ if (sub.ended || this.status === "closed") return;
2216
+ sub.lastCheckpoint = offset;
2217
+ sub.retries = 0;
2218
+ if (streamClosed) sub.streamClosedSeen = true;
2093
2219
  }
2094
2220
  async catchup(sub, resumeOffsetHint) {
2095
- const from = sub.lastCheckpoint ?? (typeof sub.initial === "bigint" ? sub.initial : sub.initial === "start" ? -1n : resumeOffsetHint ?? sub.startOffset);
2221
+ const from = sub.lastCheckpoint ?? (typeof sub.initial === "bigint" ? sub.initial : sub.initial === "start" ? -1n : sub.startOffset ?? resumeOffsetHint);
2096
2222
  const now = Date.now();
2097
2223
  sub.catchupTimes = sub.catchupTimes.filter((t) => now - t < CATCHUP_WINDOW_MS);
2098
2224
  sub.catchupTimes.push(now);
@@ -2466,12 +2592,16 @@ var DurableWsMultiplexer = class {
2466
2592
  const entry = conn.producerSlots.get(bindProducer.producerId);
2467
2593
  if (entry && entry.slot === bindProducer.slot && entry.generation === bindProducer.generation) entry.confirmed = true;
2468
2594
  }
2469
- settle.resolve({
2470
- transport: "ws",
2595
+ const ackEvent = {
2471
2596
  nextOffset: frame.nextOffset,
2472
2597
  created: frame.created,
2473
2598
  duplicate: frame.duplicate,
2474
2599
  ...frame.prevOffset === void 0 ? {} : { prevOffset: frame.prevOffset }
2600
+ };
2601
+ if (options.onAck) safeCall(() => options.onAck(ackEvent));
2602
+ settle.resolve({
2603
+ transport: "ws",
2604
+ ...ackEvent
2475
2605
  });
2476
2606
  }
2477
2607
  });
@@ -2554,7 +2684,7 @@ var DurableWsMultiplexer = class {
2554
2684
  }
2555
2685
  }
2556
2686
  sendFrame(conn, frame) {
2557
- const bytes = encodeClientFrame(frame);
2687
+ const bytes = encodeClientFrame(frame, conn.v11);
2558
2688
  if (bytes.length > this.maxFrame) throw new RangeError("frame exceeds max_frame_bytes");
2559
2689
  try {
2560
2690
  conn.socket.send(bytes);
@@ -2647,6 +2777,191 @@ const defaultWebSocketFactory = (url, init) => {
2647
2777
  headers: init.headers
2648
2778
  }) : new Ctor(url, [...init.protocols]);
2649
2779
  };
2780
+ const bridgedFunctionAuth = /* @__PURE__ */ new WeakMap();
2781
+ const stringAuthPoolKeys = /* @__PURE__ */ new WeakMap();
2782
+ const authPoolIds = /* @__PURE__ */ new WeakMap();
2783
+ let nextAuthPoolId = 0;
2784
+ const SHA256_K = new Uint32Array([
2785
+ 1116352408,
2786
+ 1899447441,
2787
+ 3049323471,
2788
+ 3921009573,
2789
+ 961987163,
2790
+ 1508970993,
2791
+ 2453635748,
2792
+ 2870763221,
2793
+ 3624381080,
2794
+ 310598401,
2795
+ 607225278,
2796
+ 1426881987,
2797
+ 1925078388,
2798
+ 2162078206,
2799
+ 2614888103,
2800
+ 3248222580,
2801
+ 3835390401,
2802
+ 4022224774,
2803
+ 264347078,
2804
+ 604807628,
2805
+ 770255983,
2806
+ 1249150122,
2807
+ 1555081692,
2808
+ 1996064986,
2809
+ 2554220882,
2810
+ 2821834349,
2811
+ 2952996808,
2812
+ 3210313671,
2813
+ 3336571891,
2814
+ 3584528711,
2815
+ 113926993,
2816
+ 338241895,
2817
+ 666307205,
2818
+ 773529912,
2819
+ 1294757372,
2820
+ 1396182291,
2821
+ 1695183700,
2822
+ 1986661051,
2823
+ 2177026350,
2824
+ 2456956037,
2825
+ 2730485921,
2826
+ 2820302411,
2827
+ 3259730800,
2828
+ 3345764771,
2829
+ 3516065817,
2830
+ 3600352804,
2831
+ 4094571909,
2832
+ 275423344,
2833
+ 430227734,
2834
+ 506948616,
2835
+ 659060556,
2836
+ 883997877,
2837
+ 958139571,
2838
+ 1322822218,
2839
+ 1537002063,
2840
+ 1747873779,
2841
+ 1955562222,
2842
+ 2024104815,
2843
+ 2227730452,
2844
+ 2361852424,
2845
+ 2428436474,
2846
+ 2756734187,
2847
+ 3204031479,
2848
+ 3329325298
2849
+ ]);
2850
+ function rotr32(value, bits) {
2851
+ return value >>> bits | value << 32 - bits;
2852
+ }
2853
+ function sha256Utf8Hex(input) {
2854
+ const bytes = new TextEncoder().encode(input);
2855
+ const totalLen = Math.ceil((bytes.length + 9) / 64) * 64;
2856
+ const padded = new Uint8Array(totalLen);
2857
+ padded.set(bytes);
2858
+ padded[bytes.length] = 128;
2859
+ const view = new DataView(padded.buffer);
2860
+ view.setUint32(totalLen - 8, Math.floor(bytes.length / 536870912), false);
2861
+ view.setUint32(totalLen - 4, bytes.length << 3 >>> 0, false);
2862
+ let h0 = 1779033703;
2863
+ let h1 = 3144134277;
2864
+ let h2 = 1013904242;
2865
+ let h3 = 2773480762;
2866
+ let h4 = 1359893119;
2867
+ let h5 = 2600822924;
2868
+ let h6 = 528734635;
2869
+ let h7 = 1541459225;
2870
+ const w = new Uint32Array(64);
2871
+ for (let offset = 0; offset < totalLen; offset += 64) {
2872
+ for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(offset + i * 4, false);
2873
+ for (let i = 16; i < 64; i += 1) {
2874
+ const w15 = w[i - 15];
2875
+ const w2 = w[i - 2];
2876
+ const s0 = rotr32(w15, 7) ^ rotr32(w15, 18) ^ w15 >>> 3;
2877
+ const s1 = rotr32(w2, 17) ^ rotr32(w2, 19) ^ w2 >>> 10;
2878
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
2879
+ }
2880
+ let a = h0;
2881
+ let b = h1;
2882
+ let c = h2;
2883
+ let d = h3;
2884
+ let e = h4;
2885
+ let f = h5;
2886
+ let g = h6;
2887
+ let h = h7;
2888
+ for (let i = 0; i < 64; i += 1) {
2889
+ const s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);
2890
+ const ch = e & f ^ ~e & g;
2891
+ const temp1 = h + s1 + ch + SHA256_K[i] + w[i] >>> 0;
2892
+ const temp2 = (rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
2893
+ h = g;
2894
+ g = f;
2895
+ f = e;
2896
+ e = d + temp1 >>> 0;
2897
+ d = c;
2898
+ c = b;
2899
+ b = a;
2900
+ a = temp1 + temp2 >>> 0;
2901
+ }
2902
+ h0 = h0 + a >>> 0;
2903
+ h1 = h1 + b >>> 0;
2904
+ h2 = h2 + c >>> 0;
2905
+ h3 = h3 + d >>> 0;
2906
+ h4 = h4 + e >>> 0;
2907
+ h5 = h5 + f >>> 0;
2908
+ h6 = h6 + g >>> 0;
2909
+ h7 = h7 + h >>> 0;
2910
+ }
2911
+ return [
2912
+ h0,
2913
+ h1,
2914
+ h2,
2915
+ h3,
2916
+ h4,
2917
+ h5,
2918
+ h6,
2919
+ h7
2920
+ ].map((word) => (word >>> 0).toString(16).padStart(8, "0")).join("");
2921
+ }
2922
+ function requireToken(token) {
2923
+ const trimmed = token?.trim();
2924
+ if (trimmed == null || trimmed.length === 0) throw new Error("WebSocket transport requires a token");
2925
+ return trimmed;
2926
+ }
2927
+ function wsAuthFromProvider(provider) {
2928
+ if (provider == null) return void 0;
2929
+ if (typeof provider === "string") {
2930
+ const token = requireToken(provider);
2931
+ const bridged2 = () => token;
2932
+ stringAuthPoolKeys.set(bridged2, `token-sha256:${sha256Utf8Hex(token)}`);
2933
+ return bridged2;
2934
+ }
2935
+ let bridged = bridgedFunctionAuth.get(provider);
2936
+ if (bridged == null) {
2937
+ let lastToken;
2938
+ bridged = async ({ reason }) => {
2939
+ const refresh = () => provider({
2940
+ reason: "unauthorized",
2941
+ status: 401,
2942
+ previousToken: lastToken
2943
+ });
2944
+ let token = requireToken(await (reason === "reauth" ? refresh() : provider({ reason: "request" })) ?? void 0);
2945
+ if (reason === "renew" && token === lastToken) token = requireToken(await refresh() ?? void 0);
2946
+ lastToken = token;
2947
+ return token;
2948
+ };
2949
+ bridgedFunctionAuth.set(provider, bridged);
2950
+ }
2951
+ return bridged;
2952
+ }
2953
+ function deriveWsAuthPoolKey(options, auth) {
2954
+ if (options.authPoolKey != null) return `key:${options.authPoolKey}`;
2955
+ if (auth == null) return "anonymous";
2956
+ const tokenKey = stringAuthPoolKeys.get(auth);
2957
+ if (tokenKey != null) return tokenKey;
2958
+ let id = authPoolIds.get(auth);
2959
+ if (id == null) {
2960
+ id = ++nextAuthPoolId;
2961
+ authPoolIds.set(auth, id);
2962
+ }
2963
+ return `auth:${id}`;
2964
+ }
2650
2965
  var IoCancelled = class extends TaggedError("StreamsIoCancelled") {
2651
2966
  };
2652
2967
  var IoOwner = class IoOwner2 {
@@ -3060,7 +3375,7 @@ const makeStreamsHttp = fnUntraced(function* (options = {}) {
3060
3375
  } catch {
3061
3376
  }
3062
3377
  };
3063
- const attempt = fnUntraced(function* (context) {
3378
+ const attempt = fnUntraced(function* (context, rejected) {
3064
3379
  const requestId = diagnostic == null ? void 0 : createDiagnosticId();
3065
3380
  const upload = opts.phase === "upload" && options.uploadTransport != null ? createUploadProgressState(bodyByteLength) : void 0;
3066
3381
  const uploadMode = opts.phase !== "upload" ? void 0 : options.uploadTransport == null ? "total-only" : "progress";
@@ -3113,6 +3428,18 @@ const makeStreamsHttp = fnUntraced(function* (options = {}) {
3113
3428
  timeoutMs: authBudget,
3114
3429
  phase: "auth"
3115
3430
  }, init.signal), init.signal, "auth"), "auth", authBudget, start("auth", authBudget));
3431
+ if (rejected != null && context.reason === "unauthorized") {
3432
+ if (bearer === context.previousToken) return {
3433
+ acquired: rejected,
3434
+ bearer
3435
+ };
3436
+ const lease = rejected.lease;
3437
+ if (lease != null) {
3438
+ const stopped = owner.stopResource(lease);
3439
+ yield* bounded(promise(() => stopped));
3440
+ if (owner.releaseCause.reasons.length > 0) return yield* fail$1(receipt());
3441
+ }
3442
+ }
3116
3443
  const startedAt = start("request", opts.timeoutMs);
3117
3444
  lastProgressAt = startedAt;
3118
3445
  const idleTimeoutMs = opts.uploadIdleTimeoutMs;
@@ -3161,19 +3488,11 @@ const makeStreamsHttp = fnUntraced(function* (options = {}) {
3161
3488
  }
3162
3489
  })();
3163
3490
  const skipForbiddenRefresh = init.method?.toUpperCase() === "POST" && response.headers.has("Producer-Epoch") || isNoAuthRefreshErrorCode(serverErrorCode) || isPutSnapshot;
3164
- if (auth.enabled !== false && (response.status === 401 || response.status === 403 && !skipForbiddenRefresh)) {
3165
- const lease = acquired.lease;
3166
- if (lease != null) {
3167
- const stopped = owner.stopResource(lease);
3168
- yield* bounded(promise(() => stopped));
3169
- if (owner.releaseCause.reasons.length > 0) return yield* fail$1(receipt());
3170
- }
3171
- acquired = (yield* attempt({
3172
- reason: "unauthorized",
3173
- status: response.status,
3174
- previousToken: first.bearer
3175
- })).acquired;
3176
- }
3491
+ if (auth.enabled !== false && (response.status === 401 || response.status === 403 && !skipForbiddenRefresh)) acquired = (yield* attempt({
3492
+ reason: "unauthorized",
3493
+ status: response.status,
3494
+ previousToken: first.bearer
3495
+ }, acquired)).acquired;
3177
3496
  return acquired;
3178
3497
  });
3179
3498
  const makeReaders = fnUntraced(function* (owner, { response, lease }) {
@@ -3822,9 +4141,19 @@ var AuthorizedHttpClient = class {
3822
4141
  bodyByteLength,
3823
4142
  error: context
3824
4143
  });
4144
+ if (refresh != null) await refresh.response.body?.cancel().catch(() => {
4145
+ });
3825
4146
  throw error;
3826
4147
  }
3827
4148
  }
4149
+ if (refresh != null) {
4150
+ if (token === refresh.previousToken) return {
4151
+ response: refresh.response,
4152
+ token
4153
+ };
4154
+ await refresh.response.body?.cancel().catch(() => {
4155
+ });
4156
+ }
3828
4157
  const startedAt = performance.now();
3829
4158
  const progress = createUploadProgressState(bodyByteLength);
3830
4159
  const uploadDetail = () => phase !== "upload" ? {} : {
@@ -3888,11 +4217,10 @@ var AuthorizedHttpClient = class {
3888
4217
  const isNoRefresh = isNoAuthRefreshErrorCode(parseStreamErrorCode(first.response.headers.get("stream-error-code")));
3889
4218
  const shouldRetryAuthFailure = options?.shouldRetryAuthFailure ?? ((response) => response.status === 401 || response.status === 403);
3890
4219
  if (this.authProvider == null || first.response.status === 403 && isNoRefresh || !shouldRetryAuthFailure(first.response)) return first.response;
3891
- await first.response.body?.cancel().catch(() => {
3892
- });
3893
4220
  return (await attempt({
3894
4221
  status: first.response.status,
3895
- previousToken: first.token
4222
+ previousToken: first.token,
4223
+ response: first.response
3896
4224
  })).response;
3897
4225
  }
3898
4226
  async resolveToken(context) {
@@ -4076,6 +4404,9 @@ function toRequestBody(bytes) {
4076
4404
  }
4077
4405
  var StreamsClient = class {
4078
4406
  streamUrl;
4407
+ rawFetch;
4408
+ rawAuth;
4409
+ webSocket;
4079
4410
  http;
4080
4411
  defaultHeaders;
4081
4412
  retryConfig;
@@ -4087,6 +4418,9 @@ var StreamsClient = class {
4087
4418
  this.streamUrl = options.url instanceof URL ? new URL(options.url) : new URL(options.url);
4088
4419
  const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
4089
4420
  if (typeof fetchImpl !== "function") throw new Error("fetch is unavailable; pass options.fetch explicitly");
4421
+ this.rawFetch = fetchImpl;
4422
+ this.rawAuth = options.auth;
4423
+ this.webSocket = options.webSocket;
4090
4424
  this.timeoutConfig = normalizeTimeoutConfig(options.timeout);
4091
4425
  validateUploadPolicy(this.timeoutConfig.uploadTimeoutMs, this.timeoutConfig.uploadIdleTimeoutMs, options.uploadTransport);
4092
4426
  this.http = new AuthorizedHttpClient({
@@ -4247,15 +4581,21 @@ var StreamsClient = class {
4247
4581
  async append(input) {
4248
4582
  validateAppendInput(input);
4249
4583
  const part = input.part == null ? void 0 : normalizeStreamPartLike(input.part);
4584
+ if (this.canAttemptWsAppend(input, part)) {
4585
+ const wsAttempt = await this.tryAppendViaWs(input, part);
4586
+ if (wsAttempt !== "fallback") return wsAttempt;
4587
+ }
4250
4588
  let attempt = 0;
4251
4589
  while (true) try {
4252
4590
  const requestUrl = this.streamEndpoint();
4253
4591
  const response = await this.http.fetchAuthorized(requestUrl, {
4254
4592
  method: "POST",
4255
4593
  headers: this.appendHeaders(input, part?.contentType),
4256
- body: part == null ? void 0 : toRequestBody(part.body)
4594
+ body: part == null ? void 0 : toRequestBody(part.body),
4595
+ signal: input.signal
4257
4596
  }, this.timeoutConfig.uploadTimeoutMs, "upload", {
4258
4597
  operation: "append",
4598
+ onDiagnostic: input.onDiagnostic,
4259
4599
  shouldRetryAuthFailure: (nextResponse) => nextResponse.status === 401 || nextResponse.status === 403 && nextResponse.headers.get("Producer-Epoch") == null
4260
4600
  });
4261
4601
  if (response.status !== 200 && response.status !== 204) return {
@@ -4347,6 +4687,116 @@ var StreamsClient = class {
4347
4687
  producer: input.producer
4348
4688
  });
4349
4689
  }
4690
+ canAttemptWsAppend(input, part) {
4691
+ const wsOptions = this.webSocket;
4692
+ if (wsOptions == null || wsOptions.enabled !== true) return false;
4693
+ if (part == null || part.body.byteLength === 0) return false;
4694
+ if (input.close === true) return false;
4695
+ if (hasAnyHeaders(input.headers)) return false;
4696
+ if (input.includeMeta === true || input.onDiagnostic != null) return false;
4697
+ if (input.signal?.aborted) return false;
4698
+ if (deriveWsStreamId(this.streamUrl, wsOptions.streamId) == null) return false;
4699
+ const targetUrl = wsOptions.url ?? this.streamUrl.toString();
4700
+ try {
4701
+ dsWsEndpoints(targetUrl);
4702
+ } catch {
4703
+ return false;
4704
+ }
4705
+ return true;
4706
+ }
4707
+ async tryAppendViaWs(input, part) {
4708
+ const wsOptions = this.webSocket;
4709
+ const streamId = deriveWsStreamId(this.streamUrl, wsOptions.streamId);
4710
+ const targetUrl = wsOptions.url ?? this.streamUrl.toString();
4711
+ let lease;
4712
+ let mux;
4713
+ try {
4714
+ if (wsOptions.multiplexer != null) mux = wsOptions.multiplexer;
4715
+ else {
4716
+ const wsAuth = wsOptions.auth ?? wsAuthFromProvider(this.rawAuth);
4717
+ lease = acquireDurableWsMultiplexer({
4718
+ url: targetUrl,
4719
+ authPoolKey: deriveWsAuthPoolKey(wsOptions, wsAuth),
4720
+ ...wsAuth != null ? { auth: wsAuth } : {},
4721
+ ...wsOptions.authMode != null ? { authMode: wsOptions.authMode } : {},
4722
+ ...wsOptions.webSocketFactory != null ? { webSocketFactory: wsOptions.webSocketFactory } : {},
4723
+ fetch: this.rawFetch,
4724
+ ...wsOptions.probe != null ? { probe: wsOptions.probe } : {}
4725
+ });
4726
+ mux = lease.multiplexer;
4727
+ }
4728
+ if (mux.state !== "ready") {
4729
+ lease?.release();
4730
+ return "fallback";
4731
+ }
4732
+ } catch {
4733
+ lease?.release();
4734
+ return "fallback";
4735
+ }
4736
+ let cleanupAbort;
4737
+ try {
4738
+ const appendPromise = mux.append(streamId, part.body, {
4739
+ contentType: part.contentType,
4740
+ ...input.producer != null ? { producer: {
4741
+ id: input.producer.producerId,
4742
+ epoch: input.producer.epoch,
4743
+ seq: input.producer.seq
4744
+ } } : {},
4745
+ ...input.streamSeq != null ? { streamSeq: input.streamSeq } : {},
4746
+ writeTimeoutMs: this.timeoutConfig.uploadTimeoutMs
4747
+ });
4748
+ appendPromise.catch(() => {
4749
+ });
4750
+ const result = input.signal == null ? await appendPromise : await Promise.race([appendPromise, new Promise((_, reject) => {
4751
+ const signal = input.signal;
4752
+ const onAbort = () => {
4753
+ reject(recordRequestBoundary(signal.reason ?? new DOMException("Aborted", "AbortError"), {
4754
+ source: "local",
4755
+ abortKind: "caller"
4756
+ }));
4757
+ };
4758
+ if (signal.aborted) {
4759
+ onAbort();
4760
+ return;
4761
+ }
4762
+ signal.addEventListener("abort", onAbort, { once: true });
4763
+ cleanupAbort = () => signal.removeEventListener("abort", onAbort);
4764
+ })]);
4765
+ if (result.transport === "http") {
4766
+ this.knownContentType = part.contentType;
4767
+ return {
4768
+ ok: true,
4769
+ result: result.result
4770
+ };
4771
+ }
4772
+ this.knownContentType = part.contentType;
4773
+ return {
4774
+ ok: true,
4775
+ result: {
4776
+ status: result.duplicate ? 204 : 200,
4777
+ nextOffset: formatWsOffset(result.nextOffset),
4778
+ closed: false,
4779
+ ...input.producer != null ? { producer: {
4780
+ epoch: input.producer.epoch,
4781
+ seq: input.producer.seq
4782
+ } } : {}
4783
+ }
4784
+ };
4785
+ } catch (error) {
4786
+ if (shouldFallbackWsAppendToHttp(error)) return "fallback";
4787
+ if (error instanceof DsWsError) return {
4788
+ ok: false,
4789
+ result: wsErrorToStreamError(error, "append", this.timeoutConfig.uploadTimeoutMs)
4790
+ };
4791
+ return {
4792
+ ok: false,
4793
+ result: thrownToStreamError(error, "append")
4794
+ };
4795
+ } finally {
4796
+ cleanupAbort?.();
4797
+ lease?.release();
4798
+ }
4799
+ }
4350
4800
  /**
4351
4801
  * Read complete messages backward from a message-aligned offset. Each request
4352
4802
  * fetches at most `pageBytes`; a message larger than that is fetched over
@@ -4725,32 +5175,448 @@ var StreamsClient = class {
4725
5175
  }
4726
5176
  live(input) {
4727
5177
  validateLiveInput(input);
4728
- return this.liveInternal({
4729
- offset: input.offset,
4730
- mode: input.mode ?? "auto",
4731
- signal: input.signal
5178
+ const queue = new LiveAsyncQueue();
5179
+ const stopController = new AbortController();
5180
+ const effectiveSignal = mergeAbortSignals(input.signal, stopController.signal);
5181
+ let resolvedReady = false;
5182
+ let resolveReady;
5183
+ let rejectReady;
5184
+ const ready = new Promise((resolve, reject) => {
5185
+ resolveReady = (info) => {
5186
+ if (resolvedReady) return;
5187
+ resolvedReady = true;
5188
+ resolve(info);
5189
+ };
5190
+ rejectReady = (reason) => {
5191
+ if (resolvedReady) return;
5192
+ resolvedReady = true;
5193
+ reject(reason);
5194
+ };
5195
+ });
5196
+ ready.catch(() => {
4732
5197
  });
5198
+ const notifyJoined = (info) => {
5199
+ if (!resolvedReady) {
5200
+ resolveReady(info);
5201
+ try {
5202
+ input.onJoined?.(info);
5203
+ } catch {
5204
+ }
5205
+ }
5206
+ };
5207
+ const failReady = (reason) => {
5208
+ if (!resolvedReady) rejectReady(reason);
5209
+ };
5210
+ const pumpPromise = (async () => {
5211
+ try {
5212
+ await this.runLivePump({
5213
+ offset: input.offset,
5214
+ mode: input.mode ?? "auto",
5215
+ signal: effectiveSignal,
5216
+ webSocket: input.webSocket ?? this.webSocket,
5217
+ autoCreate: normalizeAutoCreate(input.autoCreate),
5218
+ maxInlineBytes: input.maxInlineBytes ?? DEFAULT_WS_MAX_INLINE_BYTES,
5219
+ liveIdleTimeoutMs: input.liveIdleTimeoutMs
5220
+ }, (event) => {
5221
+ queue.push(event);
5222
+ if (event.type === "error") failReady(event.error);
5223
+ }, async (event) => {
5224
+ queue.push(event);
5225
+ if (event.type === "error") failReady(event.error);
5226
+ if (resolvedReady) await queue.waitForPull(effectiveSignal);
5227
+ }, notifyJoined);
5228
+ } catch (error) {
5229
+ failReady(error);
5230
+ } finally {
5231
+ if (!resolvedReady) failReady(effectiveSignal?.aborted ? new DOMException("Aborted", "AbortError") : /* @__PURE__ */ new Error("live subscription ended before joining"));
5232
+ queue.close();
5233
+ }
5234
+ })();
5235
+ return {
5236
+ ready,
5237
+ next: () => queue.next(),
5238
+ return: async (value) => {
5239
+ if (!stopController.signal.aborted) stopController.abort(new DOMException("Aborted", "AbortError"));
5240
+ queue.close();
5241
+ await pumpPromise;
5242
+ return {
5243
+ value,
5244
+ done: true
5245
+ };
5246
+ },
5247
+ throw: async (err) => {
5248
+ if (!stopController.signal.aborted) stopController.abort(err ?? new DOMException("Aborted", "AbortError"));
5249
+ queue.close();
5250
+ await pumpPromise;
5251
+ throw err;
5252
+ },
5253
+ [Symbol.asyncIterator]() {
5254
+ return this;
5255
+ }
5256
+ };
4733
5257
  }
4734
- async *liveInternal(input) {
5258
+ async runLivePump(input, emit, emitPull, notifyJoined) {
4735
5259
  if (input.mode === "long-poll") {
4736
5260
  const state2 = {
4737
5261
  offset: input.offset,
4738
- contentType: this.knownContentType ?? "application/octet-stream"
5262
+ contentType: this.knownContentType ?? input.autoCreate?.contentType ?? "application/octet-stream"
4739
5263
  };
4740
- yield* this.runLongPollLive(state2, input.signal);
5264
+ for await (const ev of this.runLongPollLive(state2, input, notifyJoined)) await emitPull(ev);
4741
5265
  return;
4742
5266
  }
4743
5267
  const state = {
4744
5268
  offset: input.offset,
4745
5269
  contentType: this.knownContentType
4746
5270
  };
4747
- if (await (yield* this.runSseLive(state, input.signal, input.mode === "auto")) === "fallback") yield* this.runLongPollLive(state, input.signal);
5271
+ if (input.mode === "ws" || input.mode === "auto" && input.webSocket?.enabled === true) {
5272
+ if (await this.runWsLive(state, input, input.mode === "auto", emit, notifyJoined) === "done") return;
5273
+ }
5274
+ if (input.mode === "ws") return;
5275
+ if (await (async () => {
5276
+ const gen2 = this.runSseLive(state, input, input.mode === "auto", notifyJoined);
5277
+ for (; ; ) {
5278
+ const next = await gen2.next();
5279
+ if (next.done) return next.value;
5280
+ await emitPull(next.value);
5281
+ }
5282
+ })() === "fallback") {
5283
+ if (state.contentType == null) state.contentType = this.knownContentType ?? input.autoCreate?.contentType ?? "application/octet-stream";
5284
+ for await (const ev of this.runLongPollLive(state, input, notifyJoined)) await emitPull(ev);
5285
+ }
5286
+ }
5287
+ async runWsLive(state, input, allowFallback, emit, notifyJoined) {
5288
+ if (input.signal?.aborted) return "done";
5289
+ const wsOptions = input.webSocket;
5290
+ if (wsOptions == null || wsOptions.enabled !== true) {
5291
+ if (allowFallback) return "fallback";
5292
+ emit({
5293
+ type: "error",
5294
+ mode: "ws",
5295
+ error: {
5296
+ code: "bad_request",
5297
+ status: 400,
5298
+ message: "WebSocket live mode requires webSocket.enabled: true",
5299
+ context: {
5300
+ source: "local",
5301
+ operation: "live-ws",
5302
+ originalCode: "bad_request",
5303
+ retryable: false
5304
+ }
5305
+ }
5306
+ });
5307
+ return "done";
5308
+ }
5309
+ const streamId = deriveWsStreamId(this.streamUrl, wsOptions.streamId);
5310
+ const joinAt = toWsJoinOffset(state.offset);
5311
+ const targetUrl = wsOptions.url ?? this.streamUrl.toString();
5312
+ let validUrl = true;
5313
+ try {
5314
+ dsWsEndpoints(targetUrl);
5315
+ } catch {
5316
+ validUrl = false;
5317
+ }
5318
+ if (!validUrl || streamId == null || joinAt === void 0) {
5319
+ if (allowFallback) return "fallback";
5320
+ emit({
5321
+ type: "error",
5322
+ mode: "ws",
5323
+ error: {
5324
+ code: "bad_request",
5325
+ status: 400,
5326
+ message: "stream URL or offset is incompatible with WebSocket live mode",
5327
+ context: {
5328
+ source: "local",
5329
+ operation: "live-ws",
5330
+ originalCode: "bad_request",
5331
+ retryable: false
5332
+ }
5333
+ }
5334
+ });
5335
+ return "done";
5336
+ }
5337
+ let lease;
5338
+ let mux;
5339
+ try {
5340
+ if (wsOptions.multiplexer != null) mux = wsOptions.multiplexer;
5341
+ else {
5342
+ const wsAuth = wsOptions.auth ?? wsAuthFromProvider(this.rawAuth);
5343
+ lease = acquireDurableWsMultiplexer({
5344
+ url: targetUrl,
5345
+ authPoolKey: deriveWsAuthPoolKey(wsOptions, wsAuth),
5346
+ ...wsAuth != null ? { auth: wsAuth } : {},
5347
+ ...wsOptions.authMode != null ? { authMode: wsOptions.authMode } : {},
5348
+ ...wsOptions.webSocketFactory != null ? { webSocketFactory: wsOptions.webSocketFactory } : {},
5349
+ fetch: this.rawFetch,
5350
+ ...wsOptions.probe != null ? { probe: wsOptions.probe } : {},
5351
+ ...wsOptions.onEvent != null ? { onEvent: wsOptions.onEvent } : {}
5352
+ });
5353
+ mux = lease.multiplexer;
5354
+ }
5355
+ } catch (error) {
5356
+ if (allowFallback) return "fallback";
5357
+ emit({
5358
+ type: "error",
5359
+ mode: "ws",
5360
+ error: thrownToStreamError(error, "live-ws")
5361
+ });
5362
+ return "done";
5363
+ }
5364
+ let sub;
5365
+ let settled = false;
5366
+ let resolveOutcome;
5367
+ const outcomePromise = new Promise((resolve) => {
5368
+ resolveOutcome = (outcome) => {
5369
+ if (settled) return;
5370
+ settled = true;
5371
+ resolve(outcome);
5372
+ };
5373
+ });
5374
+ const idleTimeoutMs = input.liveIdleTimeoutMs;
5375
+ let idleTimer;
5376
+ let joinedOnce = false;
5377
+ let disconnectedSinceJoin = false;
5378
+ let reconnectAttempt = 0;
5379
+ let pendingPayloads = [];
5380
+ let streamClosedEmitted = false;
5381
+ const armIdle = () => {
5382
+ clearTimeout(idleTimer);
5383
+ if (idleTimeoutMs == null || !(idleTimeoutMs > 0) || settled) return;
5384
+ idleTimer = setTimeout(() => {
5385
+ emit({
5386
+ type: "error",
5387
+ mode: "ws",
5388
+ error: thrownToStreamError(new TimeoutError("poll", idleTimeoutMs), "live-ws")
5389
+ });
5390
+ resolveOutcome("done");
5391
+ }, idleTimeoutMs);
5392
+ };
5393
+ const onAbort = () => {
5394
+ resolveOutcome("done");
5395
+ };
5396
+ input.signal?.addEventListener("abort", onAbort, { once: true });
5397
+ try {
5398
+ armIdle();
5399
+ sub = mux.joinDurable(streamId, joinAt, {
5400
+ onJoined: (info) => {
5401
+ if (settled || input.signal?.aborted) return;
5402
+ armIdle();
5403
+ pendingPayloads = [];
5404
+ const nextOffset = formatWsOffset(info.startOffset);
5405
+ state.offset = nextOffset;
5406
+ state.contentType = info.contentType;
5407
+ this.knownContentType = info.contentType;
5408
+ if (disconnectedSinceJoin) {
5409
+ disconnectedSinceJoin = false;
5410
+ emit({
5411
+ type: "reconnected",
5412
+ mode: "ws",
5413
+ attempt: reconnectAttempt
5414
+ });
5415
+ reconnectAttempt = 0;
5416
+ }
5417
+ if (!joinedOnce) {
5418
+ joinedOnce = true;
5419
+ notifyJoined({
5420
+ mode: "ws",
5421
+ nextOffset,
5422
+ contentType: info.contentType,
5423
+ closed: info.streamClosed,
5424
+ ...info.tailOffset === void 0 ? {} : { tailOffset: formatWsOffset(info.tailOffset) }
5425
+ });
5426
+ }
5427
+ },
5428
+ onData: (event) => {
5429
+ if (settled || input.signal?.aborted) return;
5430
+ armIdle();
5431
+ for (const msg of event.messages) pendingPayloads.push(msg);
5432
+ },
5433
+ onCheckpoint: (event) => {
5434
+ if (settled || input.signal?.aborted) return;
5435
+ armIdle();
5436
+ const batchStartOffset = state.offset;
5437
+ const nextOffset = formatWsOffset(event.offset);
5438
+ const contentType = state.contentType ?? input.autoCreate?.contentType ?? "application/octet-stream";
5439
+ state.offset = nextOffset;
5440
+ const batch = pendingPayloads;
5441
+ pendingPayloads = [];
5442
+ for (let i = 0; i < batch.length; i += 1) emit({
5443
+ type: "data",
5444
+ mode: "ws",
5445
+ nextOffset: i + 1 < batch.length ? batchStartOffset : nextOffset,
5446
+ payload: createStreamPart(contentType, batch[i])
5447
+ });
5448
+ if (event.streamClosed) {
5449
+ streamClosedEmitted = true;
5450
+ emit({
5451
+ type: "eof",
5452
+ mode: "ws",
5453
+ nextOffset
5454
+ });
5455
+ resolveOutcome("done");
5456
+ return;
5457
+ }
5458
+ if (event.upToDate) emit({
5459
+ type: "up_to_date",
5460
+ mode: "ws",
5461
+ nextOffset
5462
+ });
5463
+ },
5464
+ catchupViaHttp: async ({ fromOffset }) => {
5465
+ pendingPayloads = [];
5466
+ let cursorOffset = formatWsOffset(fromOffset);
5467
+ for (; ; ) {
5468
+ if (settled || input.signal?.aborted) throw new DOMException("Aborted", "AbortError");
5469
+ const page = await this.readOnceForCatchup(cursorOffset, input.signal);
5470
+ if (page.cursor != null) state.cursor = page.cursor;
5471
+ if (page.payload?.contentType != null) {
5472
+ state.contentType = page.payload.contentType;
5473
+ this.knownContentType = page.payload.contentType;
5474
+ }
5475
+ if (!joinedOnce) {
5476
+ joinedOnce = true;
5477
+ notifyJoined({
5478
+ mode: "ws",
5479
+ nextOffset: page.nextOffset,
5480
+ contentType: page.payload?.contentType ?? state.contentType ?? input.autoCreate?.contentType ?? "application/octet-stream",
5481
+ closed: page.closed
5482
+ });
5483
+ }
5484
+ if (page.payload != null && page.payload.body.byteLength > 0) {
5485
+ const boundary = extractBoundary(page.payload.contentType);
5486
+ const parts = boundary != null ? decodeMultipartMixed(boundary, page.payload.body).map((part) => createStreamPart(part.contentType, part.body)) : expandLiveHttpPart(page.payload);
5487
+ for (let i = 0; i < parts.length; i += 1) emit({
5488
+ type: "data",
5489
+ mode: "ws",
5490
+ nextOffset: i + 1 < parts.length ? cursorOffset : page.nextOffset,
5491
+ cursor: state.cursor,
5492
+ payload: parts[i]
5493
+ });
5494
+ }
5495
+ cursorOffset = page.nextOffset;
5496
+ state.offset = page.nextOffset;
5497
+ if (page.closed) {
5498
+ streamClosedEmitted = true;
5499
+ emit({
5500
+ type: "eof",
5501
+ mode: "ws",
5502
+ nextOffset: page.nextOffset
5503
+ });
5504
+ resolveOutcome("done");
5505
+ return parseWsOffset(page.nextOffset);
5506
+ }
5507
+ if (page.upToDate) return parseWsOffset(page.nextOffset);
5508
+ }
5509
+ },
5510
+ onDisconnect: () => {
5511
+ pendingPayloads = [];
5512
+ if (settled || input.signal?.aborted) return;
5513
+ if (joinedOnce) {
5514
+ disconnectedSinceJoin = true;
5515
+ reconnectAttempt += 1;
5516
+ emit({
5517
+ type: "reconnecting",
5518
+ mode: "ws",
5519
+ attempt: reconnectAttempt,
5520
+ delayMs: 0,
5521
+ error: {
5522
+ code: "network_error",
5523
+ message: "WebSocket disconnected",
5524
+ cause: null,
5525
+ context: {
5526
+ source: "fetch",
5527
+ operation: "live-ws",
5528
+ originalCode: "network_error",
5529
+ retryable: true
5530
+ }
5531
+ }
5532
+ });
5533
+ }
5534
+ },
5535
+ onFallback: (event) => {
5536
+ if (settled || input.signal?.aborted) return;
5537
+ if (event.resumeFrom !== void 0) state.offset = formatWsOffset(event.resumeFrom);
5538
+ if (allowFallback && canFallbackWsReasonToHttp(event.reason)) {
5539
+ resolveOutcome("fallback");
5540
+ return;
5541
+ }
5542
+ emit({
5543
+ type: "error",
5544
+ mode: "ws",
5545
+ error: wsFallbackToStreamError(event.reason)
5546
+ });
5547
+ resolveOutcome("done");
5548
+ },
5549
+ onEnd: () => {
5550
+ if (settled || input.signal?.aborted) return;
5551
+ if (!streamClosedEmitted) {
5552
+ streamClosedEmitted = true;
5553
+ emit({
5554
+ type: "eof",
5555
+ mode: "ws",
5556
+ nextOffset: state.offset
5557
+ });
5558
+ }
5559
+ resolveOutcome("done");
5560
+ },
5561
+ onError: (error) => {
5562
+ if (settled || input.signal?.aborted) return;
5563
+ emit({
5564
+ type: "error",
5565
+ mode: "ws",
5566
+ error: wsErrorToStreamError(error)
5567
+ });
5568
+ resolveOutcome("done");
5569
+ }
5570
+ }, {
5571
+ maxInlineBytes: BigInt(input.maxInlineBytes),
5572
+ ...input.autoCreate != null ? {
5573
+ createIfNotFound: true,
5574
+ ...input.autoCreate.contentType !== void 0 ? { contentType: input.autoCreate.contentType } : this.knownContentType !== void 0 ? { contentType: this.knownContentType } : {},
5575
+ ...input.autoCreate.ttlSeconds !== void 0 ? { ttlSeconds: BigInt(input.autoCreate.ttlSeconds) } : {}
5576
+ } : {}
5577
+ });
5578
+ return await outcomePromise;
5579
+ } finally {
5580
+ clearTimeout(idleTimer);
5581
+ input.signal?.removeEventListener("abort", onAbort);
5582
+ if (sub != null) sub.leave().catch(() => {
5583
+ });
5584
+ lease?.release();
5585
+ }
5586
+ }
5587
+ async readOnceForCatchup(offset, signal) {
5588
+ let attempt = 0;
5589
+ for (; ; ) {
5590
+ const result = await this.readOnce({
5591
+ offset,
5592
+ signal
5593
+ });
5594
+ if (result.ok) return result.result;
5595
+ const status = result.result.status;
5596
+ if (!(isRetryableLiveError(result.result) || typeof status === "number" && LIVE_RETRYABLE_STATUSES.has(status)) || attempt >= this.retryConfig.maxAttempts) throw result.result;
5597
+ const delayMs = computeRetryDelay(attempt, this.retryConfig);
5598
+ attempt += 1;
5599
+ await sleep(delayMs, signal);
5600
+ }
5601
+ }
5602
+ async ensureStreamCreatedForAutoCreate(autoCreate) {
5603
+ const created = await this.create({
5604
+ ...autoCreate.contentType !== void 0 ? { contentType: autoCreate.contentType } : {},
5605
+ ...autoCreate.ttlSeconds !== void 0 ? { ttlSeconds: autoCreate.ttlSeconds } : {}
5606
+ });
5607
+ if (created.ok) return {
5608
+ ok: true,
5609
+ result: created.result.contentType
5610
+ };
5611
+ if (created.result.code === "conflict") return await this.ensureKnownContentType();
5612
+ return created;
4748
5613
  }
4749
- async *runSseLive(state, signal, allowFallback) {
5614
+ async *runSseLive(state, input, allowFallback, notifyJoined) {
5615
+ const signal = input.signal;
4750
5616
  let attempt = 0;
4751
5617
  let reconnectAttempt = 0;
4752
5618
  let connectedOnce = false;
4753
- const idleTimeoutMs = this.sseIdleTimeoutMs();
5619
+ const idleTimeoutMs = input.liveIdleTimeoutMs ?? this.sseIdleTimeoutMs();
4754
5620
  while (true) {
4755
5621
  if (signal?.aborted) return "done";
4756
5622
  const idle = new AbortController();
@@ -4758,6 +5624,7 @@ var StreamsClient = class {
4758
5624
  let idleTimer;
4759
5625
  const armIdle = () => {
4760
5626
  clearTimeout(idleTimer);
5627
+ if (!(idleTimeoutMs > 0)) return;
4761
5628
  idleTimer = setTimeout(() => {
4762
5629
  idleFired = true;
4763
5630
  idle.abort(new TimeoutError("poll", idleTimeoutMs));
@@ -4767,8 +5634,12 @@ var StreamsClient = class {
4767
5634
  try {
4768
5635
  if (state.contentType == null) {
4769
5636
  const contentTypeResult = await this.ensureKnownContentType();
4770
- if (!contentTypeResult.ok) throw new LiveStreamFailure(contentTypeResult.result);
4771
- state.contentType = contentTypeResult.result;
5637
+ if (!contentTypeResult.ok) if (input.autoCreate != null && contentTypeResult.result.code === "not_found" && contentTypeResult.result.context?.serverErrorCode == null) {
5638
+ const created = await this.ensureStreamCreatedForAutoCreate(input.autoCreate);
5639
+ if (!created.ok) throw new LiveStreamFailure(created.result);
5640
+ state.contentType = created.result;
5641
+ } else throw new LiveStreamFailure(contentTypeResult.result);
5642
+ else state.contentType = contentTypeResult.result;
4772
5643
  }
4773
5644
  const response = await this.http.fetchAuthorized(this.readEndpoint({
4774
5645
  offset: state.offset,
@@ -4778,6 +5649,21 @@ var StreamsClient = class {
4778
5649
  method: "GET",
4779
5650
  signal: connectionSignal
4780
5651
  }, this.timeoutConfig.connectTimeoutMs, "connect", { coversBody: false });
5652
+ if (response.status === 404 && input.autoCreate != null) {
5653
+ const error = await responseToStreamErrorWithin(response, "live sse", this.timeoutConfig.connectTimeoutMs);
5654
+ if (error.context?.serverErrorCode == null) {
5655
+ const created = await this.ensureStreamCreatedForAutoCreate(input.autoCreate);
5656
+ if (!created.ok) throw new LiveStreamFailure(created.result);
5657
+ state.contentType = created.result;
5658
+ continue;
5659
+ }
5660
+ yield {
5661
+ type: "error",
5662
+ mode: "sse",
5663
+ error
5664
+ };
5665
+ return "done";
5666
+ }
4781
5667
  if (response.status === 400) {
4782
5668
  const errorText = await readTextWithin(response, this.timeoutConfig.connectTimeoutMs);
4783
5669
  if (allowFallback && !connectedOnce && isSseUnsupportedErrorText(errorText)) return "fallback";
@@ -4819,6 +5705,12 @@ var StreamsClient = class {
4819
5705
  }
4820
5706
  if (event.event !== "control") continue;
4821
5707
  const control = parseSseControlData(event.data);
5708
+ if (!sawControlEvent) notifyJoined({
5709
+ mode: "sse",
5710
+ nextOffset: control.nextOffset,
5711
+ contentType: state.contentType ?? "application/octet-stream",
5712
+ closed: control.streamClosed
5713
+ });
4822
5714
  if (!sawControlEvent && reconnectAttempt > 0) yield {
4823
5715
  type: "reconnected",
4824
5716
  mode: "sse",
@@ -4828,16 +5720,20 @@ var StreamsClient = class {
4828
5720
  attempt = 0;
4829
5721
  reconnectAttempt = 0;
4830
5722
  }
5723
+ const batchStartOffset = !sawControlEvent && state.offset === "now" ? response.headers.get("Stream-Content-Offset") ?? state.offset : state.offset;
4831
5724
  sawControlEvent = true;
4832
5725
  state.offset = control.nextOffset;
4833
5726
  const effectiveCursor = control.streamCursor ?? state.cursor;
4834
5727
  state.cursor = effectiveCursor;
4835
- for (const payload of pendingPayloads) yield {
5728
+ const sseContentType = state.contentType ?? "application/octet-stream";
5729
+ const parts = [];
5730
+ for (const payload of pendingPayloads) for (const part of expandLiveHttpPart(createStreamPart(sseContentType, payload))) parts.push(part);
5731
+ for (let i = 0; i < parts.length; i += 1) yield {
4836
5732
  type: "data",
4837
5733
  mode: "sse",
4838
- nextOffset: control.nextOffset,
5734
+ nextOffset: i + 1 < parts.length ? batchStartOffset : control.nextOffset,
4839
5735
  cursor: effectiveCursor,
4840
- payload: createStreamPart(state.contentType ?? "application/octet-stream", payload)
5736
+ payload: parts[i]
4841
5737
  };
4842
5738
  pendingPayloads = [];
4843
5739
  if (control.streamClosed) {
@@ -4904,7 +5800,8 @@ var StreamsClient = class {
4904
5800
  }
4905
5801
  }
4906
5802
  }
4907
- async *runLongPollLive(state, signal) {
5803
+ async *runLongPollLive(state, input, notifyJoined) {
5804
+ const signal = input.signal;
4908
5805
  let attempt = 0;
4909
5806
  let reconnectAttempt = 0;
4910
5807
  while (true) {
@@ -4918,11 +5815,32 @@ var StreamsClient = class {
4918
5815
  method: "GET",
4919
5816
  signal
4920
5817
  }, this.longPollDeadlineMs(), "poll");
5818
+ if (response.status === 404 && input.autoCreate != null) {
5819
+ const error = await responseToStreamErrorWithin(response, "live long-poll", this.timeoutConfig.connectTimeoutMs, "live-long-poll");
5820
+ if (error.context?.serverErrorCode == null) {
5821
+ const created = await this.ensureStreamCreatedForAutoCreate(input.autoCreate);
5822
+ if (!created.ok) throw new LiveStreamFailure(created.result);
5823
+ state.contentType = created.result;
5824
+ continue;
5825
+ }
5826
+ yield {
5827
+ type: "error",
5828
+ mode: "long-poll",
5829
+ error
5830
+ };
5831
+ return;
5832
+ }
4921
5833
  if (response.status === 204) {
4922
5834
  const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "live long-poll");
4923
5835
  if (!hasTrueHeader(response.headers, "Stream-Up-To-Date")) throw new ProtocolError("long-poll 204 response missing Stream-Up-To-Date: true");
4924
5836
  const closed = hasTrueHeader(response.headers, "Stream-Closed");
4925
5837
  const effectiveCursor = response.headers.get("Stream-Cursor") ?? void 0 ?? state.cursor;
5838
+ notifyJoined({
5839
+ mode: "long-poll",
5840
+ nextOffset,
5841
+ contentType: response.headers.get("Content-Type") ?? state.contentType ?? "application/octet-stream",
5842
+ closed
5843
+ });
4926
5844
  if (reconnectAttempt > 0) yield {
4927
5845
  type: "reconnected",
4928
5846
  mode: "long-poll",
@@ -4965,16 +5883,25 @@ var StreamsClient = class {
4965
5883
  };
4966
5884
  attempt = 0;
4967
5885
  reconnectAttempt = 0;
5886
+ const batchStartOffset = state.offset === "now" ? response.headers.get("Stream-Content-Offset") ?? state.offset : state.offset;
4968
5887
  const output = await this.parseReadOutput(response, state.offset, "live long-poll");
4969
5888
  const outputCursor = output.cursor ?? state.cursor;
4970
5889
  state.offset = output.nextOffset;
4971
5890
  state.cursor = outputCursor;
4972
- yield {
4973
- type: "data",
5891
+ state.contentType = output.payload.contentType;
5892
+ notifyJoined({
4974
5893
  mode: "long-poll",
4975
5894
  nextOffset: output.nextOffset,
5895
+ contentType: output.payload.contentType,
5896
+ closed: output.closed
5897
+ });
5898
+ const parts = expandLiveHttpPart(output.payload);
5899
+ for (let i = 0; i < parts.length; i += 1) yield {
5900
+ type: "data",
5901
+ mode: "long-poll",
5902
+ nextOffset: i + 1 < parts.length ? batchStartOffset : output.nextOffset,
4976
5903
  cursor: outputCursor,
4977
- payload: output.payload
5904
+ payload: parts[i]
4978
5905
  };
4979
5906
  if (output.closed) {
4980
5907
  yield {
@@ -5156,6 +6083,60 @@ var StreamsClient = class {
5156
6083
  }
5157
6084
  };
5158
6085
  const MIN_SSE_IDLE_TIMEOUT_MS = 45e3;
6086
+ const isJsonWs = (b) => b === 32 || b === 9 || b === 10 || b === 13;
6087
+ function splitJsonArrayBytes(bytes) {
6088
+ let start = 0;
6089
+ let end = bytes.length;
6090
+ while (start < end && isJsonWs(bytes[start])) start += 1;
6091
+ while (end > start && isJsonWs(bytes[end - 1])) end -= 1;
6092
+ if (start >= end || bytes[start] !== 91 || bytes[end - 1] !== 93) return;
6093
+ let pos = start + 1;
6094
+ const limit = end - 1;
6095
+ while (pos < limit && isJsonWs(bytes[pos])) pos += 1;
6096
+ if (pos >= limit) return [];
6097
+ const items = [];
6098
+ let elemStart = pos;
6099
+ let depth = 0;
6100
+ let inString = false;
6101
+ let escaped = false;
6102
+ while (pos < limit) {
6103
+ const b = bytes[pos];
6104
+ if (inString) {
6105
+ if (escaped) escaped = false;
6106
+ else if (b === 92) escaped = true;
6107
+ else if (b === 34) inString = false;
6108
+ } else if (b === 34) inString = true;
6109
+ else if (b === 123 || b === 91) depth += 1;
6110
+ else if (b === 125 || b === 93) {
6111
+ if (depth === 0) return void 0;
6112
+ depth -= 1;
6113
+ } else if (b === 44 && depth === 0) {
6114
+ let elemEnd2 = pos;
6115
+ while (elemEnd2 > elemStart && isJsonWs(bytes[elemEnd2 - 1])) elemEnd2 -= 1;
6116
+ if (elemEnd2 <= elemStart) return void 0;
6117
+ items.push(bytes.slice(elemStart, elemEnd2));
6118
+ pos += 1;
6119
+ while (pos < limit && isJsonWs(bytes[pos])) pos += 1;
6120
+ if (pos >= limit) return void 0;
6121
+ elemStart = pos;
6122
+ continue;
6123
+ }
6124
+ pos += 1;
6125
+ }
6126
+ if (inString || depth !== 0) return void 0;
6127
+ let elemEnd = limit;
6128
+ while (elemEnd > elemStart && isJsonWs(bytes[elemEnd - 1])) elemEnd -= 1;
6129
+ if (elemEnd <= elemStart) return void 0;
6130
+ items.push(bytes.slice(elemStart, elemEnd));
6131
+ return items;
6132
+ }
6133
+ function expandLiveHttpPart(part) {
6134
+ if (part.body.byteLength === 0) return [];
6135
+ if (part.contentType.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return [part];
6136
+ const items = splitJsonArrayBytes(part.body);
6137
+ if (items === void 0) return [part];
6138
+ return items.map((item) => createStreamPart(part.contentType, item));
6139
+ }
5159
6140
  const LIVE_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
5160
6141
  429,
5161
6142
  502,
@@ -5250,6 +6231,12 @@ function validateOpenSseSessionInput(input) {
5250
6231
  }
5251
6232
  function validateLiveInput(input) {
5252
6233
  assertNonEmptyString(input.offset, "offset");
6234
+ if (typeof input.autoCreate === "object" && input.autoCreate != null) {
6235
+ if (input.autoCreate.ttlSeconds != null) assertNonNegativeSafeInteger(input.autoCreate.ttlSeconds, "autoCreate.ttlSeconds");
6236
+ if (input.autoCreate.contentType != null) normalizeContentType(input.autoCreate.contentType);
6237
+ }
6238
+ if (input.maxInlineBytes != null) assertNonNegativeSafeInteger(input.maxInlineBytes, "maxInlineBytes");
6239
+ if (input.liveIdleTimeoutMs != null) assertNonNegativeSafeInteger(input.liveIdleTimeoutMs, "liveIdleTimeoutMs");
5253
6240
  }
5254
6241
  function assertNonEmptyString(value, name) {
5255
6242
  if (value.trim().length === 0) throw new Error(`${name} must be a non-empty string`);
@@ -5323,32 +6310,286 @@ function mergeAbortSignals(...signals) {
5323
6310
  }
5324
6311
  return controller.signal;
5325
6312
  }
6313
+ const DEFAULT_WS_MAX_INLINE_BYTES = 65536;
6314
+ function normalizeAutoCreate(autoCreate) {
6315
+ if (autoCreate === true) return {};
6316
+ if (autoCreate == null || autoCreate === false) return void 0;
6317
+ return autoCreate;
6318
+ }
6319
+ function toWsJoinOffset(offset) {
6320
+ if (offset === "-1") return "start";
6321
+ if (offset === "now") return "tail";
6322
+ try {
6323
+ return parseWsOffset(offset);
6324
+ } catch {
6325
+ return;
6326
+ }
6327
+ }
6328
+ function deriveWsStreamId(streamUrl, override) {
6329
+ if (override != null) return isValidWsStreamFullId(override) ? override : void 0;
6330
+ if (streamUrl.protocol !== "https:" && streamUrl.protocol !== "http:") return void 0;
6331
+ const match = /^\/ds\/([^/]+)\/([^/]+)$/u.exec(streamUrl.pathname);
6332
+ if (match == null) return void 0;
6333
+ try {
6334
+ const id = `${decodeURIComponent(match[1])}/${decodeURIComponent(match[2])}`;
6335
+ return isValidWsStreamFullId(id) ? id : void 0;
6336
+ } catch {
6337
+ return;
6338
+ }
6339
+ }
6340
+ function canFallbackWsReasonToHttp(reason) {
6341
+ return reason === "ws_unavailable" || reason === "unsupported_content_type" || reason === "catchup_required" || reason === "catchup_loop";
6342
+ }
6343
+ function wsFallbackToStreamError(reason) {
6344
+ return {
6345
+ code: reason === "unsupported_content_type" ? "protocol_error" : "network_error",
6346
+ message: `WebSocket live read ended with fallback reason: ${reason}`,
6347
+ ...reason === "unsupported_content_type" ? {} : { cause: null },
6348
+ context: {
6349
+ source: "fetch",
6350
+ operation: "live-ws",
6351
+ originalCode: reason === "unsupported_content_type" ? "protocol_error" : "network_error",
6352
+ retryable: false
6353
+ }
6354
+ };
6355
+ }
6356
+ function hasAnyHeaders(headers) {
6357
+ if (headers == null) return false;
6358
+ let found = false;
6359
+ new Headers(headers).forEach(() => {
6360
+ found = true;
6361
+ });
6362
+ return found;
6363
+ }
6364
+ function shouldFallbackWsAppendToHttp(error) {
6365
+ if (!(error instanceof DsWsError)) return false;
6366
+ if (error.code === "http_required" || error.notExecuted === true) return true;
6367
+ if (error.code === "request_failed") {
6368
+ if (error.status === 401) return true;
6369
+ if (error.status === 403 && error.serverErrorCode == null && error.producerCurrentEpoch == null) return true;
6370
+ }
6371
+ return false;
6372
+ }
6373
+ function wsConflictDetail(error) {
6374
+ if (error.casCurrentNextOffset != null) return {
6375
+ kind: "cas_mismatch",
6376
+ currentOffset: formatWsOffset(error.casCurrentNextOffset)
6377
+ };
6378
+ if (error.producerExpectedSeq != null) {
6379
+ const expectedSeq = Number(error.producerExpectedSeq);
6380
+ if (Number.isSafeInteger(expectedSeq)) return {
6381
+ kind: "producer_seq_gap",
6382
+ expectedSeq
6383
+ };
6384
+ }
6385
+ const normalized = (error.serverMessage ?? "").toLowerCase();
6386
+ if (normalized.includes("closed")) return { kind: "stream_closed" };
6387
+ if (normalized.includes("content type") || normalized.includes("content-type")) return { kind: "content_type_mismatch" };
6388
+ if (normalized.includes("stream-seq") || normalized.includes("sequence")) return { kind: "stream_seq_conflict" };
6389
+ return { kind: "other" };
6390
+ }
6391
+ function wsErrorToStreamError(error, operation = "live-ws", timeoutMs) {
6392
+ if (error.code === "catchup_failed") {
6393
+ const cause = error.cause;
6394
+ if (typeof cause === "object" && cause != null && "code" in cause && "message" in cause) return cause;
6395
+ }
6396
+ if (error.code === "outcome_unknown") {
6397
+ if (error.message.includes("timed out")) return {
6398
+ code: "timeout",
6399
+ phase: "upload",
6400
+ message: error.message,
6401
+ context: {
6402
+ source: "unknown",
6403
+ operation,
6404
+ originalCode: "timeout",
6405
+ retryable: error.retryable,
6406
+ phase: "upload",
6407
+ timeoutKind: "total",
6408
+ ...timeoutMs != null ? { timeoutMs } : {}
6409
+ }
6410
+ };
6411
+ return {
6412
+ code: "network_error",
6413
+ message: error.message,
6414
+ cause: error,
6415
+ context: {
6416
+ source: "unknown",
6417
+ operation,
6418
+ originalCode: "network_error",
6419
+ retryable: error.retryable
6420
+ }
6421
+ };
6422
+ }
6423
+ if (error.code === "connection_failed" && error.status == null) return {
6424
+ code: "network_error",
6425
+ message: error.message,
6426
+ cause: error,
6427
+ context: {
6428
+ source: "unknown",
6429
+ operation,
6430
+ originalCode: "network_error",
6431
+ retryable: error.retryable
6432
+ }
6433
+ };
6434
+ const status = error.status;
6435
+ const serverErrorCode = error.serverErrorCode;
6436
+ const retryable = error.retryable;
6437
+ const originalCode = status === 400 ? "bad_request" : status === 401 ? "unauthorized" : status === 403 ? "forbidden" : status === 404 ? "not_found" : status === 409 ? "conflict" : status === 410 ? "gone" : status === 429 ? "rate_limited" : "unknown";
6438
+ const context = {
6439
+ source: status != null ? "http" : "unknown",
6440
+ operation,
6441
+ originalCode,
6442
+ retryable,
6443
+ ...status != null ? { status } : {},
6444
+ ...serverErrorCode != null ? { serverErrorCode } : {},
6445
+ ...error.context.requestId != null ? { requestId: error.context.requestId } : {}
6446
+ };
6447
+ switch (originalCode) {
6448
+ case "bad_request":
6449
+ return {
6450
+ code: "bad_request",
6451
+ status: 400,
6452
+ message: error.message,
6453
+ context
6454
+ };
6455
+ case "unauthorized":
6456
+ return {
6457
+ code: "unauthorized",
6458
+ status: 401,
6459
+ message: error.message,
6460
+ context
6461
+ };
6462
+ case "forbidden":
6463
+ return {
6464
+ code: "forbidden",
6465
+ status: 403,
6466
+ message: error.message,
6467
+ ...error.producerCurrentEpoch != null ? { detail: {
6468
+ kind: "stale_producer_epoch",
6469
+ serverEpoch: Number(error.producerCurrentEpoch)
6470
+ } } : {},
6471
+ context
6472
+ };
6473
+ case "not_found":
6474
+ return {
6475
+ code: "not_found",
6476
+ status: 404,
6477
+ message: error.message,
6478
+ context
6479
+ };
6480
+ case "conflict":
6481
+ return {
6482
+ code: "conflict",
6483
+ status: 409,
6484
+ message: error.message,
6485
+ detail: wsConflictDetail(error),
6486
+ context
6487
+ };
6488
+ case "gone":
6489
+ return {
6490
+ code: "gone",
6491
+ status: 410,
6492
+ message: error.message,
6493
+ context
6494
+ };
6495
+ case "rate_limited":
6496
+ return {
6497
+ code: "rate_limited",
6498
+ status: 429,
6499
+ ...error.retryAfterMs !== void 0 ? { retryAfterMs: error.retryAfterMs } : {},
6500
+ message: error.message,
6501
+ context
6502
+ };
6503
+ default:
6504
+ return {
6505
+ code: "unknown",
6506
+ ...status != null ? { status } : {},
6507
+ message: error.message,
6508
+ cause: error,
6509
+ context
6510
+ };
6511
+ }
6512
+ }
6513
+ var LiveAsyncQueue = class {
6514
+ items = [];
6515
+ waiters = [];
6516
+ pullWaiters = [];
6517
+ closed = false;
6518
+ push(item) {
6519
+ if (this.closed) return;
6520
+ const waiter = this.waiters.shift();
6521
+ if (waiter != null) waiter({
6522
+ value: item,
6523
+ done: false
6524
+ });
6525
+ else this.items.push(item);
6526
+ }
6527
+ waitForPull(signal) {
6528
+ if (this.closed || signal?.aborted) return Promise.resolve();
6529
+ return new Promise((resolve) => {
6530
+ const done2 = () => {
6531
+ signal?.removeEventListener("abort", done2);
6532
+ resolve();
6533
+ };
6534
+ this.pullWaiters.push(done2);
6535
+ signal?.addEventListener("abort", done2, { once: true });
6536
+ });
6537
+ }
6538
+ flushPullWaiters() {
6539
+ while (this.pullWaiters.length > 0) this.pullWaiters.shift()();
6540
+ }
6541
+ close() {
6542
+ if (this.closed) return;
6543
+ this.closed = true;
6544
+ while (this.waiters.length > 0) this.waiters.shift()({
6545
+ value: void 0,
6546
+ done: true
6547
+ });
6548
+ this.flushPullWaiters();
6549
+ }
6550
+ next() {
6551
+ if (this.items.length > 0) return Promise.resolve({
6552
+ value: this.items.shift(),
6553
+ done: false
6554
+ });
6555
+ if (this.closed) return Promise.resolve({
6556
+ value: void 0,
6557
+ done: true
6558
+ });
6559
+ this.flushPullWaiters();
6560
+ return new Promise((resolve) => {
6561
+ this.waiters.push(resolve);
6562
+ });
6563
+ }
6564
+ };
5326
6565
  export {
5327
6566
  DsWsError as D,
5328
6567
  IoOwner as I,
5329
6568
  StreamsClient as S,
5330
6569
  acquireDurableWsMultiplexer as a,
5331
- DEFAULT_TIMEOUT_CONFIG as b,
5332
- createDiagnosticId as c,
5333
- decodeSsePayload as d,
5334
- StreamsAuth as e,
6570
+ decodeSsePayload as b,
6571
+ DEFAULT_TIMEOUT_CONFIG as c,
6572
+ deriveWsAuthPoolKey as d,
6573
+ createDiagnosticId as e,
5335
6574
  formatWsOffset as f,
5336
- parseSseControlData as g,
5337
- StreamsHttpFailure as h,
6575
+ StreamsAuth as g,
6576
+ parseSseControlData as h,
5338
6577
  isValidWsStreamFullId as i,
5339
- StreamsHttpClosed as j,
5340
- StreamsHttpReleaseFailure as k,
5341
- isSseUnsupportedErrorText as l,
6578
+ withSafeSpan as j,
6579
+ StreamsHttpFailure as k,
6580
+ StreamsHttpClosed as l,
5342
6581
  makeStreamsHttp as m,
5343
6582
  networkErrorCode as n,
5344
6583
  ownedTask as o,
5345
6584
  parseWsOffset as p,
5346
- extractBoundary as q,
6585
+ StreamsHttpReleaseFailure as q,
5347
6586
  readSseEvents as r,
5348
6587
  safeRequestId as s,
5349
6588
  thrownToStreamError as t,
5350
- decodeMultipartMixed as u,
5351
- parseStreamErrorCode as v,
5352
- withSafeSpan as w
6589
+ isSseUnsupportedErrorText as u,
6590
+ extractBoundary as v,
6591
+ wsAuthFromProvider as w,
6592
+ decodeMultipartMixed as x,
6593
+ parseStreamErrorCode as y
5353
6594
  };
5354
- //# sourceMappingURL=vendor-@loro-dev-streams-client-DPTfaXHE.js.map
6595
+ //# sourceMappingURL=vendor-@loro-dev-streams-client-DkeRiNAY.js.map