@powerhousedao/ph-clint-app 0.1.0-dev.90 → 0.1.0-dev.91

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 (525) hide show
  1. package/dist/browser/connect-ayTpkZ7D.js.map +1 -1
  2. package/dist/browser/document-models/index.js +1 -1
  3. package/dist/browser/document-models/ph-clint-project/index.js +2 -2
  4. package/dist/browser/{editor-Bp2wUo8R.js → editor-BmNIZjpu.js} +3 -3
  5. package/dist/browser/{editor-Bp2wUo8R.js.map → editor-BmNIZjpu.js.map} +1 -1
  6. package/dist/browser/editors/ph-clint-project-editor/module.js +1 -1
  7. package/dist/browser/factory-6X-atFO0.js.map +1 -1
  8. package/dist/browser/index.js +6 -2
  9. package/dist/browser/index.js.map +1 -1
  10. package/dist/browser/{module-B16ZT36n.js → module-BzVWlfCE.js} +19 -7
  11. package/dist/browser/module-BzVWlfCE.js.map +1 -0
  12. package/dist/browser/{ph-clint-project-CHq59BKL.js → ph-clint-project-1Xn2yUDQ.js} +3 -15
  13. package/dist/browser/ph-clint-project-1Xn2yUDQ.js.map +1 -0
  14. package/dist/browser/subgraphs/index.js +8 -0
  15. package/dist/browser/subgraphs/index.js.map +1 -0
  16. package/dist/browser/switchboard-DyNO-2Mk.js.map +1 -1
  17. package/dist/connect/__react__/chunks/chunk-DV4czemZ.js +1 -0
  18. package/dist/connect/__react__/chunks/{react-DInDUHsR.js → react-6__-7Yi6.js} +1 -1
  19. package/dist/connect/__react__/chunks/{react-dom-QyonbUot.js → react-dom-D8SQgl6v.js} +1 -1
  20. package/dist/connect/__react__/chunks/{react-dom-server-legacy.browser.production-KSpBOUM7.js → react-dom-server-legacy.browser.production-tEo0fxOJ.js} +2 -2
  21. package/dist/connect/__react__/chunks/{react-dom-server.browser.production-NeoI_ldE.js → react-dom-server.browser.production-CWSDDfJ2.js} +2 -2
  22. package/dist/connect/__react__/chunks/{react-dom-server.edge.production-Djx8cQAo.js → react-dom-server.edge.production-K2OjKVH3.js} +2 -2
  23. package/dist/connect/__react__/chunks/{scheduler-CxGS3ZcN.js → scheduler-C_FnfDtC.js} +1 -1
  24. package/dist/connect/__react__/chunks/server.browser-Bu7JkTx-.js +1 -0
  25. package/dist/connect/__react__/chunks/static.browser-C6ypYl2H.js +1 -0
  26. package/dist/connect/__react__/react/compiler-runtime.js +1 -1
  27. package/dist/connect/__react__/react/jsx-dev-runtime.js +1 -1
  28. package/dist/connect/__react__/react/jsx-runtime.js +1 -1
  29. package/dist/connect/__react__/react-dom/client.js +1 -1
  30. package/dist/connect/__react__/react-dom/profiling.js +1 -1
  31. package/dist/connect/__react__/react-dom/server.browser.js +1 -1
  32. package/dist/connect/__react__/react-dom/server.edge.js +1 -1
  33. package/dist/connect/__react__/react-dom/server.js +1 -1
  34. package/dist/connect/__react__/react-dom/static.browser.js +1 -1
  35. package/dist/connect/__react__/react-dom/static.edge.js +1 -1
  36. package/dist/connect/__react__/react-dom/static.js +1 -1
  37. package/dist/connect/__react__/react-dom/test-utils.js +1 -1
  38. package/dist/connect/__react__/react-dom.js +1 -1
  39. package/dist/connect/__react__/react.js +1 -1
  40. package/dist/connect/assets/{ClearStorageModal-CXoNWmRe-D3ifKRm-.js → ClearStorageModal-CXoNWmRe-CpE72nB8.js} +2 -2
  41. package/dist/connect/assets/{ClearStorageModal-CXoNWmRe-D3ifKRm-.js.map → ClearStorageModal-CXoNWmRe-CpE72nB8.js.map} +1 -1
  42. package/dist/connect/assets/{DebugSettingsModal-5SDhy5gt-DLMPdDQB.js → DebugSettingsModal-5SDhy5gt-Me3H9oNw.js} +2 -2
  43. package/dist/connect/assets/{DebugSettingsModal-5SDhy5gt-DLMPdDQB.js.map → DebugSettingsModal-5SDhy5gt-Me3H9oNw.js.map} +1 -1
  44. package/dist/connect/assets/{InspectorModal-BsSihzuc-B0n5gbGB.js → InspectorModal-BsSihzuc-DVTFZSUH.js} +2 -2
  45. package/dist/connect/assets/{InspectorModal-BsSihzuc-B0n5gbGB.js.map → InspectorModal-BsSihzuc-DVTFZSUH.js.map} +1 -1
  46. package/dist/connect/assets/{SettingsModal-S_A5qf95-uzigz0nk.js → SettingsModal-S_A5qf95-nzYOCl3o.js} +2 -2
  47. package/dist/connect/assets/{SettingsModal-S_A5qf95-uzigz0nk.js.map → SettingsModal-S_A5qf95-nzYOCl3o.js.map} +1 -1
  48. package/dist/connect/assets/{components-ByEUkO4U-xPZUVkzr.js → components-ByEUkO4U-DoBYY0k7.js} +4 -4
  49. package/dist/connect/assets/{components-ByEUkO4U-xPZUVkzr.js.map → components-ByEUkO4U-DoBYY0k7.js.map} +1 -1
  50. package/dist/connect/assets/connect-DGfzdELb.js.map +1 -1
  51. package/dist/connect/assets/{connect.config-Bt4pvvWV-Dj3FkjaZ.js → connect.config-Bt4pvvWV-DPiXrGYV.js} +2 -2
  52. package/dist/connect/assets/{connect.config-Bt4pvvWV-Dj3FkjaZ.js.map → connect.config-Bt4pvvWV-DPiXrGYV.js.map} +1 -1
  53. package/dist/connect/assets/editor-Bds50MuL.js +2 -0
  54. package/dist/connect/assets/{editor-BaQ62r3i.js.map → editor-Bds50MuL.js.map} +1 -1
  55. package/dist/connect/assets/hooks-CE3gZpe3.js +2 -0
  56. package/dist/connect/assets/hooks-CE3gZpe3.js.map +1 -0
  57. package/dist/connect/assets/{ph-clint-project-p1zY6e17.js → index-CK9tPzCS.js} +4 -3
  58. package/dist/connect/assets/index-CK9tPzCS.js.map +1 -0
  59. package/dist/connect/assets/index-Skfhz8KO.css +2 -0
  60. package/dist/connect/assets/{load-BWibkoFV-CDRjWwYQ.js → load-BWibkoFV-DWy1LALw.js} +2 -2
  61. package/dist/connect/assets/{load-BWibkoFV-CDRjWwYQ.js.map → load-BWibkoFV-DWy1LALw.js.map} +1 -1
  62. package/dist/connect/assets/{module-7zCQE1MC.js → module-5NdQh7xr.js} +2 -2
  63. package/dist/connect/assets/{module-7zCQE1MC.js.map → module-5NdQh7xr.js.map} +1 -1
  64. package/dist/connect/assets/{pglite-seed-BWk7yOwr-b2F0oJiP.js → pglite-seed-BWk7yOwr-BHQsaOhO.js} +2 -2
  65. package/dist/connect/assets/{pglite-seed-BWk7yOwr-b2F0oJiP.js.map → pglite-seed-BWk7yOwr-BHQsaOhO.js.map} +1 -1
  66. package/dist/connect/assets/{reactor-BxNvHOKC-CeMF1M2u.js → reactor-BxNvHOKC-CSy_kfH0.js} +2 -2
  67. package/dist/connect/assets/{reactor-BxNvHOKC-CeMF1M2u.js.map → reactor-BxNvHOKC-CSy_kfH0.js.map} +1 -1
  68. package/dist/connect/assets/{registerServiceWorker-D9l1kja7-DG3DqQna.js → registerServiceWorker-D9l1kja7-C-5yx671.js} +2 -2
  69. package/dist/connect/assets/{registerServiceWorker-D9l1kja7-DG3DqQna.js.map → registerServiceWorker-D9l1kja7-C-5yx671.js.map} +1 -1
  70. package/dist/connect/assets/switchboard-CPQzDmSh.js.map +1 -1
  71. package/dist/connect/index.html +6 -9
  72. package/dist/connect/powerhouse.config.json +3 -2
  73. package/dist/node/connect-CIR7GJmj.mjs.map +1 -1
  74. package/dist/node/document-models/index.mjs +1 -1
  75. package/dist/node/document-models/ph-clint-project/index.mjs +2 -2
  76. package/dist/node/{editor-BC9t7D3T.mjs → editor-8cCevQVX.mjs} +3 -3
  77. package/dist/node/{editor-BC9t7D3T.mjs.map → editor-8cCevQVX.mjs.map} +1 -1
  78. package/dist/node/editors/ph-clint-project-editor/module.mjs +1 -1
  79. package/dist/node/factory-BV9KTFaw.mjs.map +1 -1
  80. package/dist/node/index.mjs +6 -2
  81. package/dist/node/index.mjs.map +1 -1
  82. package/dist/node/{module-BPw40Ypp.mjs → module-CJId0WUE.mjs} +19 -7
  83. package/dist/node/module-CJId0WUE.mjs.map +1 -0
  84. package/dist/node/{ph-clint-project-B5IjiXbp.mjs → ph-clint-project-CqqaE1LT.mjs} +3 -15
  85. package/dist/node/ph-clint-project-CqqaE1LT.mjs.map +1 -0
  86. package/dist/node/subgraphs/index.mjs +8 -0
  87. package/dist/node/subgraphs/index.mjs.map +1 -0
  88. package/dist/node/switchboard-kqcv15ax.mjs.map +1 -1
  89. package/dist/powerhouse.manifest.json +26 -26
  90. package/dist/style.css +198 -178
  91. package/dist/tsconfig.tsbuildinfo +1 -1
  92. package/dist/types/document-models/document-models.d.ts +30 -15
  93. package/dist/types/document-models/document-models.d.ts.map +1 -1
  94. package/dist/types/document-models/index.d.ts +1 -1
  95. package/dist/types/document-models/ph-clint-project/gen/schema/types.d.ts.map +1 -0
  96. package/dist/types/document-models/ph-clint-project/gen/schema/zod.d.ts.map +1 -0
  97. package/dist/types/document-models/ph-clint-project/index.d.ts +2 -2
  98. package/dist/types/document-models/ph-clint-project/upgrades/index.d.ts +2 -2
  99. package/dist/types/document-models/ph-clint-project/upgrades/upgrade-manifest.d.ts +2 -2
  100. package/dist/types/document-models/ph-clint-project/upgrades/upgrade-manifest.d.ts.map +1 -1
  101. package/dist/types/document-models/ph-clint-project/v1/actions.d.ts +30 -15
  102. package/dist/types/document-models/ph-clint-project/v1/actions.d.ts.map +1 -1
  103. package/dist/types/document-models/ph-clint-project/v1/gen/actions.d.ts +29 -19
  104. package/dist/types/document-models/ph-clint-project/v1/gen/actions.d.ts.map +1 -1
  105. package/dist/types/document-models/ph-clint-project/v1/gen/controller.d.ts +2 -2
  106. package/dist/types/document-models/ph-clint-project/v1/gen/controller.d.ts.map +1 -1
  107. package/dist/types/document-models/ph-clint-project/v1/gen/creators.d.ts +28 -18
  108. package/dist/types/document-models/ph-clint-project/v1/gen/creators.d.ts.map +1 -1
  109. package/dist/types/document-models/ph-clint-project/v1/gen/deployment/actions.d.ts +10 -6
  110. package/dist/types/document-models/ph-clint-project/v1/gen/deployment/actions.d.ts.map +1 -1
  111. package/dist/types/document-models/ph-clint-project/v1/gen/deployment/creators.d.ts +3 -2
  112. package/dist/types/document-models/ph-clint-project/v1/gen/deployment/creators.d.ts.map +1 -1
  113. package/dist/types/document-models/ph-clint-project/v1/gen/deployment/error.d.ts +1 -1
  114. package/dist/types/document-models/ph-clint-project/v1/gen/deployment/operations.d.ts +4 -3
  115. package/dist/types/document-models/ph-clint-project/v1/gen/deployment/operations.d.ts.map +1 -1
  116. package/dist/types/document-models/ph-clint-project/v1/gen/document-model.d.ts +1 -1
  117. package/dist/types/document-models/ph-clint-project/v1/gen/document-model.d.ts.map +1 -1
  118. package/dist/types/document-models/ph-clint-project/v1/gen/document-schema.d.ts +2 -2
  119. package/dist/types/document-models/ph-clint-project/v1/gen/document-schema.d.ts.map +1 -1
  120. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/actions.d.ts +6 -6
  121. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/actions.d.ts.map +1 -1
  122. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/creators.d.ts +2 -2
  123. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/creators.d.ts.map +1 -1
  124. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/error.d.ts +1 -1
  125. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/error.d.ts.map +1 -1
  126. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/operations.d.ts +3 -3
  127. package/dist/types/document-models/ph-clint-project/v1/gen/external-skills/operations.d.ts.map +1 -1
  128. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/actions.d.ts +6 -54
  129. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/actions.d.ts.map +1 -1
  130. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/creators.d.ts +2 -14
  131. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/creators.d.ts.map +1 -1
  132. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/error.d.ts +1 -78
  133. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/error.d.ts.map +1 -1
  134. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/operations.d.ts +3 -15
  135. package/dist/types/document-models/ph-clint-project/v1/gen/features-mastra/operations.d.ts.map +1 -1
  136. package/dist/types/document-models/ph-clint-project/v1/gen/features-powerhouse/actions.d.ts +3 -3
  137. package/dist/types/document-models/ph-clint-project/v1/gen/features-powerhouse/creators.d.ts +2 -2
  138. package/dist/types/document-models/ph-clint-project/v1/gen/features-powerhouse/creators.d.ts.map +1 -1
  139. package/dist/types/document-models/ph-clint-project/v1/gen/features-powerhouse/error.d.ts +1 -1
  140. package/dist/types/document-models/ph-clint-project/v1/gen/features-powerhouse/operations.d.ts +3 -3
  141. package/dist/types/document-models/ph-clint-project/v1/gen/features-powerhouse/operations.d.ts.map +1 -1
  142. package/dist/types/document-models/ph-clint-project/v1/gen/features-routine/actions.d.ts +4 -4
  143. package/dist/types/document-models/ph-clint-project/v1/gen/features-routine/actions.d.ts.map +1 -1
  144. package/dist/types/document-models/ph-clint-project/v1/gen/features-routine/creators.d.ts +2 -2
  145. package/dist/types/document-models/ph-clint-project/v1/gen/features-routine/creators.d.ts.map +1 -1
  146. package/dist/types/document-models/ph-clint-project/v1/gen/features-routine/operations.d.ts +3 -3
  147. package/dist/types/document-models/ph-clint-project/v1/gen/features-routine/operations.d.ts.map +1 -1
  148. package/dist/types/document-models/ph-clint-project/v1/gen/identity/actions.d.ts +5 -5
  149. package/dist/types/document-models/ph-clint-project/v1/gen/identity/actions.d.ts.map +1 -1
  150. package/dist/types/document-models/ph-clint-project/v1/gen/identity/creators.d.ts +2 -2
  151. package/dist/types/document-models/ph-clint-project/v1/gen/identity/creators.d.ts.map +1 -1
  152. package/dist/types/document-models/ph-clint-project/v1/gen/identity/error.d.ts +1 -1
  153. package/dist/types/document-models/ph-clint-project/v1/gen/identity/error.d.ts.map +1 -1
  154. package/dist/types/document-models/ph-clint-project/v1/gen/identity/operations.d.ts +3 -3
  155. package/dist/types/document-models/ph-clint-project/v1/gen/identity/operations.d.ts.map +1 -1
  156. package/dist/types/document-models/ph-clint-project/v1/gen/index.d.ts +25 -20
  157. package/dist/types/document-models/ph-clint-project/v1/gen/index.d.ts.map +1 -1
  158. package/dist/types/document-models/ph-clint-project/v1/gen/lifecycle/actions.d.ts +3 -3
  159. package/dist/types/document-models/ph-clint-project/v1/gen/lifecycle/creators.d.ts +2 -2
  160. package/dist/types/document-models/ph-clint-project/v1/gen/lifecycle/creators.d.ts.map +1 -1
  161. package/dist/types/document-models/ph-clint-project/v1/gen/lifecycle/operations.d.ts +3 -3
  162. package/dist/types/document-models/ph-clint-project/v1/gen/lifecycle/operations.d.ts.map +1 -1
  163. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/actions.d.ts.map +1 -0
  164. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/creators.d.ts.map +1 -0
  165. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/error.d.ts.map +1 -0
  166. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/operations.d.ts.map +1 -0
  167. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-main-agent/actions.d.ts.map +1 -0
  168. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-main-agent/creators.d.ts.map +1 -0
  169. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-main-agent/error.d.ts.map +1 -0
  170. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-main-agent/operations.d.ts.map +1 -0
  171. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-models/actions.d.ts.map +1 -0
  172. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-models/creators.d.ts.map +1 -0
  173. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-models/error.d.ts.map +1 -0
  174. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-models/operations.d.ts.map +1 -0
  175. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-profiles/actions.d.ts.map +1 -0
  176. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-profiles/creators.d.ts.map +1 -0
  177. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-profiles/error.d.ts.map +1 -0
  178. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-profiles/operations.d.ts.map +1 -0
  179. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-sub-agents/actions.d.ts.map +1 -0
  180. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-sub-agents/creators.d.ts.map +1 -0
  181. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-sub-agents/error.d.ts.map +1 -0
  182. package/dist/types/document-models/ph-clint-project/v1/gen/mastra-sub-agents/operations.d.ts.map +1 -0
  183. package/dist/types/document-models/ph-clint-project/v1/gen/ph-factories.d.ts +2 -2
  184. package/dist/types/document-models/ph-clint-project/v1/gen/ph-factories.d.ts.map +1 -1
  185. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/actions.d.ts +7 -7
  186. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/actions.d.ts.map +1 -1
  187. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/creators.d.ts +2 -2
  188. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/creators.d.ts.map +1 -1
  189. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/error.d.ts +1 -1
  190. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/error.d.ts.map +1 -1
  191. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/operations.d.ts +3 -3
  192. package/dist/types/document-models/ph-clint-project/v1/gen/powerhouse-packages/operations.d.ts.map +1 -1
  193. package/dist/types/document-models/ph-clint-project/v1/gen/publishing/actions.d.ts +7 -7
  194. package/dist/types/document-models/ph-clint-project/v1/gen/publishing/actions.d.ts.map +1 -1
  195. package/dist/types/document-models/ph-clint-project/v1/gen/publishing/creators.d.ts +2 -2
  196. package/dist/types/document-models/ph-clint-project/v1/gen/publishing/creators.d.ts.map +1 -1
  197. package/dist/types/document-models/ph-clint-project/v1/gen/publishing/error.d.ts +1 -1
  198. package/dist/types/document-models/ph-clint-project/v1/gen/publishing/operations.d.ts +3 -3
  199. package/dist/types/document-models/ph-clint-project/v1/gen/publishing/operations.d.ts.map +1 -1
  200. package/dist/types/document-models/ph-clint-project/v1/gen/reducer.d.ts +2 -2
  201. package/dist/types/document-models/ph-clint-project/v1/gen/reducer.d.ts.map +1 -1
  202. package/dist/types/document-models/ph-clint-project/v1/gen/schema/index.d.ts +2 -2
  203. package/dist/types/document-models/ph-clint-project/v1/gen/schema/types.d.ts +215 -131
  204. package/dist/types/document-models/ph-clint-project/v1/gen/schema/types.d.ts.map +1 -1
  205. package/dist/types/document-models/ph-clint-project/v1/gen/schema/zod.d.ts +24 -8
  206. package/dist/types/document-models/ph-clint-project/v1/gen/schema/zod.d.ts.map +1 -1
  207. package/dist/types/document-models/ph-clint-project/v1/gen/types.d.ts +5 -5
  208. package/dist/types/document-models/ph-clint-project/v1/gen/types.d.ts.map +1 -1
  209. package/dist/types/document-models/ph-clint-project/v1/gen/utils.d.ts +2 -2
  210. package/dist/types/document-models/ph-clint-project/v1/gen/utils.d.ts.map +1 -1
  211. package/dist/types/document-models/ph-clint-project/v1/hooks.d.ts +3 -6
  212. package/dist/types/document-models/ph-clint-project/v1/hooks.d.ts.map +1 -1
  213. package/dist/types/document-models/ph-clint-project/v1/index.d.ts +6 -6
  214. package/dist/types/document-models/ph-clint-project/v1/module.d.ts +31 -16
  215. package/dist/types/document-models/ph-clint-project/v1/module.d.ts.map +1 -1
  216. package/dist/types/document-models/ph-clint-project/v1/src/index.d.ts +1 -1
  217. package/dist/types/document-models/ph-clint-project/v1/src/reducers/deployment.d.ts +1 -1
  218. package/dist/types/document-models/ph-clint-project/v1/src/reducers/deployment.d.ts.map +1 -1
  219. package/dist/types/document-models/ph-clint-project/v1/src/reducers/external-skills.d.ts +1 -1
  220. package/dist/types/document-models/ph-clint-project/v1/src/reducers/external-skills.d.ts.map +1 -1
  221. package/dist/types/document-models/ph-clint-project/v1/src/reducers/features-mastra.d.ts +1 -1
  222. package/dist/types/document-models/ph-clint-project/v1/src/reducers/features-mastra.d.ts.map +1 -1
  223. package/dist/types/document-models/ph-clint-project/v1/src/reducers/features-powerhouse.d.ts +1 -1
  224. package/dist/types/document-models/ph-clint-project/v1/src/reducers/features-powerhouse.d.ts.map +1 -1
  225. package/dist/types/document-models/ph-clint-project/v1/src/reducers/features-routine.d.ts +1 -1
  226. package/dist/types/document-models/ph-clint-project/v1/src/reducers/features-routine.d.ts.map +1 -1
  227. package/dist/types/document-models/ph-clint-project/v1/src/reducers/identity.d.ts +1 -1
  228. package/dist/types/document-models/ph-clint-project/v1/src/reducers/identity.d.ts.map +1 -1
  229. package/dist/types/document-models/ph-clint-project/v1/src/reducers/lifecycle.d.ts +1 -1
  230. package/dist/types/document-models/ph-clint-project/v1/src/reducers/lifecycle.d.ts.map +1 -1
  231. package/dist/types/document-models/ph-clint-project/v1/src/reducers/mastra-agent-bindings.d.ts.map +1 -0
  232. package/dist/types/document-models/ph-clint-project/v1/src/reducers/mastra-main-agent.d.ts.map +1 -0
  233. package/dist/types/document-models/ph-clint-project/v1/src/reducers/mastra-models.d.ts.map +1 -0
  234. package/dist/types/document-models/ph-clint-project/v1/src/reducers/mastra-profiles.d.ts.map +1 -0
  235. package/dist/types/document-models/ph-clint-project/v1/src/reducers/mastra-sub-agents.d.ts.map +1 -0
  236. package/dist/types/document-models/ph-clint-project/v1/src/reducers/powerhouse-packages.d.ts +1 -1
  237. package/dist/types/document-models/ph-clint-project/v1/src/reducers/powerhouse-packages.d.ts.map +1 -1
  238. package/dist/types/document-models/ph-clint-project/v1/src/reducers/publishing.d.ts +1 -1
  239. package/dist/types/document-models/ph-clint-project/v1/src/reducers/publishing.d.ts.map +1 -1
  240. package/dist/types/document-models/ph-clint-project/v1/tests/mastra-agent-bindings.test.d.ts.map +1 -0
  241. package/dist/types/document-models/ph-clint-project/v1/tests/mastra-main-agent.test.d.ts.map +1 -0
  242. package/dist/types/document-models/ph-clint-project/v1/tests/mastra-models.test.d.ts.map +1 -0
  243. package/dist/types/document-models/ph-clint-project/v1/tests/mastra-profiles.test.d.ts.map +1 -0
  244. package/dist/types/document-models/ph-clint-project/v1/tests/mastra-sub-agents.test.d.ts.map +1 -0
  245. package/dist/types/document-models/ph-clint-project/v1/utils.d.ts +2 -2
  246. package/dist/types/document-models/upgrade-manifests.d.ts +1 -1
  247. package/dist/types/document-models/upgrade-manifests.d.ts.map +1 -1
  248. package/dist/types/editors/editors.d.ts +1 -5
  249. package/dist/types/editors/editors.d.ts.map +1 -1
  250. package/dist/types/editors/index.d.ts +1 -1
  251. package/dist/types/editors/ph-clint-project-editor/editor.d.ts.map +1 -1
  252. package/dist/types/editors/ph-clint-project-editor/module.d.ts +1 -5
  253. package/dist/types/editors/ph-clint-project-editor/module.d.ts.map +1 -1
  254. package/dist/types/index.d.ts +7 -9
  255. package/dist/types/index.d.ts.map +1 -1
  256. package/dist/types/processors/connect.d.ts +1 -1
  257. package/dist/types/processors/factory.d.ts +2 -2
  258. package/dist/types/processors/factory.d.ts.map +1 -1
  259. package/dist/types/processors/index.d.ts +1 -1
  260. package/dist/types/processors/switchboard.d.ts +1 -1
  261. package/package.json +38 -27
  262. package/dist/browser/module-B16ZT36n.js.map +0 -1
  263. package/dist/browser/ph-clint-project-CHq59BKL.js.map +0 -1
  264. package/dist/connect/__react__/chunks/chunk-BUAv4yFm.js +0 -1
  265. package/dist/connect/__react__/chunks/server.browser-Ds-0IcTb.js +0 -1
  266. package/dist/connect/__react__/chunks/static.browser-CL3g4nOE.js +0 -1
  267. package/dist/connect/assets/editor-BaQ62r3i.js +0 -2
  268. package/dist/connect/assets/index-NB86TKkT.js +0 -3
  269. package/dist/connect/assets/index-NB86TKkT.js.map +0 -1
  270. package/dist/connect/assets/index-vlKMuf0A.css +0 -2
  271. package/dist/connect/assets/ph-clint-project-p1zY6e17.js.map +0 -1
  272. package/dist/document-models/document-models.d.ts +0 -7
  273. package/dist/document-models/document-models.d.ts.map +0 -1
  274. package/dist/document-models/index.d.ts +0 -2
  275. package/dist/document-models/index.d.ts.map +0 -1
  276. package/dist/document-models/ph-clint-project/gen/schema/types.d.ts.map +0 -1
  277. package/dist/document-models/ph-clint-project/gen/schema/zod.d.ts.map +0 -1
  278. package/dist/document-models/ph-clint-project/index.d.ts +0 -3
  279. package/dist/document-models/ph-clint-project/index.d.ts.map +0 -1
  280. package/dist/document-models/ph-clint-project/upgrades/index.d.ts +0 -3
  281. package/dist/document-models/ph-clint-project/upgrades/index.d.ts.map +0 -1
  282. package/dist/document-models/ph-clint-project/upgrades/upgrade-manifest.d.ts +0 -8
  283. package/dist/document-models/ph-clint-project/upgrades/upgrade-manifest.d.ts.map +0 -1
  284. package/dist/document-models/ph-clint-project/upgrades/versions.d.ts +0 -3
  285. package/dist/document-models/ph-clint-project/upgrades/versions.d.ts.map +0 -1
  286. package/dist/document-models/ph-clint-project/v1/actions.d.ts +0 -68
  287. package/dist/document-models/ph-clint-project/v1/actions.d.ts.map +0 -1
  288. package/dist/document-models/ph-clint-project/v1/gen/actions.d.ts +0 -34
  289. package/dist/document-models/ph-clint-project/v1/gen/actions.d.ts.map +0 -1
  290. package/dist/document-models/ph-clint-project/v1/gen/controller.d.ts +0 -8
  291. package/dist/document-models/ph-clint-project/v1/gen/controller.d.ts.map +0 -1
  292. package/dist/document-models/ph-clint-project/v1/gen/creators.d.ts +0 -33
  293. package/dist/document-models/ph-clint-project/v1/gen/creators.d.ts.map +0 -1
  294. package/dist/document-models/ph-clint-project/v1/gen/deployment/actions.d.ts +0 -24
  295. package/dist/document-models/ph-clint-project/v1/gen/deployment/actions.d.ts.map +0 -1
  296. package/dist/document-models/ph-clint-project/v1/gen/deployment/creators.d.ts +0 -7
  297. package/dist/document-models/ph-clint-project/v1/gen/deployment/creators.d.ts.map +0 -1
  298. package/dist/document-models/ph-clint-project/v1/gen/deployment/error.d.ts +0 -21
  299. package/dist/document-models/ph-clint-project/v1/gen/deployment/error.d.ts.map +0 -1
  300. package/dist/document-models/ph-clint-project/v1/gen/deployment/operations.d.ts +0 -14
  301. package/dist/document-models/ph-clint-project/v1/gen/deployment/operations.d.ts.map +0 -1
  302. package/dist/document-models/ph-clint-project/v1/gen/document-model.d.ts +0 -3
  303. package/dist/document-models/ph-clint-project/v1/gen/document-model.d.ts.map +0 -1
  304. package/dist/document-models/ph-clint-project/v1/gen/document-schema.d.ts +0 -68
  305. package/dist/document-models/ph-clint-project/v1/gen/document-schema.d.ts.map +0 -1
  306. package/dist/document-models/ph-clint-project/v1/gen/document-type.d.ts +0 -6
  307. package/dist/document-models/ph-clint-project/v1/gen/document-type.d.ts.map +0 -1
  308. package/dist/document-models/ph-clint-project/v1/gen/external-skills/actions.d.ts +0 -24
  309. package/dist/document-models/ph-clint-project/v1/gen/external-skills/actions.d.ts.map +0 -1
  310. package/dist/document-models/ph-clint-project/v1/gen/external-skills/creators.d.ts +0 -7
  311. package/dist/document-models/ph-clint-project/v1/gen/external-skills/creators.d.ts.map +0 -1
  312. package/dist/document-models/ph-clint-project/v1/gen/external-skills/error.d.ts +0 -34
  313. package/dist/document-models/ph-clint-project/v1/gen/external-skills/error.d.ts.map +0 -1
  314. package/dist/document-models/ph-clint-project/v1/gen/external-skills/operations.d.ts +0 -14
  315. package/dist/document-models/ph-clint-project/v1/gen/external-skills/operations.d.ts.map +0 -1
  316. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/actions.d.ts +0 -20
  317. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/actions.d.ts.map +0 -1
  318. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/creators.d.ts +0 -6
  319. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/creators.d.ts.map +0 -1
  320. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/error.d.ts +0 -31
  321. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/error.d.ts.map +0 -1
  322. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/operations.d.ts +0 -13
  323. package/dist/document-models/ph-clint-project/v1/gen/features-mastra/operations.d.ts.map +0 -1
  324. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/actions.d.ts +0 -12
  325. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/actions.d.ts.map +0 -1
  326. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/creators.d.ts +0 -4
  327. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/creators.d.ts.map +0 -1
  328. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/error.d.ts +0 -14
  329. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/error.d.ts.map +0 -1
  330. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/operations.d.ts +0 -11
  331. package/dist/document-models/ph-clint-project/v1/gen/features-powerhouse/operations.d.ts.map +0 -1
  332. package/dist/document-models/ph-clint-project/v1/gen/features-routine/actions.d.ts +0 -16
  333. package/dist/document-models/ph-clint-project/v1/gen/features-routine/actions.d.ts.map +0 -1
  334. package/dist/document-models/ph-clint-project/v1/gen/features-routine/creators.d.ts +0 -5
  335. package/dist/document-models/ph-clint-project/v1/gen/features-routine/creators.d.ts.map +0 -1
  336. package/dist/document-models/ph-clint-project/v1/gen/features-routine/error.d.ts +0 -2
  337. package/dist/document-models/ph-clint-project/v1/gen/features-routine/error.d.ts.map +0 -1
  338. package/dist/document-models/ph-clint-project/v1/gen/features-routine/operations.d.ts +0 -12
  339. package/dist/document-models/ph-clint-project/v1/gen/features-routine/operations.d.ts.map +0 -1
  340. package/dist/document-models/ph-clint-project/v1/gen/identity/actions.d.ts +0 -20
  341. package/dist/document-models/ph-clint-project/v1/gen/identity/actions.d.ts.map +0 -1
  342. package/dist/document-models/ph-clint-project/v1/gen/identity/creators.d.ts +0 -6
  343. package/dist/document-models/ph-clint-project/v1/gen/identity/creators.d.ts.map +0 -1
  344. package/dist/document-models/ph-clint-project/v1/gen/identity/error.d.ts +0 -21
  345. package/dist/document-models/ph-clint-project/v1/gen/identity/error.d.ts.map +0 -1
  346. package/dist/document-models/ph-clint-project/v1/gen/identity/operations.d.ts +0 -13
  347. package/dist/document-models/ph-clint-project/v1/gen/identity/operations.d.ts.map +0 -1
  348. package/dist/document-models/ph-clint-project/v1/gen/index.d.ts +0 -30
  349. package/dist/document-models/ph-clint-project/v1/gen/index.d.ts.map +0 -1
  350. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/actions.d.ts +0 -12
  351. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/actions.d.ts.map +0 -1
  352. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/creators.d.ts +0 -4
  353. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/creators.d.ts.map +0 -1
  354. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/error.d.ts +0 -8
  355. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/error.d.ts.map +0 -1
  356. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/operations.d.ts +0 -11
  357. package/dist/document-models/ph-clint-project/v1/gen/lifecycle/operations.d.ts.map +0 -1
  358. package/dist/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/actions.d.ts.map +0 -1
  359. package/dist/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/creators.d.ts.map +0 -1
  360. package/dist/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/error.d.ts.map +0 -1
  361. package/dist/document-models/ph-clint-project/v1/gen/mastra-agent-bindings/operations.d.ts.map +0 -1
  362. package/dist/document-models/ph-clint-project/v1/gen/mastra-main-agent/actions.d.ts.map +0 -1
  363. package/dist/document-models/ph-clint-project/v1/gen/mastra-main-agent/creators.d.ts.map +0 -1
  364. package/dist/document-models/ph-clint-project/v1/gen/mastra-main-agent/error.d.ts.map +0 -1
  365. package/dist/document-models/ph-clint-project/v1/gen/mastra-main-agent/operations.d.ts.map +0 -1
  366. package/dist/document-models/ph-clint-project/v1/gen/mastra-models/actions.d.ts.map +0 -1
  367. package/dist/document-models/ph-clint-project/v1/gen/mastra-models/creators.d.ts.map +0 -1
  368. package/dist/document-models/ph-clint-project/v1/gen/mastra-models/error.d.ts.map +0 -1
  369. package/dist/document-models/ph-clint-project/v1/gen/mastra-models/operations.d.ts.map +0 -1
  370. package/dist/document-models/ph-clint-project/v1/gen/mastra-profiles/actions.d.ts.map +0 -1
  371. package/dist/document-models/ph-clint-project/v1/gen/mastra-profiles/creators.d.ts.map +0 -1
  372. package/dist/document-models/ph-clint-project/v1/gen/mastra-profiles/error.d.ts.map +0 -1
  373. package/dist/document-models/ph-clint-project/v1/gen/mastra-profiles/operations.d.ts.map +0 -1
  374. package/dist/document-models/ph-clint-project/v1/gen/mastra-sub-agents/actions.d.ts.map +0 -1
  375. package/dist/document-models/ph-clint-project/v1/gen/mastra-sub-agents/creators.d.ts.map +0 -1
  376. package/dist/document-models/ph-clint-project/v1/gen/mastra-sub-agents/error.d.ts.map +0 -1
  377. package/dist/document-models/ph-clint-project/v1/gen/mastra-sub-agents/operations.d.ts.map +0 -1
  378. package/dist/document-models/ph-clint-project/v1/gen/ph-factories.d.ts +0 -25
  379. package/dist/document-models/ph-clint-project/v1/gen/ph-factories.d.ts.map +0 -1
  380. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/actions.d.ts +0 -28
  381. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/actions.d.ts.map +0 -1
  382. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/creators.d.ts +0 -8
  383. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/creators.d.ts.map +0 -1
  384. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/error.d.ts +0 -60
  385. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/error.d.ts.map +0 -1
  386. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/operations.d.ts +0 -15
  387. package/dist/document-models/ph-clint-project/v1/gen/powerhouse-packages/operations.d.ts.map +0 -1
  388. package/dist/document-models/ph-clint-project/v1/gen/publishing/actions.d.ts +0 -28
  389. package/dist/document-models/ph-clint-project/v1/gen/publishing/actions.d.ts.map +0 -1
  390. package/dist/document-models/ph-clint-project/v1/gen/publishing/creators.d.ts +0 -8
  391. package/dist/document-models/ph-clint-project/v1/gen/publishing/creators.d.ts.map +0 -1
  392. package/dist/document-models/ph-clint-project/v1/gen/publishing/error.d.ts +0 -21
  393. package/dist/document-models/ph-clint-project/v1/gen/publishing/error.d.ts.map +0 -1
  394. package/dist/document-models/ph-clint-project/v1/gen/publishing/operations.d.ts +0 -15
  395. package/dist/document-models/ph-clint-project/v1/gen/publishing/operations.d.ts.map +0 -1
  396. package/dist/document-models/ph-clint-project/v1/gen/reducer.d.ts +0 -4
  397. package/dist/document-models/ph-clint-project/v1/gen/reducer.d.ts.map +0 -1
  398. package/dist/document-models/ph-clint-project/v1/gen/schema/index.d.ts +0 -7
  399. package/dist/document-models/ph-clint-project/v1/gen/schema/index.d.ts.map +0 -1
  400. package/dist/document-models/ph-clint-project/v1/gen/schema/types.d.ts +0 -475
  401. package/dist/document-models/ph-clint-project/v1/gen/schema/types.d.ts.map +0 -1
  402. package/dist/document-models/ph-clint-project/v1/gen/schema/zod.d.ts +0 -97
  403. package/dist/document-models/ph-clint-project/v1/gen/schema/zod.d.ts.map +0 -1
  404. package/dist/document-models/ph-clint-project/v1/gen/types.d.ts +0 -16
  405. package/dist/document-models/ph-clint-project/v1/gen/types.d.ts.map +0 -1
  406. package/dist/document-models/ph-clint-project/v1/gen/utils.d.ts +0 -10
  407. package/dist/document-models/ph-clint-project/v1/gen/utils.d.ts.map +0 -1
  408. package/dist/document-models/ph-clint-project/v1/hooks.d.ts +0 -15
  409. package/dist/document-models/ph-clint-project/v1/hooks.d.ts.map +0 -1
  410. package/dist/document-models/ph-clint-project/v1/index.d.ts +0 -11
  411. package/dist/document-models/ph-clint-project/v1/index.d.ts.map +0 -1
  412. package/dist/document-models/ph-clint-project/v1/module.d.ts +0 -75
  413. package/dist/document-models/ph-clint-project/v1/module.d.ts.map +0 -1
  414. package/dist/document-models/ph-clint-project/v1/src/index.d.ts +0 -6
  415. package/dist/document-models/ph-clint-project/v1/src/index.d.ts.map +0 -1
  416. package/dist/document-models/ph-clint-project/v1/src/reducers/deployment.d.ts +0 -3
  417. package/dist/document-models/ph-clint-project/v1/src/reducers/deployment.d.ts.map +0 -1
  418. package/dist/document-models/ph-clint-project/v1/src/reducers/external-skills.d.ts +0 -3
  419. package/dist/document-models/ph-clint-project/v1/src/reducers/external-skills.d.ts.map +0 -1
  420. package/dist/document-models/ph-clint-project/v1/src/reducers/features-mastra.d.ts +0 -3
  421. package/dist/document-models/ph-clint-project/v1/src/reducers/features-mastra.d.ts.map +0 -1
  422. package/dist/document-models/ph-clint-project/v1/src/reducers/features-powerhouse.d.ts +0 -3
  423. package/dist/document-models/ph-clint-project/v1/src/reducers/features-powerhouse.d.ts.map +0 -1
  424. package/dist/document-models/ph-clint-project/v1/src/reducers/features-routine.d.ts +0 -3
  425. package/dist/document-models/ph-clint-project/v1/src/reducers/features-routine.d.ts.map +0 -1
  426. package/dist/document-models/ph-clint-project/v1/src/reducers/identity.d.ts +0 -3
  427. package/dist/document-models/ph-clint-project/v1/src/reducers/identity.d.ts.map +0 -1
  428. package/dist/document-models/ph-clint-project/v1/src/reducers/lifecycle.d.ts +0 -3
  429. package/dist/document-models/ph-clint-project/v1/src/reducers/lifecycle.d.ts.map +0 -1
  430. package/dist/document-models/ph-clint-project/v1/src/reducers/mastra-agent-bindings.d.ts.map +0 -1
  431. package/dist/document-models/ph-clint-project/v1/src/reducers/mastra-main-agent.d.ts.map +0 -1
  432. package/dist/document-models/ph-clint-project/v1/src/reducers/mastra-models.d.ts.map +0 -1
  433. package/dist/document-models/ph-clint-project/v1/src/reducers/mastra-profiles.d.ts.map +0 -1
  434. package/dist/document-models/ph-clint-project/v1/src/reducers/mastra-sub-agents.d.ts.map +0 -1
  435. package/dist/document-models/ph-clint-project/v1/src/reducers/powerhouse-packages.d.ts +0 -3
  436. package/dist/document-models/ph-clint-project/v1/src/reducers/powerhouse-packages.d.ts.map +0 -1
  437. package/dist/document-models/ph-clint-project/v1/src/reducers/publishing.d.ts +0 -3
  438. package/dist/document-models/ph-clint-project/v1/src/reducers/publishing.d.ts.map +0 -1
  439. package/dist/document-models/ph-clint-project/v1/src/utils.d.ts +0 -2
  440. package/dist/document-models/ph-clint-project/v1/src/utils.d.ts.map +0 -1
  441. package/dist/document-models/ph-clint-project/v1/tests/deployment.test.d.ts +0 -2
  442. package/dist/document-models/ph-clint-project/v1/tests/deployment.test.d.ts.map +0 -1
  443. package/dist/document-models/ph-clint-project/v1/tests/document-model.test.d.ts +0 -10
  444. package/dist/document-models/ph-clint-project/v1/tests/document-model.test.d.ts.map +0 -1
  445. package/dist/document-models/ph-clint-project/v1/tests/external-skills.test.d.ts +0 -2
  446. package/dist/document-models/ph-clint-project/v1/tests/external-skills.test.d.ts.map +0 -1
  447. package/dist/document-models/ph-clint-project/v1/tests/features-mastra.test.d.ts +0 -2
  448. package/dist/document-models/ph-clint-project/v1/tests/features-mastra.test.d.ts.map +0 -1
  449. package/dist/document-models/ph-clint-project/v1/tests/features-powerhouse.test.d.ts +0 -2
  450. package/dist/document-models/ph-clint-project/v1/tests/features-powerhouse.test.d.ts.map +0 -1
  451. package/dist/document-models/ph-clint-project/v1/tests/features-routine.test.d.ts +0 -2
  452. package/dist/document-models/ph-clint-project/v1/tests/features-routine.test.d.ts.map +0 -1
  453. package/dist/document-models/ph-clint-project/v1/tests/identity.test.d.ts +0 -2
  454. package/dist/document-models/ph-clint-project/v1/tests/identity.test.d.ts.map +0 -1
  455. package/dist/document-models/ph-clint-project/v1/tests/lifecycle.test.d.ts +0 -2
  456. package/dist/document-models/ph-clint-project/v1/tests/lifecycle.test.d.ts.map +0 -1
  457. package/dist/document-models/ph-clint-project/v1/tests/mastra-agent-bindings.test.d.ts.map +0 -1
  458. package/dist/document-models/ph-clint-project/v1/tests/mastra-main-agent.test.d.ts.map +0 -1
  459. package/dist/document-models/ph-clint-project/v1/tests/mastra-models.test.d.ts.map +0 -1
  460. package/dist/document-models/ph-clint-project/v1/tests/mastra-profiles.test.d.ts.map +0 -1
  461. package/dist/document-models/ph-clint-project/v1/tests/mastra-sub-agents.test.d.ts.map +0 -1
  462. package/dist/document-models/ph-clint-project/v1/tests/powerhouse-packages.test.d.ts +0 -2
  463. package/dist/document-models/ph-clint-project/v1/tests/powerhouse-packages.test.d.ts.map +0 -1
  464. package/dist/document-models/ph-clint-project/v1/tests/publishing.test.d.ts +0 -2
  465. package/dist/document-models/ph-clint-project/v1/tests/publishing.test.d.ts.map +0 -1
  466. package/dist/document-models/ph-clint-project/v1/utils.d.ts +0 -9
  467. package/dist/document-models/ph-clint-project/v1/utils.d.ts.map +0 -1
  468. package/dist/document-models/upgrade-manifests.d.ts +0 -7
  469. package/dist/document-models/upgrade-manifests.d.ts.map +0 -1
  470. package/dist/editors/editors.d.ts +0 -3
  471. package/dist/editors/editors.d.ts.map +0 -1
  472. package/dist/editors/index.d.ts +0 -2
  473. package/dist/editors/index.d.ts.map +0 -1
  474. package/dist/editors/ph-clint-project-editor/editor.d.ts +0 -2
  475. package/dist/editors/ph-clint-project-editor/editor.d.ts.map +0 -1
  476. package/dist/editors/ph-clint-project-editor/module.d.ts +0 -4
  477. package/dist/editors/ph-clint-project-editor/module.d.ts.map +0 -1
  478. package/dist/index.d.ts +0 -9
  479. package/dist/index.d.ts.map +0 -1
  480. package/dist/main.d.ts +0 -2
  481. package/dist/main.d.ts.map +0 -1
  482. package/dist/node/module-BPw40Ypp.mjs.map +0 -1
  483. package/dist/node/ph-clint-project-B5IjiXbp.mjs.map +0 -1
  484. package/dist/processors/connect.d.ts +0 -3
  485. package/dist/processors/connect.d.ts.map +0 -1
  486. package/dist/processors/factory.d.ts +0 -8
  487. package/dist/processors/factory.d.ts.map +0 -1
  488. package/dist/processors/index.d.ts +0 -6
  489. package/dist/processors/index.d.ts.map +0 -1
  490. package/dist/processors/switchboard.d.ts +0 -3
  491. package/dist/processors/switchboard.d.ts.map +0 -1
  492. package/dist/subgraphs/index.d.ts +0 -2
  493. package/dist/subgraphs/index.d.ts.map +0 -1
  494. /package/dist/{document-models → types/document-models}/ph-clint-project/gen/schema/types.d.ts +0 -0
  495. /package/dist/{document-models → types/document-models}/ph-clint-project/gen/schema/zod.d.ts +0 -0
  496. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-agent-bindings/actions.d.ts +0 -0
  497. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-agent-bindings/creators.d.ts +0 -0
  498. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-agent-bindings/error.d.ts +0 -0
  499. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-agent-bindings/operations.d.ts +0 -0
  500. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-main-agent/actions.d.ts +0 -0
  501. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-main-agent/creators.d.ts +0 -0
  502. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-main-agent/error.d.ts +0 -0
  503. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-main-agent/operations.d.ts +0 -0
  504. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-models/actions.d.ts +0 -0
  505. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-models/creators.d.ts +0 -0
  506. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-models/error.d.ts +0 -0
  507. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-models/operations.d.ts +0 -0
  508. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-profiles/actions.d.ts +0 -0
  509. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-profiles/creators.d.ts +0 -0
  510. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-profiles/error.d.ts +0 -0
  511. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-profiles/operations.d.ts +0 -0
  512. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-sub-agents/actions.d.ts +0 -0
  513. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-sub-agents/creators.d.ts +0 -0
  514. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-sub-agents/error.d.ts +0 -0
  515. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/gen/mastra-sub-agents/operations.d.ts +0 -0
  516. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/src/reducers/mastra-agent-bindings.d.ts +0 -0
  517. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/src/reducers/mastra-main-agent.d.ts +0 -0
  518. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/src/reducers/mastra-models.d.ts +0 -0
  519. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/src/reducers/mastra-profiles.d.ts +0 -0
  520. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/src/reducers/mastra-sub-agents.d.ts +0 -0
  521. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/tests/mastra-agent-bindings.test.d.ts +0 -0
  522. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/tests/mastra-main-agent.test.d.ts +0 -0
  523. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/tests/mastra-models.test.d.ts +0 -0
  524. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/tests/mastra-profiles.test.d.ts +0 -0
  525. /package/dist/{document-models → types/document-models}/ph-clint-project/v1/tests/mastra-sub-agents.test.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ph-clint-project-1Xn2yUDQ.js","names":["z.any","z.enum","z.object","z.string","z.literal","z.boolean","z.array","z.union","addFile","addFolder","initialGlobalState","initialLocalState","e","t","e","t","e","n","e","createState","isPlainObj","funnel","hasAtLeast","lzString","isDefined","DriveCollectionId$1"],"sources":["../../document-models/ph-clint-project/v1/gen/controller.ts","../../document-models/ph-clint-project/v1/gen/ph-factories.ts","../../../../node_modules/.pnpm/@powerhousedao+reactor-browser@6.2.0-dev.23_@electric-sql+pglite@0.3.15_@sentry+node-co_a06decc8eb2e8e779520ae1fd2edd0f6/node_modules/@powerhousedao/reactor-browser/dist/make-ph-event-functions-BHoLPif5.js","../../../../node_modules/.pnpm/@powerhousedao+reactor@6.2.0-dev.23_@sentry+node-core@10.58.0_@opentelemetry+api@1.9.1__d02404168724a95d129c110ba1297217/node_modules/@powerhousedao/reactor/dist/drive-container-types-BxnXaOAp.js","../../../../node_modules/.pnpm/@powerhousedao+shared@6.2.0-dev.23_@sentry+node-core@10.58.0_@opentelemetry+api@1.9.1_@_b658b833cfb712fadb570e50952defdb/node_modules/@powerhousedao/shared/dist/document-drive/index.js","../../../../node_modules/.pnpm/@powerhousedao+reactor@6.2.0-dev.23_@sentry+node-core@10.58.0_@opentelemetry+api@1.9.1__d02404168724a95d129c110ba1297217/node_modules/@powerhousedao/reactor/dist/index.js","../../../../node_modules/.pnpm/@powerhousedao+reactor-browser@6.2.0-dev.23_@electric-sql+pglite@0.3.15_@sentry+node-co_a06decc8eb2e8e779520ae1fd2edd0f6/node_modules/@powerhousedao/reactor-browser/dist/document-by-id-dLYFX-xz.js","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/jsutils/devAssert.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/jsutils/isObjectLike.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/jsutils/invariant.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/location.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/printLocation.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/error/GraphQLError.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/error/syntaxError.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/ast.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/directiveLocation.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/kinds.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/characterClasses.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/blockString.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/tokenKind.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/lexer.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/jsutils/inspect.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/jsutils/instanceOf.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/source.mjs","../../../../node_modules/.pnpm/graphql@16.12.0/node_modules/graphql/language/parser.mjs","../../../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs","../../../../node_modules/.pnpm/graphql-tag@2.12.6_graphql@16.12.0/node_modules/graphql-tag/lib/index.js","../../../../node_modules/.pnpm/@powerhousedao+reactor-browser@6.2.0-dev.23_@electric-sql+pglite@0.3.15_@sentry+node-co_a06decc8eb2e8e779520ae1fd2edd0f6/node_modules/@powerhousedao/reactor-browser/dist/client-_Gh2Uf0E.js","../../../../node_modules/.pnpm/@powerhousedao+reactor-browser@6.2.0-dev.23_@electric-sql+pglite@0.3.15_@sentry+node-co_a06decc8eb2e8e779520ae1fd2edd0f6/node_modules/@powerhousedao/reactor-browser/dist/renown-D-1c_Bvx.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js","../../../../node_modules/.pnpm/@powerhousedao+reactor-drive@6.2.0-dev.23_@sentry+node-core@10.58.0_@opentelemetry+api@_bd7cec8a444ae8a21aa81bf0b5277e9f/node_modules/@powerhousedao/reactor-drive/dist/index.js","../../../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js","../../../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js","../../../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js","../../../../node_modules/.pnpm/lz-string@1.5.0/node_modules/lz-string/libs/lz-string.js","../../../../node_modules/.pnpm/@powerhousedao+reactor-browser@6.2.0-dev.23_@electric-sql+pglite@0.3.15_@sentry+node-co_a06decc8eb2e8e779520ae1fd2edd0f6/node_modules/@powerhousedao/reactor-browser/dist/index.js","../../document-models/ph-clint-project/v1/hooks.ts"],"sourcesContent":["/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport { PHDocumentController } from 'document-model';\nimport { PhClintProject } from '../module.js';\nimport type { PhClintProjectAction, PhClintProjectPHState } from './types.js';\n\nexport const PhClintProjectController = PHDocumentController.forDocumentModel<PhClintProjectPHState, PhClintProjectAction>(PhClintProject);\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n * Factory methods for creating PhClintProjectDocument instances\n */\nimport type { PHAuthState, PHBaseState, PHDocumentState } from 'document-model';\nimport { createBaseState, defaultBaseState } from 'document-model';\nimport type { PhClintProjectDocument, PhClintProjectGlobalState, PhClintProjectLocalState, PhClintProjectPHState } from './types.js';\nimport { utils } from './utils.js';\n\nexport function defaultGlobalState(): PhClintProjectGlobalState {\n return {\n name: null,\n scope: null,\n version: '0.1.0',\n description: '',\n features: {\n powerhouse: 'Disabled',\n mastra: {\n enabled: false,\n mainAgent: null,\n subAgents: [],\n models: [],\n profiles: [],\n common: { enableChat: false },\n },\n routine: { enabled: false },\n },\n packages: [],\n externalSkills: [],\n publishHistory: [],\n deployment: {\n proxyEnabled: false,\n observabilityEnabled: false,\n supportedResources: ['vetra-agent-s', 'vetra-agent-m', 'vetra-agent-l', 'vetra-agent-xl', 'vetra-agent-xxl'],\n },\n };\n}\n\nexport function defaultLocalState(): PhClintProjectLocalState {\n return {};\n}\n\nexport function defaultPHState(): PhClintProjectPHState {\n return {\n ...defaultBaseState(),\n global: defaultGlobalState(),\n local: defaultLocalState(),\n };\n}\n\nexport function createGlobalState(state?: Partial<PhClintProjectGlobalState>): PhClintProjectGlobalState {\n return {\n ...defaultGlobalState(),\n ...(state || {}),\n };\n}\n\nexport function createLocalState(state?: Partial<PhClintProjectLocalState>): PhClintProjectLocalState {\n return {\n ...defaultLocalState(),\n ...(state || {}),\n } as PhClintProjectLocalState;\n}\n\nexport function createState(baseState?: Partial<PHBaseState>, globalState?: Partial<PhClintProjectGlobalState>, localState?: Partial<PhClintProjectLocalState>): PhClintProjectPHState {\n return {\n ...createBaseState(baseState?.auth, baseState?.document),\n global: createGlobalState(globalState),\n local: createLocalState(localState),\n };\n}\n\n/**\n * Creates a PhClintProjectDocument with custom global and local state\n * This properly handles the PHBaseState requirements while allowing\n * document-specific state to be set.\n */\nexport function createPhClintProjectDocument(\n state?: Partial<{\n auth?: Partial<PHAuthState>;\n document?: Partial<PHDocumentState>;\n global?: Partial<PhClintProjectGlobalState>;\n local?: Partial<PhClintProjectLocalState>;\n }>,\n): PhClintProjectDocument {\n const document = utils.createDocument(state ? createState(createBaseState(state.auth, state.document), state.global, state.local) : undefined);\n\n return document;\n}\n","import { capitalCase } from \"change-case\";\nimport { useSyncExternalStore } from \"react\";\n//#region src/hooks/make-ph-event-functions.ts\nconst isServer = typeof window === \"undefined\";\nfunction makePHEventFunctions(key) {\n\tconst setEventName = `ph:set${capitalCase(key)}`;\n\tconst updateEventName = `ph:${key}Updated`;\n\tfunction setValue(value) {\n\t\tif (isServer) return;\n\t\tconst event = new CustomEvent(setEventName, { detail: { [key]: value } });\n\t\twindow.dispatchEvent(event);\n\t}\n\tfunction dispatchUpdatedEvent() {\n\t\tif (isServer) return;\n\t\tconst event = new CustomEvent(updateEventName);\n\t\twindow.dispatchEvent(event);\n\t}\n\tfunction handleSetValueEvent(event) {\n\t\tif (isServer) return;\n\t\tconst value = event.detail[key];\n\t\tif (!window.ph) window.ph = {};\n\t\twindow.ph[key] = value;\n\t\tdispatchUpdatedEvent();\n\t}\n\tfunction addEventHandler() {\n\t\tif (isServer) return;\n\t\twindow.addEventListener(setEventName, handleSetValueEvent);\n\t}\n\tfunction subscribeToValue(onStoreChange) {\n\t\tif (isServer) return () => {};\n\t\twindow.addEventListener(updateEventName, onStoreChange);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(updateEventName, onStoreChange);\n\t\t};\n\t}\n\tfunction getSnapshot() {\n\t\tif (isServer) return;\n\t\treturn window.ph?.[key];\n\t}\n\tfunction getServerSnapshot() {}\n\tfunction useValue() {\n\t\treturn useSyncExternalStore(subscribeToValue, getSnapshot, getServerSnapshot);\n\t}\n\treturn {\n\t\tuseValue,\n\t\tsetValue,\n\t\taddEventHandler\n\t};\n}\n//#endregion\nexport { makePHEventFunctions as t };\n\n//# sourceMappingURL=make-ph-event-functions-BHoLPif5.js.map","import { n as ReactorEventTypes, t as EventBusAggregateError } from \"./types-CxSpmNGK.js\";\nimport { DowngradeNotSupportedError, applyDeleteDocumentAction, applyDeleteDocumentAction as applyDeleteDocumentAction$1, applyUpgradeDocumentAction, applyUpgradeDocumentAction as applyUpgradeDocumentAction$1, createPresignedHeader, defaultBaseState, deriveOperationId, isUndoRedo } from \"@powerhousedao/shared/document-model\";\nimport { v4 } from \"uuid\";\nimport { Migrator, sql } from \"kysely\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/shared/utils.ts\nfunction matchesScope(view = {}, scope) {\n\tif (view.scopes) return view.scopes.includes(scope);\n\treturn true;\n}\nfunction yieldToMain() {\n\tconst s = globalThis.scheduler;\n\tif (s?.yield) return s.yield();\n\treturn new Promise((resolve) => setTimeout(resolve, 0));\n}\nconst defaultAbortError = () => /* @__PURE__ */ new Error(\"Operation aborted\");\nfunction throwIfAborted(signal, makeError = defaultAbortError) {\n\tif (signal?.aborted) throw makeError();\n}\n/**\n* Validates PagingOptions and returns a normalized offset and limit.\n* Throws if the cursor is not empty and not a non-negative integer, or if\n* limit is less than 1. When `paging` is undefined, returns offset 0 and\n* the caller-supplied `defaultLimit`.\n*/\nfunction parsePagingOptions(paging, defaultLimit) {\n\tif (paging === void 0) return {\n\t\toffset: 0,\n\t\tlimit: defaultLimit\n\t};\n\tif (!Number.isInteger(paging.limit) || paging.limit < 1) throw new Error(`Invalid paging limit: ${String(paging.limit)} (must be an integer >= 1)`);\n\tif (paging.cursor === \"\") return {\n\t\toffset: 0,\n\t\tlimit: paging.limit\n\t};\n\tconst parsed = Number(paging.cursor);\n\tif (!Number.isInteger(parsed) || parsed < 0) throw new Error(`Invalid paging cursor: ${JSON.stringify(paging.cursor)} (must be empty or a non-negative integer)`);\n\treturn {\n\t\toffset: parsed,\n\t\tlimit: paging.limit\n\t};\n}\n//#endregion\n//#region src/shared/errors.ts\n/**\n* Error thrown when attempting to access a deleted document.\n*/\nvar DocumentDeletedError = class DocumentDeletedError extends Error {\n\tdocumentId;\n\tdeletedAtUtcIso;\n\tconstructor(documentId, deletedAtUtcIso = null) {\n\t\tconst message = deletedAtUtcIso ? `Document ${documentId} was deleted at ${deletedAtUtcIso}` : `Document ${documentId} has been deleted`;\n\t\tsuper(message);\n\t\tthis.name = \"DocumentDeletedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.deletedAtUtcIso = deletedAtUtcIso;\n\t\tError.captureStackTrace(this, DocumentDeletedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentDeletedError\";\n\t}\n};\n/**\n* Error thrown when an operation has an invalid signature.\n*/\nvar InvalidSignatureError = class InvalidSignatureError extends Error {\n\tdocumentId;\n\treason;\n\tconstructor(documentId, reason) {\n\t\tsuper(`Invalid signature in document ${documentId}: ${reason}`);\n\t\tthis.name = \"InvalidSignatureError\";\n\t\tthis.documentId = documentId;\n\t\tthis.reason = reason;\n\t\tError.captureStackTrace(this, InvalidSignatureError);\n\t}\n};\n/**\n* Error thrown when a document is not found (no operations exist for the document ID).\n*/\nvar DocumentNotFoundError = class DocumentNotFoundError extends Error {\n\tdocumentId;\n\tconstructor(documentId) {\n\t\tsuper(`Document ${documentId} not found`);\n\t\tthis.name = \"DocumentNotFoundError\";\n\t\tthis.documentId = documentId;\n\t\tError.captureStackTrace(this, DocumentNotFoundError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentNotFoundError\";\n\t}\n};\n//#endregion\n//#region src/registry/errors.ts\n/**\n* Error thrown when a document model module is not found in the registry.\n*/\nvar ModuleNotFoundError = class extends Error {\n\tdocumentType;\n\trequestedVersion;\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` version ${version}` : \"\";\n\t\tsuper(`Document model module not found for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"ModuleNotFoundError\";\n\t\tthis.documentType = documentType;\n\t\tthis.requestedVersion = version;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ModuleNotFoundError\";\n\t}\n};\n/**\n* Error thrown when attempting to register a module that already exists.\n*/\nvar DuplicateModuleError = class extends Error {\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` (version ${version})` : \"\";\n\t\tsuper(`Document model module already registered for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"DuplicateModuleError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateModuleError\";\n\t}\n};\n/**\n* Error thrown when a module is invalid or malformed.\n*/\nvar InvalidModuleError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(`Invalid document model module: ${message}`);\n\t\tthis.name = \"InvalidModuleError\";\n\t}\n};\n/**\n* Error thrown when attempting to register an upgrade manifest that already exists.\n*/\nvar DuplicateManifestError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest already registered for type: ${documentType}`);\n\t\tthis.name = \"DuplicateManifestError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateManifestError\";\n\t}\n};\n/**\n* Error thrown when an upgrade manifest is not found.\n*/\nvar ManifestNotFoundError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest not found for type: ${documentType}`);\n\t\tthis.name = \"ManifestNotFoundError\";\n\t}\n};\n/**\n* Error thrown when a required upgrade transition is missing from the manifest.\n*/\nvar MissingUpgradeTransitionError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Missing upgrade transition for ${documentType}: v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"MissingUpgradeTransitionError\";\n\t}\n};\n/**\n* Error thrown when getUpgradeReducer is called with a non-single-step version increment.\n*/\nvar InvalidUpgradeStepError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Invalid upgrade step for ${documentType}: must be single version increment, got v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"InvalidUpgradeStepError\";\n\t}\n};\n//#endregion\n//#region src/cache/collection-membership-cache.ts\nvar CollectionMembershipCache = class CollectionMembershipCache {\n\tcache = /* @__PURE__ */ new Map();\n\tconstructor(operationIndex) {\n\t\tthis.operationIndex = operationIndex;\n\t}\n\twithScopedIndex(operationIndex) {\n\t\tconst scoped = new CollectionMembershipCache(operationIndex);\n\t\tscoped.cache = this.cache;\n\t\treturn scoped;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tconst result = {};\n\t\tconst missing = [];\n\t\tfor (const docId of documentIds) {\n\t\t\tconst cached = this.cache.get(docId);\n\t\t\tif (cached !== void 0) result[docId] = cached;\n\t\t\telse missing.push(docId);\n\t\t}\n\t\tif (missing.length > 0) {\n\t\t\tconst fromDb = await this.operationIndex.getCollectionsForDocuments(missing);\n\t\t\tfor (const docId of missing) {\n\t\t\t\tconst collections = fromDb[docId] ?? [];\n\t\t\t\tresult[docId] = collections;\n\t\t\t\tthis.cache.set(docId, collections);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tinvalidate(documentId) {\n\t\tthis.cache.delete(documentId);\n\t}\n};\n//#endregion\n//#region src/executor/util.ts\n/**\n* Creates a PHDocument from a CREATE_DOCUMENT action input.\n* Reconstructs the document header and initializes the base state.\n*\n* @param action - The CREATE_DOCUMENT action containing the document parameters\n* @returns A newly constructed PHDocument with initialized header and base state\n*/\nfunction createDocumentFromAction(action) {\n\tconst input = action.input;\n\tconst header = createPresignedHeader();\n\theader.id = input.documentId;\n\theader.documentType = input.model;\n\tif (input.signing) {\n\t\theader.createdAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.lastModifiedAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.sig = {\n\t\t\tpublicKey: input.signing.publicKey,\n\t\t\tnonce: input.signing.nonce\n\t\t};\n\t}\n\tif (input.slug !== void 0) header.slug = input.slug;\n\tif (!header.slug) header.slug = input.documentId;\n\tif (input.name !== void 0) header.name = input.name;\n\tif (input.branch !== void 0) header.branch = input.branch;\n\tif (input.meta !== void 0) header.meta = input.meta;\n\tif (input.protocolVersions !== void 0) header.protocolVersions = input.protocolVersions;\n\tconst baseState = defaultBaseState();\n\treturn {\n\t\theader,\n\t\toperations: {},\n\t\tstate: baseState,\n\t\tinitialState: baseState,\n\t\tclipboard: []\n\t};\n}\n/**\n* Calculate the next operation index for a specific scope.\n* Each scope maintains its own independent index sequence.\n*\n* Per-scope indexing means:\n* - Each scope (document, global, local, etc.) has independent indexes\n* - Indexes start at 0 for each scope\n* - Different scopes can have operations with the same index value\n*\n* This function uses header.revision which is populated by the cache/storage layer\n* and contains the next available index for each scope. This design avoids requiring\n* the full operation history to be loaded, which is crucial for snapshot-based caching.\n*\n* @param document - The document whose header.revision to inspect\n* @param scope - The scope to calculate the next index for\n* @returns The next available index in the specified scope\n*/\nconst getNextIndexForScope = (document, scope) => {\n\treturn document.header.revision[scope] || 0;\n};\n/**\n* Creates an empty consistency token with no coordinates.\n* Used when a job is registered or fails without writing operations.\n*\n* @returns A consistency token with an empty coordinates array\n*/\nfunction createEmptyConsistencyToken() {\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates: []\n\t};\n}\n/**\n* Creates a consistency token from operations written during job execution.\n* Maps each operation to a consistency coordinate tracking (documentId, scope, branch, operationIndex).\n* If no operations are provided, returns an empty token.\n*\n* @param operationsWithContext - Array of operations with their execution context\n* @returns A consistency token representing all operations written\n*/\nfunction createConsistencyToken(operationsWithContext) {\n\tif (operationsWithContext.length === 0) return createEmptyConsistencyToken();\n\tconst coordinates = [];\n\tfor (let i = 0; i < operationsWithContext.length; i++) {\n\t\tconst opWithContext = operationsWithContext[i];\n\t\tcoordinates.push({\n\t\t\tdocumentId: opWithContext.context.documentId,\n\t\t\tscope: opWithContext.context.scope,\n\t\t\tbranch: opWithContext.context.branch,\n\t\t\toperationIndex: opWithContext.operation.index\n\t\t});\n\t}\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates\n\t};\n}\nfunction createOperation(action, index, skip, context) {\n\treturn {\n\t\tid: deriveOperationId(context.documentId, context.scope, context.branch, action.id),\n\t\tindex,\n\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\thash: \"\",\n\t\tskip,\n\t\taction\n\t};\n}\nfunction updateDocumentRevision(document, scope, operationIndex) {\n\tdocument.header.revision = {\n\t\t...document.header.revision,\n\t\t[scope]: operationIndex + 1\n\t};\n}\nfunction buildSuccessResult(job, operation, documentId, documentType, resultingState, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: true,\n\t\toperations: [operation],\n\t\toperationsWithContext: [{\n\t\t\toperation,\n\t\t\tcontext: {\n\t\t\t\tdocumentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tdocumentType,\n\t\t\t\tresultingState,\n\t\t\t\tordinal: 0\n\t\t\t}\n\t\t}],\n\t\tduration: Date.now() - startTime\n\t};\n}\nfunction buildErrorResult(job, error, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: false,\n\t\terror,\n\t\tduration: Date.now() - startTime\n\t};\n}\n//#endregion\n//#region src/cache/lru/lru-tracker.ts\nvar LRUNode = class {\n\tkey;\n\tprev;\n\tnext;\n\tconstructor(key) {\n\t\tthis.key = key;\n\t\tthis.prev = void 0;\n\t\tthis.next = void 0;\n\t}\n};\nvar LRUTracker = class {\n\tmap;\n\thead;\n\ttail;\n\tconstructor() {\n\t\tthis.map = /* @__PURE__ */ new Map();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\tget size() {\n\t\treturn this.map.size;\n\t}\n\ttouch(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (node) this.moveToFront(node);\n\t\telse this.addToFront(key);\n\t}\n\tevict() {\n\t\tif (!this.tail) return;\n\t\tconst key = this.tail.key;\n\t\tthis.remove(key);\n\t\treturn key;\n\t}\n\tremove(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (!node) return;\n\t\tthis.removeNode(node);\n\t\tthis.map.delete(key);\n\t}\n\tclear() {\n\t\tthis.map.clear();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\taddToFront(key) {\n\t\tconst node = new LRUNode(key);\n\t\tthis.map.set(key, node);\n\t\tif (!this.head) {\n\t\t\tthis.head = node;\n\t\t\tthis.tail = node;\n\t\t} else {\n\t\t\tnode.next = this.head;\n\t\t\tthis.head.prev = node;\n\t\t\tthis.head = node;\n\t\t}\n\t}\n\tmoveToFront(node) {\n\t\tif (node === this.head) return;\n\t\tthis.removeNode(node);\n\t\tnode.prev = void 0;\n\t\tnode.next = this.head;\n\t\tif (this.head) this.head.prev = node;\n\t\tthis.head = node;\n\t\tif (!this.tail) this.tail = node;\n\t}\n\tremoveNode(node) {\n\t\tif (node.prev) node.prev.next = node.next;\n\t\telse this.head = node.next;\n\t\tif (node.next) node.next.prev = node.prev;\n\t\telse this.tail = node.prev;\n\t}\n};\n//#endregion\n//#region src/cache/document-meta-cache.ts\n/**\n* In-memory document metadata cache with LRU eviction.\n*\n* Caches PHDocumentState per (documentId, branch) key. On cache miss,\n* rebuilds from document scope operations. Provides an explicit cross-scope\n* contract for accessing document scope metadata.\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n*/\nvar DocumentMetaCache = class DocumentMetaCache {\n\tcache;\n\tlruTracker;\n\toperationStore;\n\tconfig;\n\tconstructor(operationStore, config) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.config = { maxDocuments: config.maxDocuments };\n\t\tthis.cache = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStore(operationStore) {\n\t\tconst scoped = new DocumentMetaCache(operationStore, this.config);\n\t\tscoped.cache = this.cache;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\tasync getDocumentMeta(documentId, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\tthis.lruTracker.touch(key);\n\t\t\treturn cached;\n\t\t}\n\t\tconst meta = await this.rebuildLatest(documentId, branch, signal);\n\t\tthis.putDocumentMeta(documentId, branch, meta);\n\t\treturn meta;\n\t}\n\tasync rebuildAtRevision(documentId, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn this.rebuildFromOperations(documentId, branch, targetRevision, signal);\n\t}\n\tputDocumentMeta(documentId, branch, meta) {\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tif (!this.cache.has(key) && this.cache.size >= this.config.maxDocuments) {\n\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\tif (evictKey) this.cache.delete(evictKey);\n\t\t}\n\t\tthis.cache.set(key, structuredClone(meta));\n\t\tthis.lruTracker.touch(key);\n\t}\n\tinvalidate(documentId, branch) {\n\t\tlet evicted = 0;\n\t\tif (branch === void 0) {\n\t\t\tfor (const key of this.cache.keys()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = this.makeKey(documentId, branch);\n\t\t\tif (this.cache.has(key)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\tmakeKey(documentId, branch) {\n\t\treturn `${documentId}:${branch}`;\n\t}\n\tasync rebuildLatest(documentId, branch, signal) {\n\t\treturn this.rebuildFromOperations(documentId, branch, void 0, signal);\n\t}\n\tasync rebuildFromOperations(documentId, branch, targetRevision, signal) {\n\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, void 0, signal);\n\t\tif (docScopeOps.results.length === 0) throw new DocumentNotFoundError(documentId);\n\t\tconst createOp = docScopeOps.results[0];\n\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Invalid document: first operation must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\tconst createAction = createOp.action;\n\t\tconst documentType = createAction.input.model;\n\t\tlet document = createDocumentFromAction(createAction);\n\t\tlet documentScopeRevision = 0;\n\t\tfor (const op of docScopeOps.results) {\n\t\t\tif (targetRevision !== void 0 && op.index > targetRevision) break;\n\t\t\tdocumentScopeRevision = op.index;\n\t\t\tif (op.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\tconst upgradeAction = op.action;\n\t\t\t\tdocument = applyUpgradeDocumentAction$1(document, upgradeAction);\n\t\t\t} else if (op.action.type === \"DELETE_DOCUMENT\") document = applyDeleteDocumentAction$1(document, op.action);\n\t\t}\n\t\treturn {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType,\n\t\t\tdocumentScopeRevision: documentScopeRevision + 1\n\t\t};\n\t}\n};\n//#endregion\n//#region src/cache/kysely-operation-index.ts\nvar KyselyOperationIndexTxn = class {\n\tcollections = [];\n\tcollectionMemberships = [];\n\tcollectionRemovals = [];\n\toperations = [];\n\tcreateCollection(collectionId) {\n\t\tthis.collections.push(collectionId);\n\t}\n\taddToCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"addToCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionMemberships.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\tremoveFromCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"removeFromCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionRemovals.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\twrite(operations) {\n\t\tthis.operations.push(...operations);\n\t}\n\tgetCollections() {\n\t\treturn this.collections;\n\t}\n\tgetCollectionMembershipRecords() {\n\t\treturn this.collectionMemberships;\n\t}\n\tgetCollectionRemovals() {\n\t\treturn this.collectionRemovals;\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\nvar KyselyOperationIndex = class KyselyOperationIndex {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyOperationIndex(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tstart() {\n\t\treturn new KyselyOperationIndexTxn();\n\t}\n\tasync commit(txn, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst kyselyTxn = txn;\n\t\tif (this.trx) return this.executeCommit(this.trx, kyselyTxn);\n\t\tlet resultOrdinals = [];\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tresultOrdinals = await this.executeCommit(trx, kyselyTxn);\n\t\t});\n\t\treturn resultOrdinals;\n\t}\n\tasync executeCommit(trx, kyselyTxn) {\n\t\tconst collections = kyselyTxn.getCollections();\n\t\tconst memberships = kyselyTxn.getCollectionMembershipRecords();\n\t\tconst removals = kyselyTxn.getCollectionRemovals();\n\t\tconst operations = kyselyTxn.getOperations();\n\t\tif (collections.length > 0) {\n\t\t\tconst collectionRows = collections.map((collectionId) => ({\n\t\t\t\tdocumentId: collectionId,\n\t\t\t\tcollectionId,\n\t\t\t\tjoinedOrdinal: BigInt(0),\n\t\t\t\tleftOrdinal: null\n\t\t\t}));\n\t\t\tawait trx.insertInto(\"document_collections\").values(collectionRows).onConflict((oc) => oc.doNothing()).execute();\n\t\t}\n\t\tlet operationOrdinals = [];\n\t\tif (operations.length > 0) {\n\t\t\tconst operationRows = operations.map((op) => ({\n\t\t\t\topId: op.id || \"\",\n\t\t\t\tdocumentId: op.documentId,\n\t\t\t\tdocumentType: op.documentType,\n\t\t\t\tscope: op.scope,\n\t\t\t\tbranch: op.branch,\n\t\t\t\ttimestampUtcMs: op.timestampUtcMs,\n\t\t\t\tindex: op.index,\n\t\t\t\tskip: op.skip,\n\t\t\t\thash: op.hash,\n\t\t\t\taction: op.action,\n\t\t\t\tsourceRemote: op.sourceRemote\n\t\t\t}));\n\t\t\toperationOrdinals = (await trx.insertInto(\"operation_index_operations\").values(operationRows).returning(\"ordinal\").execute()).map((row) => row.ordinal);\n\t\t}\n\t\tif (memberships.length > 0) for (const m of memberships) {\n\t\t\tconst ordinal = operationOrdinals[m.operationIndex];\n\t\t\tawait trx.insertInto(\"document_collections\").values({\n\t\t\t\tdocumentId: m.documentId,\n\t\t\t\tcollectionId: m.collectionId,\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t})).execute();\n\t\t}\n\t\tif (removals.length > 0) for (const r of removals) {\n\t\t\tconst ordinal = operationOrdinals[r.operationIndex];\n\t\t\tawait trx.updateTable(\"document_collections\").set({ leftOrdinal: BigInt(ordinal) }).where(\"collectionId\", \"=\", r.collectionId).where(\"documentId\", \"=\", r.documentId).where(\"leftOrdinal\", \"is\", null).execute();\n\t\t}\n\t\treturn operationOrdinals;\n\t}\n\tasync find(collectionId, cursor, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst outerCursor = cursor ?? -1;\n\t\tconst pagingCursorOrdinal = paging?.cursor !== void 0 ? Number.parseInt(paging.cursor, 10) : -1;\n\t\tconst buildBranch = (kind) => {\n\t\t\tlet qb = this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").selectAll(\"oi\").select([\"dc.documentId\", \"dc.collectionId\"]).where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`);\n\t\t\tif (kind === \"joiner\") qb = qb.where(\"dc.joinedOrdinal\", \">\", BigInt(outerCursor)).where(\"oi.ordinal\", \"<=\", outerCursor);\n\t\t\telse qb = qb.where(\"oi.ordinal\", \">\", outerCursor);\n\t\t\tqb = qb.where(\"oi.ordinal\", \">\", pagingCursorOrdinal);\n\t\t\tif (view?.branch) qb = qb.where(\"oi.branch\", \"=\", view.branch);\n\t\t\tif (view?.scopes && view.scopes.length > 0) qb = qb.where(\"oi.scope\", \"in\", view.scopes);\n\t\t\tif (view?.excludeSourceRemote) qb = qb.where(\"oi.sourceRemote\", \"!=\", view.excludeSourceRemote);\n\t\t\treturn qb;\n\t\t};\n\t\tlet unionQuery = buildBranch(\"joiner\").unionAll(buildBranch(\"newOps\")).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.limit) unionQuery = unionQuery.limit(paging.limit + 1);\n\t\tconst rows = await unionQuery.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.find(collectionId, cursor, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync get(documentId, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"ordinal\", \"asc\");\n\t\tif (view?.branch) query = query.where(\"branch\", \"=\", view.branch);\n\t\tif (view?.scopes && view.scopes.length > 0) query = query.where(\"scope\", \"in\", view.scopes);\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tif (paging?.limit) query = query.limit(paging.limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.get(documentId, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync getSinceOrdinal(ordinal, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"ordinal\", \">\", ordinal).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tif (paging?.limit) query = query.limit(paging.limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationWithContext(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.getSinceOrdinal(ordinal, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: {\n\t\t\t\tindex: row.index,\n\t\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\t\thash: row.hash,\n\t\t\t\tskip: row.skip,\n\t\t\t\taction: row.action,\n\t\t\t\tid: row.opId\n\t\t\t},\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.ordinal\n\t\t\t}\n\t\t};\n\t}\n\trowToOperationIndexEntry(row) {\n\t\treturn {\n\t\t\tordinal: row.ordinal,\n\t\t\tdocumentId: row.documentId,\n\t\t\tdocumentType: row.documentType,\n\t\t\tbranch: row.branch,\n\t\t\tscope: row.scope,\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\taction: row.action,\n\t\t\tid: row.opId,\n\t\t\tsourceRemote: row.sourceRemote\n\t\t};\n\t}\n\tasync getLatestTimestampForCollection(collectionId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").select(\"oi.timestampUtcMs\").where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`).orderBy(\"oi.ordinal\", \"desc\").limit(1).executeTakeFirst())?.timestampUtcMs ?? null;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tif (documentIds.length === 0) return {};\n\t\tconst rows = await this.queryExecutor.selectFrom(\"document_collections\").select([\"documentId\", \"collectionId\"]).where(\"documentId\", \"in\", documentIds).where(\"leftOrdinal\", \"is\", null).execute();\n\t\tconst result = {};\n\t\tfor (const row of rows) {\n\t\t\tif (!(row.documentId in result)) result[row.documentId] = [];\n\t\t\tresult[row.documentId].push(row.collectionId);\n\t\t}\n\t\treturn result;\n\t}\n};\n//#endregion\n//#region src/cache/buffer/ring-buffer.ts\n/**\n* RingBuffer is a generic circular buffer implementation that stores a fixed number\n* of items. When the buffer is full, new items overwrite the oldest items.\n*\n* This implementation maintains O(1) time complexity for push operations and provides\n* items in chronological order (oldest to newest) via getAll().\n*\n* @template T - The type of items stored in the buffer\n*/\nvar RingBuffer = class {\n\tbuffer;\n\thead = 0;\n\tsize = 0;\n\tcapacity;\n\tconstructor(capacity) {\n\t\tif (capacity <= 0) throw new Error(\"Ring buffer capacity must be greater than 0\");\n\t\tthis.capacity = capacity;\n\t\tthis.buffer = new Array(capacity);\n\t}\n\t/**\n\t* Adds an item to the buffer. If the buffer is full, overwrites the oldest item.\n\t*\n\t* @param item - The item to add\n\t*/\n\tpush(item) {\n\t\tconst index = (this.head + this.size) % this.capacity;\n\t\tif (this.size < this.capacity) {\n\t\t\tthis.buffer[index] = item;\n\t\t\tthis.size++;\n\t\t} else {\n\t\t\tthis.buffer[this.head] = item;\n\t\t\tthis.head = (this.head + 1) % this.capacity;\n\t\t}\n\t}\n\t/**\n\t* Returns all items in the buffer in chronological order (oldest to newest).\n\t*\n\t* @returns Array of items in insertion order\n\t*/\n\tgetAll() {\n\t\tif (this.size === 0) return [];\n\t\tconst result = [];\n\t\tfor (let i = 0; i < this.size; i++) {\n\t\t\tconst index = (this.head + i) % this.capacity;\n\t\t\tresult.push(this.buffer[index]);\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t* Clears all items from the buffer.\n\t*/\n\tclear() {\n\t\tthis.buffer = new Array(this.capacity);\n\t\tthis.head = 0;\n\t\tthis.size = 0;\n\t}\n\t/**\n\t* Gets the current number of items in the buffer.\n\t*/\n\tget length() {\n\t\treturn this.size;\n\t}\n};\n//#endregion\n//#region src/cache/kysely-write-cache.ts\nfunction extractModuleVersion(doc) {\n\tconst v = doc.state.document.version;\n\treturn v === 0 ? void 0 : v;\n}\n/**\n* In-memory write cache with keyframe persistence for PHDocuments.\n*\n* Caches document snapshots in ring buffers with LRU eviction. On cache miss,\n* rebuilds documents from nearest keyframe or full operation history.\n*\n* **Performance Characteristics:**\n* - Cache hit: O(1) lookup in ring buffer\n* - Cold miss: O(n) where n is total operation count, or O(k) where k is operations since keyframe\n* - Warm miss: O(m) where m is operations since cached revision\n* - Eviction: O(1) for LRU tracking and removal\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n* External synchronization required for concurrent access across multiple executors.\n*\n* **Example:**\n* ```typescript\n* const cache = new KyselyWriteCache(\n* keyframeStore,\n* operationStore,\n* registry,\n* { maxDocuments: 1000, ringBufferSize: 10, keyframeInterval: 10 }\n* );\n*\n* await cache.startup();\n*\n* // Retrieve or rebuild document\n* const doc = await cache.getState(docId, docType, scope, branch, revision);\n*\n* // Cache result after job execution\n* cache.putState(docId, docType, scope, branch, newRevision, updatedDoc);\n*\n* await cache.shutdown();\n* ```\n*/\nvar KyselyWriteCache = class KyselyWriteCache {\n\tstreams;\n\tlruTracker;\n\tkeyframeStore;\n\toperationStore;\n\tregistry;\n\tconfig;\n\tconstructor(keyframeStore, operationStore, registry, config) {\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.operationStore = operationStore;\n\t\tthis.registry = registry;\n\t\tthis.config = {\n\t\t\tmaxDocuments: config.maxDocuments,\n\t\t\tringBufferSize: config.ringBufferSize,\n\t\t\tkeyframeInterval: config.keyframeInterval\n\t\t};\n\t\tthis.streams = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStores(operationStore, keyframeStore) {\n\t\tconst scoped = new KyselyWriteCache(keyframeStore, operationStore, this.registry, this.config);\n\t\tscoped.streams = this.streams;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\t/**\n\t* Initializes the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Shuts down the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Retrieves document state at a specific revision from cache or rebuilds it.\n\t*\n\t* Cache hit path: Returns cached snapshot if available (O(1))\n\t* Warm miss path: Rebuilds from cached base revision + incremental ops\n\t* Cold miss path: Rebuilds from keyframe or from scratch using all operations\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param targetRevision - The target revision, or undefined for newest\n\t* @param signal - Optional abort signal to cancel the operation\n\t* @returns The document at the target revision\n\t* @throws {Error} \"Operation aborted\" if signal is aborted\n\t* @throws {ModuleNotFoundError} If document type not registered in registry\n\t* @throws {Error} \"Failed to rebuild document\" if operation store fails\n\t* @throws {Error} If reducer throws during operation application\n\t* @throws {Error} If document serialization fails\n\t*/\n\tasync getState(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.streams.get(streamKey);\n\t\tif (stream) {\n\t\t\tconst snapshots = stream.ringBuffer.getAll();\n\t\t\tif (targetRevision === void 0) {\n\t\t\t\tif (snapshots.length > 0) {\n\t\t\t\t\tconst newest = snapshots[snapshots.length - 1];\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn newest.document;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst exactMatch = snapshots.find((s) => s.revision === targetRevision);\n\t\t\t\tif (exactMatch) {\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn exactMatch.document;\n\t\t\t\t}\n\t\t\t\tconst newestOlder = this.findNearestOlderSnapshot(snapshots, targetRevision);\n\t\t\t\tif (newestOlder) {\n\t\t\t\t\tconst document = await this.warmMissRebuild(newestOlder.document, newestOlder.revision, documentId, scope, branch, targetRevision, signal);\n\t\t\t\t\tthis.putState(documentId, scope, branch, targetRevision, document);\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn document;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst document = await this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tlet revision = targetRevision;\n\t\tif (revision === void 0) revision = document.header.revision[scope] || 0;\n\t\tthis.putState(documentId, scope, branch, revision, document);\n\t\treturn document;\n\t}\n\t/**\n\t* Stores a document snapshot in the cache at a specific revision.\n\t*\n\t* The cached document is a shallow copy of the input with its operation history\n\t* truncated to the last operation per scope and its clipboard cleared. This keeps\n\t* memory use and copy costs constant regardless of operation count. Consumers of\n\t* getState() must not rely on the full operation history being present; the only\n\t* guaranteed invariant is that operations[scope].at(-1) reflects the latest\n\t* operation index for each scope.\n\t*\n\t* Updates LRU tracker and may evict least recently used stream if at capacity.\n\t* Asynchronously persists keyframes at configured intervals (fire-and-forget).\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param revision - The revision number\n\t* @param document - The document to cache\n\t* @throws {Error} If document serialization fails\n\t*/\n\tputState(documentId, scope, branch, revision, document) {\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.getOrCreateStream(streamKey);\n\t\tconst snapshot = {\n\t\t\trevision,\n\t\t\tdocument: {\n\t\t\t\t...document,\n\t\t\t\toperations: Object.fromEntries(Object.entries(document.operations).map(([k, ops]) => [k, ops.length ? [ops.at(-1)] : []])),\n\t\t\t\tclipboard: []\n\t\t\t}\n\t\t};\n\t\tstream.ringBuffer.push(snapshot);\n\t\tif (this.isKeyframeRevision(revision)) this.keyframeStore.putKeyframe(documentId, scope, branch, revision, {\n\t\t\t...document,\n\t\t\toperations: {},\n\t\t\tclipboard: []\n\t\t}).catch((err) => {\n\t\t\tconsole.error(`Failed to persist keyframe ${documentId}@${revision}:`, err);\n\t\t});\n\t}\n\t/**\n\t* Invalidates cached document streams.\n\t*\n\t* Supports three invalidation scopes:\n\t* - Document-level: invalidate(documentId) - removes all streams for document\n\t* - Scope-level: invalidate(documentId, scope) - removes all branches for scope\n\t* - Stream-level: invalidate(documentId, scope, branch) - removes specific stream\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - Optional scope to narrow invalidation\n\t* @param branch - Optional branch to narrow invalidation (requires scope)\n\t* @returns The number of streams evicted\n\t*/\n\tinvalidate(documentId, scope, branch) {\n\t\tlet evicted = 0;\n\t\tif (scope === void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:${scope}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch !== void 0) {\n\t\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\t\tif (this.streams.has(key)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\t/**\n\t* Clears the entire cache, removing all cached document streams.\n\t* Resets LRU tracking state. This operation always succeeds.\n\t*/\n\tclear() {\n\t\tthis.streams.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\t/**\n\t* Retrieves a specific stream for a document. Exposed on the implementation\n\t* for testing, but not on the interface.\n\t*\n\t* @internal\n\t*/\n\tgetStream(documentId, scope, branch) {\n\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\treturn this.streams.get(key);\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (targetRevision === Number.MAX_SAFE_INTEGER || targetRevision <= 0) return;\n\t\treturn this.keyframeStore.findNearestKeyframe(documentId, scope, branch, targetRevision, signal);\n\t}\n\tasync coldMissRebuild(documentId, scope, branch, targetRevision, signal) {\n\t\tconst effectiveTargetRevision = targetRevision || Number.MAX_SAFE_INTEGER;\n\t\tconst keyframe = await this.findNearestKeyframe(documentId, scope, branch, effectiveTargetRevision, signal);\n\t\tlet document;\n\t\tlet startRevision;\n\t\tlet documentType;\n\t\tconst validatedUpgrades = [];\n\t\tif (keyframe) {\n\t\t\tdocument = keyframe.document;\n\t\t\tstartRevision = keyframe.revision;\n\t\t\tdocumentType = keyframe.document.header.documentType;\n\t\t\tconst docScopeOpsAfterKeyframe = await this.operationStore.getSince(documentId, \"document\", branch, keyframe.revision, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOpsAfterKeyframe.results) if (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\tlet upgradePath;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t}\n\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t});\n\t\t\t\t\tdocument = applyUpgradeDocumentAction(document, upgradeAction, upgradePath);\n\t\t\t\t}\n\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\") applyDeleteDocumentAction(document, operation.action);\n\t\t} else {\n\t\t\tstartRevision = -1;\n\t\t\tconst createOpResult = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: 1\n\t\t\t}, signal);\n\t\t\tif (createOpResult.results.length === 0) throw new Error(`Failed to rebuild document ${documentId}: no CREATE_DOCUMENT operation found in document scope`);\n\t\t\tconst createOp = createOpResult.results[0];\n\t\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Failed to rebuild document ${documentId}: first operation in document scope must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\t\tconst documentCreateAction = createOp.action;\n\t\t\tdocumentType = documentCreateAction.input.model;\n\t\t\tif (!documentType) throw new Error(`Failed to rebuild document ${documentId}: CREATE_DOCUMENT action missing model in input`);\n\t\t\tdocument = createDocumentFromAction(documentCreateAction);\n\t\t\tlet docModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, 0, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOps.results) {\n\t\t\t\tif (operation.index === 0) continue;\n\t\t\t\tif (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\t\tlet upgradePath;\n\t\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tdocument = applyUpgradeDocumentAction(document, upgradeAction, upgradePath);\n\t\t\t\t\tdocModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\") applyDeleteDocumentAction(document, operation.action);\n\t\t\t\telse {\n\t\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\t\tdocument = docModule.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst moduleCache = /* @__PURE__ */ new Map();\n\t\tconst getModuleCached = (version) => {\n\t\t\tconst key = version ?? 0;\n\t\t\tlet mod = moduleCache.get(key);\n\t\t\tif (!mod) {\n\t\t\t\tmod = this.registry.getModule(documentType, version);\n\t\t\t\tmoduleCache.set(key, mod);\n\t\t\t}\n\t\t\treturn mod;\n\t\t};\n\t\tlet cursor = void 0;\n\t\tconst pageSize = 100;\n\t\tlet hasMorePages;\n\t\tdo {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst paging = {\n\t\t\t\tcursor: cursor || \"0\",\n\t\t\t\tlimit: pageSize\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst result = await this.operationStore.getSince(documentId, scope, branch, startRevision, void 0, paging, signal);\n\t\t\t\tfor (const operation of result.results) {\n\t\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\t\tconst moduleVersion = this.resolveModuleVersionForOp(operation.index, operation.timestampUtcMs, scope, validatedUpgrades, extractModuleVersion(document));\n\t\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\t\tdocument = getModuleCached(moduleVersion).reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst reachedTarget = targetRevision !== void 0 && result.results.some((op) => op.index >= targetRevision);\n\t\t\t\thasMorePages = Boolean(result.nextCursor) && !reachedTarget;\n\t\t\t\tif (hasMorePages) cursor = result.nextCursor;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t}\n\t\t} while (hasMorePages);\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\t/**\n\t* Resolves which module version to use for a given operation in phase 2.\n\t*\n\t* Uses the validated-upgrade boundary rules from D7:\n\t* - If `input.revision` is present: op.index < revision[scope] → before the upgrade boundary\n\t* - Otherwise: timestamp fallback\n\t* - Falls back to final module version when neither is decidable\n\t*/\n\tresolveModuleVersionForOp(opIndex, opTimestamp, scope, validatedUpgrades, finalVersion) {\n\t\tif (validatedUpgrades.length === 0) return finalVersion;\n\t\tlet currentVersion = validatedUpgrades[0]?.fromVersion;\n\t\tfor (const upgrade of validatedUpgrades) {\n\t\t\tlet beforeUpgrade;\n\t\t\tif (upgrade.revision !== void 0) beforeUpgrade = opIndex < (upgrade.revision[scope] ?? 0);\n\t\t\telse beforeUpgrade = opTimestamp < upgrade.timestampUtcMs;\n\t\t\tif (beforeUpgrade) return currentVersion;\n\t\t\tcurrentVersion = upgrade.toVersion;\n\t\t}\n\t\treturn currentVersion;\n\t}\n\tasync warmMissRebuild(baseDocument, baseRevision, documentId, scope, branch, targetRevision, signal) {\n\t\tconst documentType = baseDocument.header.documentType;\n\t\tconst docScopeNextIndex = baseDocument.header.revision[\"document\"] ?? 0;\n\t\tif ((await this.operationStore.getSince(documentId, \"document\", branch, docScopeNextIndex - 1, void 0, void 0, signal)).results.some((op) => op.action.type === \"UPGRADE_DOCUMENT\")) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tconst module = this.registry.getModule(documentType, extractModuleVersion(baseDocument));\n\t\tlet document = baseDocument;\n\t\ttry {\n\t\t\tconst pagedResults = await this.operationStore.getSince(documentId, scope, branch, baseRevision, void 0, void 0, signal);\n\t\t\tfor (const operation of pagedResults.results) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\tdocument = module.reducer(document, operation.action, void 0, {\n\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\tprotocolVersion\n\t\t\t\t});\n\t\t\t\tif (targetRevision !== void 0 && operation.index === targetRevision) break;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t}\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\tfindNearestOlderSnapshot(snapshots, targetRevision) {\n\t\tlet nearest = void 0;\n\t\tfor (const snapshot of snapshots) if (snapshot.revision < targetRevision) {\n\t\t\tif (!nearest || snapshot.revision > nearest.revision) nearest = snapshot;\n\t\t}\n\t\treturn nearest;\n\t}\n\tmakeStreamKey(documentId, scope, branch) {\n\t\treturn `${documentId}:${scope}:${branch}`;\n\t}\n\tgetOrCreateStream(key) {\n\t\tlet stream = this.streams.get(key);\n\t\tif (!stream) {\n\t\t\tif (this.streams.size >= this.config.maxDocuments) {\n\t\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\t\tif (evictKey) this.streams.delete(evictKey);\n\t\t\t}\n\t\t\tstream = {\n\t\t\t\tkey,\n\t\t\t\tringBuffer: new RingBuffer(this.config.ringBufferSize)\n\t\t\t};\n\t\t\tthis.streams.set(key, stream);\n\t\t}\n\t\tthis.lruTracker.touch(key);\n\t\treturn stream;\n\t}\n\tisKeyframeRevision(revision) {\n\t\treturn revision > 0 && revision % this.config.keyframeInterval === 0;\n\t}\n};\n//#endregion\n//#region src/events/event-bus.ts\nvar EventBus = class {\n\teventTypeToSubscribers = /* @__PURE__ */ new Map();\n\tsubscribe(type, subscriber) {\n\t\tlet list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list) {\n\t\t\tlist = [];\n\t\t\tthis.eventTypeToSubscribers.set(type, list);\n\t\t}\n\t\tlist.push(subscriber);\n\t\tlet done = false;\n\t\treturn () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tconst arr = this.eventTypeToSubscribers.get(type);\n\t\t\tif (!arr) return;\n\t\t\tconst idx = arr.indexOf(subscriber);\n\t\t\tif (idx !== -1) arr.splice(idx, 1);\n\t\t\tif (arr.length === 0) this.eventTypeToSubscribers.delete(type);\n\t\t};\n\t}\n\tasync emit(type, data) {\n\t\tconst list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list || list.length === 0) return;\n\t\tconst snapshot = list.slice();\n\t\tconst errors = [];\n\t\tfor (const fn of snapshot) try {\n\t\t\tawait Promise.resolve(fn(type, data));\n\t\t} catch (err) {\n\t\t\terrors.push(err);\n\t\t}\n\t\tif (errors.length > 0) throw new EventBusAggregateError(errors);\n\t}\n};\n//#endregion\n//#region src/executor/execution-scope.ts\nvar DefaultExecutionScope = class {\n\tconstructor(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn fn({\n\t\t\toperationStore: this.operationStore,\n\t\t\toperationIndex: this.operationIndex,\n\t\t\twriteCache: this.writeCache,\n\t\t\tdocumentMetaCache: this.documentMetaCache,\n\t\t\tcollectionMembershipCache: this.collectionMembershipCache\n\t\t});\n\t}\n};\nvar KyselyExecutionScope = class {\n\tconstructor(db, operationStore, operationIndex, keyframeStore, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.db = db;\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn this.db.transaction().execute(async (trx) => {\n\t\t\tconst scopedOperationStore = this.operationStore.withTransaction(trx);\n\t\t\tconst scopedOperationIndex = this.operationIndex.withTransaction(trx);\n\t\t\tconst scopedKeyframeStore = this.keyframeStore.withTransaction(trx);\n\t\t\treturn fn({\n\t\t\t\toperationStore: scopedOperationStore,\n\t\t\t\toperationIndex: scopedOperationIndex,\n\t\t\t\twriteCache: this.writeCache.withScopedStores(scopedOperationStore, scopedKeyframeStore),\n\t\t\t\tdocumentMetaCache: this.documentMetaCache.withScopedStore(scopedOperationStore),\n\t\t\t\tcollectionMembershipCache: this.collectionMembershipCache.withScopedIndex(scopedOperationIndex)\n\t\t\t});\n\t\t});\n\t}\n};\n//#endregion\n//#region src/utils/reshuffle.ts\nconst STRICT_ORDER_ACTION_TYPES = new Set([\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\",\n\t\"ADD_FOLDER\",\n\t\"UPDATE_FOLDER\",\n\t\"REMOVE_FOLDER\"\n]);\n/**\n* Reshuffles operations by timestamp, then applies deterministic tie-breaking.\n* Used for merging concurrent operations from different branches.\n*\n* For strict document-structure actions (e.g., CREATE_DOCUMENT/UPGRADE_DOCUMENT),\n* logical index (index - skip) is prioritized to preserve causal replay order.\n*\n* For other actions, action ID is prioritized to ensure a canonical cross-reactor order\n* for concurrent operations that may have diverged local indices due to prior reshuffles.\n* Logical index and operation ID are then used as deterministic tie-breakers.\n*\n* Example:\n* [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]\n* GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]\n* Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]\n* Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n* merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n*/\nfunction reshuffleByTimestamp(startIndex, opsA, opsB) {\n\treturn [...opsA, ...opsB].sort((a, b) => {\n\t\tconst timestampDiff = new Date(a.timestampUtcMs).getTime() - new Date(b.timestampUtcMs).getTime();\n\t\tif (timestampDiff !== 0) return timestampDiff;\n\t\tconst shouldPrioritizeLogicalIndex = STRICT_ORDER_ACTION_TYPES.has(a.action?.type ?? \"\") || STRICT_ORDER_ACTION_TYPES.has(b.action?.type ?? \"\");\n\t\tconst logicalIndexDiff = a.index - a.skip - (b.index - b.skip);\n\t\tif (shouldPrioritizeLogicalIndex) {\n\t\t\tif (logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\t}\n\t\tconst actionIdDiff = (a.action?.id ?? \"\").localeCompare(b.action?.id ?? \"\");\n\t\tif (actionIdDiff !== 0) return actionIdDiff;\n\t\tif (!shouldPrioritizeLogicalIndex && logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\treturn a.id.localeCompare(b.id);\n\t}).map((op, i) => ({\n\t\t...op,\n\t\tindex: startIndex.index + i,\n\t\tskip: i === 0 ? startIndex.skip : 0\n\t}));\n}\n//#endregion\n//#region src/cache/operation-index-types.ts\nconst DRIVE_COLLECTION_PREFIX = \"drive.\";\n/**\n* Identifies the collection a remote synchronizes. Collections are drive-level\n* abstractions (document-drive and reactor-drive), so a collection id is the\n* drive document id plus the branch it scopes to rather than an opaque string.\n*\n* The canonical string form (`drive.${branch}.${driveId}`) is produced only by\n* `key` and parsed only by `fromKey`; that string is the wire and storage\n* representation and is byte-for-byte identical to the legacy\n* `driveCollectionId(branch, driveId)` output, so existing `document_collections`\n* rows and persisted remotes remain valid without migration.\n*/\nvar DriveCollectionId = class DriveCollectionId {\n\tconstructor(driveId, branch) {\n\t\tthis.driveId = driveId;\n\t\tthis.branch = branch;\n\t}\n\tstatic forDrive(driveId, branch = \"main\") {\n\t\treturn new DriveCollectionId(driveId, branch);\n\t}\n\t/**\n\t* The single deserializer for the wire/storage form. `branch` may contain\n\t* dots, while `driveId` is a dot-free document id, so the drive id is the\n\t* final dot-delimited segment.\n\t*/\n\tstatic fromKey(key) {\n\t\tif (!key.startsWith(DRIVE_COLLECTION_PREFIX)) throw new Error(`Unsupported collection id: ${key}`);\n\t\tconst rest = key.slice(6);\n\t\tconst lastDot = rest.lastIndexOf(\".\");\n\t\tif (lastDot === -1 || lastDot === rest.length - 1) throw new Error(`Malformed drive collection id: ${key}`);\n\t\treturn new DriveCollectionId(rest.slice(lastDot + 1), rest.slice(0, lastDot));\n\t}\n\tget key() {\n\t\treturn `${DRIVE_COLLECTION_PREFIX}${this.branch}.${this.driveId}`;\n\t}\n\ttoString() {\n\t\treturn this.key;\n\t}\n\tequals(other) {\n\t\treturn this.driveId === other.driveId && this.branch === other.branch;\n\t}\n};\n//#endregion\n//#region src/executor/document-action-handler.ts\nvar DocumentActionHandler = class {\n\tconstructor(registry, logger, driveContainerTypes) {\n\t\tthis.registry = registry;\n\t\tthis.logger = logger;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t}\n\tasync execute(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tswitch (action.type) {\n\t\t\tcase \"CREATE_DOCUMENT\": return this.executeCreate(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal);\n\t\t\tcase \"DELETE_DOCUMENT\": return this.executeDelete(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"UPGRADE_DOCUMENT\": return this.executeUpgrade(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal);\n\t\t\tcase \"ADD_RELATIONSHIP\": return this.executeAddRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"REMOVE_RELATIONSHIP\": return this.executeRemoveRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"UPDATE_RELATIONSHIP\": return this.executeUpdateRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tdefault: return buildErrorResult(job, /* @__PURE__ */ new Error(`Unknown document action type: ${action.type}`), startTime);\n\t\t}\n\t}\n\tasync executeCreate(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tif (job.scope !== \"document\") return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`CREATE_DOCUMENT must be in \"document\" scope, got \"${job.scope}\"`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst document = createDocumentFromAction(action);\n\t\tlet operation = createOperation(action, 0, skip, {\n\t\t\tdocumentId: document.header.id,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\t...document.state\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(document.header.id, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(document.header.id, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: document.header.id,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (this.driveContainerTypes.has(document.header.documentType)) {\n\t\t\tconst collectionId = DriveCollectionId.forDrive(document.header.id, job.branch).key;\n\t\t\tindexTxn.createCollection(collectionId);\n\t\t\tindexTxn.addToCollection(collectionId, document.header.id);\n\t\t}\n\t\tstores.documentMetaCache.putDocumentMeta(document.header.id, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, document.header.id, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeDelete(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"DELETE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document before deletion: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tlet operation = createOperation(action, getNextIndexForScope(document, job.scope), 0, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tapplyDeleteDocumentAction$1(document, action);\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\tdocument: document.state.document\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(documentId, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeUpgrade(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"UPGRADE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tconst fromVersion = input.fromVersion;\n\t\tconst toVersion = input.toVersion;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tconst nextIndex = getNextIndexForScope(document, job.scope);\n\t\tlet upgradePath;\n\t\tif (fromVersion > 0 && fromVersion < toVersion) try {\n\t\t\tupgradePath = this.registry.computeUpgradePath(document.header.documentType, fromVersion, toVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (fromVersion === toVersion && fromVersion > 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\ttry {\n\t\t\tdocument = applyUpgradeDocumentAction$1(document, action, upgradePath);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, nextIndex, skip, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\t...document.state\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(documentId, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\texecuteAddRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"ADD_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, (input) => input.sourceId === input.targetId ? /* @__PURE__ */ new Error(\"ADD_RELATIONSHIP: sourceId and targetId cannot be the same (self-relationships not allowed)\") : null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;\n\t\t\t\ttxn.addToCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteRemoveRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"REMOVE_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;\n\t\t\t\ttxn.removeFromCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteUpdateRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"UPDATE_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, null, null);\n\t}\n\tasync withRelationshipAction(actionTypeName, job, action, startTime, indexTxn, stores, sourceRemote, signal, preValidate, postWrite) {\n\t\tif (job.scope !== \"document\") return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} must be in \"document\" scope, got \"${job.scope}\"`), startTime);\n\t\tconst input = action.input;\n\t\tif (!input.sourceId || !input.targetId || !input.relationshipType) return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} action requires sourceId, targetId, and relationshipType in input`), startTime);\n\t\tif (preValidate !== null) {\n\t\t\tconst validationError = preValidate(input);\n\t\t\tif (validationError !== null) return buildErrorResult(job, validationError, startTime);\n\t\t}\n\t\tlet sourceDoc;\n\t\ttry {\n\t\t\tsourceDoc = await stores.writeCache.getState(input.sourceId, \"document\", job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName}: source document ${input.sourceId} not found: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, getNextIndexForScope(sourceDoc, job.scope), 0, {\n\t\t\tdocumentId: input.sourceId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst writeResult = await this.writeOperationToStore(input.sourceId, sourceDoc.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tsourceDoc.header.lastModifiedAtUtcIso = operation.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString();\n\t\tupdateDocumentRevision(sourceDoc, job.scope, operation.index);\n\t\tsourceDoc.operations = {\n\t\t\t...sourceDoc.operations,\n\t\t\t[job.scope]: [...sourceDoc.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tconst scopeState = sourceDoc.state[job.scope];\n\t\tconst resultingStateObj = {\n\t\t\theader: structuredClone(sourceDoc.header),\n\t\t\t[job.scope]: scopeState === void 0 ? {} : structuredClone(scopeState)\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tstores.writeCache.putState(input.sourceId, job.scope, job.branch, operation.index, sourceDoc);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: input.sourceId,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (postWrite !== null) postWrite({\n\t\t\tindexTxn,\n\t\t\tstores,\n\t\t\tsourceDoc,\n\t\t\tinput,\n\t\t\tjob\n\t\t});\n\t\tstores.documentMetaCache.putDocumentMeta(input.sourceId, job.branch, {\n\t\t\tstate: sourceDoc.state.document,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, input.sourceId, sourceDoc.header.documentType, resultingState, startTime);\n\t}\n\tasync writeOperationToStore(documentId, documentType, scope, branch, operation, job, startTime, stores, signal) {\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(documentId, documentType, scope, branch, operation.index, (txn) => {\n\t\t\t\ttxn.addOperations(operation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error writing @Operation to IOperationStore: @Error\", operation, error);\n\t\t\tstores.writeCache.invalidate(documentId, scope, branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${error instanceof Error ? error.message : String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\treturn storedOperations;\n\t}\n};\n//#endregion\n//#region src/executor/signature-verifier.ts\nvar SignatureVerifier = class {\n\tconstructor(verifier) {\n\t\tthis.verifier = verifier;\n\t}\n\tasync verifyActions(documentId, branch, actions) {\n\t\tif (!this.verifier) return;\n\t\tfor (const action of actions) {\n\t\t\tconst signer = action.context?.signer;\n\t\t\tif (!signer) continue;\n\t\t\tif (signer.signatures.length === 0) throw new InvalidSignatureError(documentId, `Action ${action.id} has signer but no signatures`);\n\t\t\tconst publicKey = signer.app.key;\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tconst tempOperation = {\n\t\t\t\t\tid: deriveOperationId(documentId, action.scope, branch, action.id),\n\t\t\t\t\tindex: 0,\n\t\t\t\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\t\thash: \"\",\n\t\t\t\t\tskip: 0,\n\t\t\t\t\taction\n\t\t\t\t};\n\t\t\t\tisValid = await this.verifier(tempOperation, publicKey);\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow new InvalidSignatureError(documentId, `Action ${action.id} verification failed: ${errorMessage}`);\n\t\t\t}\n\t\t\tif (!isValid) throw new InvalidSignatureError(documentId, `Action ${action.id} signature verification returned false`);\n\t\t}\n\t}\n\tasync verifyOperations(documentId, operations) {\n\t\tif (!this.verifier) return;\n\t\tfor (let i = 0; i < operations.length; i++) {\n\t\t\tconst operation = operations[i];\n\t\t\tconst signer = operation.action.context?.signer;\n\t\t\tif (!signer) continue;\n\t\t\tif (signer.signatures.length === 0) throw new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} has signer but no signatures`);\n\t\t\tconst publicKey = signer.app.key;\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tisValid = await this.verifier(operation, publicKey);\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} verification failed: ${errorMessage}`);\n\t\t\t}\n\t\t\tif (!isValid) throw new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} signature verification returned false`);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/executor/simple-job-executor.ts\nconst MAX_SKIP_THRESHOLD = 1e3;\nconst ISO_TIMESTAMP_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/;\nfunction isValidISOTimestamp(value) {\n\tif (!ISO_TIMESTAMP_REGEX.test(value)) return false;\n\treturn !isNaN(new Date(value).getTime());\n}\nconst documentScopeActions = [\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\"\n];\n/**\n* Simple job executor that processes a job by applying actions through document model reducers.\n*/\nvar SimpleJobExecutor = class {\n\tconfig;\n\tsignatureVerifierModule;\n\tdocumentActionHandler;\n\texecutionScope;\n\tconstructor(logger, registry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, driveContainerTypes, config, signatureVerifier, executionScope) {\n\t\tthis.logger = logger;\n\t\tthis.registry = registry;\n\t\tthis.operationStore = operationStore;\n\t\tthis.eventBus = eventBus;\n\t\tthis.writeCache = writeCache;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.config = {\n\t\t\tmaxSkipThreshold: config.maxSkipThreshold ?? MAX_SKIP_THRESHOLD,\n\t\t\tmaxConcurrency: config.maxConcurrency ?? 1,\n\t\t\tjobTimeoutMs: config.jobTimeoutMs ?? 3e4,\n\t\t\tretryBaseDelayMs: config.retryBaseDelayMs ?? 100,\n\t\t\tretryMaxDelayMs: config.retryMaxDelayMs ?? 5e3,\n\t\t\tyieldDeadlineMs: config.yieldDeadlineMs ?? 50\n\t\t};\n\t\tthis.signatureVerifierModule = new SignatureVerifier(signatureVerifier);\n\t\tthis.documentActionHandler = new DocumentActionHandler(registry, logger, driveContainerTypes);\n\t\tthis.executionScope = executionScope ?? new DefaultExecutionScope(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache);\n\t}\n\t/**\n\t* Execute a single job by applying all its actions through the appropriate reducers.\n\t* Actions are processed sequentially in order.\n\t*/\n\tasync executeJob(job, signal) {\n\t\tconst startTime = Date.now();\n\t\tconst touchedCacheEntries = [];\n\t\tlet pendingEvent;\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.executionScope.run(async (stores) => {\n\t\t\t\tconst indexTxn = stores.operationIndex.start();\n\t\t\t\tif (job.kind === \"load\") {\n\t\t\t\t\tconst loadResult = await this.executeLoadJob(job, startTime, indexTxn, stores, signal);\n\t\t\t\t\tif (loadResult.success && loadResult.operationsWithContext) {\n\t\t\t\t\t\tfor (const owc of loadResult.operationsWithContext) touchedCacheEntries.push({\n\t\t\t\t\t\t\tdocumentId: owc.context.documentId,\n\t\t\t\t\t\t\tscope: owc.context.scope,\n\t\t\t\t\t\t\tbranch: owc.context.branch\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\t\t\tfor (let i = 0; i < loadResult.operationsWithContext.length; i++) loadResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\t\t\tconst collectionMemberships = loadResult.operationsWithContext.length > 0 ? await this.getCollectionMembershipsForOperations(loadResult.operationsWithContext, stores) : {};\n\t\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\t\toperations: loadResult.operationsWithContext,\n\t\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn loadResult;\n\t\t\t\t}\n\t\t\t\tconst actionResult = await this.processActions(job, job.actions, startTime, indexTxn, stores, void 0, void 0, \"\", signal);\n\t\t\t\tif (!actionResult.success) return {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: actionResult.error,\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t\tif (actionResult.operationsWithContext.length > 0) for (const owc of actionResult.operationsWithContext) touchedCacheEntries.push({\n\t\t\t\t\tdocumentId: owc.context.documentId,\n\t\t\t\t\tscope: owc.context.scope,\n\t\t\t\t\tbranch: owc.context.branch\n\t\t\t\t});\n\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\tif (actionResult.operationsWithContext.length > 0) {\n\t\t\t\t\tfor (let i = 0; i < actionResult.operationsWithContext.length; i++) actionResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\t\tconst collectionMemberships = await this.getCollectionMembershipsForOperations(actionResult.operationsWithContext, stores);\n\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\toperations: actionResult.operationsWithContext,\n\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\toperations: actionResult.generatedOperations,\n\t\t\t\t\toperationsWithContext: actionResult.operationsWithContext,\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tfor (const entry of touchedCacheEntries) {\n\t\t\t\tthis.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);\n\t\t\t\tthis.documentMetaCache.invalidate(entry.documentId, entry.branch);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (pendingEvent) this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY, pendingEvent).catch((error) => {\n\t\t\tthis.logger.error(\"Failed to emit JOB_WRITE_READY event: @Event : @Error\", pendingEvent, error);\n\t\t});\n\t\treturn result;\n\t}\n\tasync getCollectionMembershipsForOperations(operations, stores) {\n\t\tconst documentIds = [...new Set(operations.map((op) => op.context.documentId))];\n\t\treturn stores.collectionMembershipCache.getCollectionsForDocuments(documentIds);\n\t}\n\tasync processActions(job, actions, startTime, indexTxn, stores, skipValues, sourceOperations, sourceRemote = \"\", signal) {\n\t\tconst generatedOperations = [];\n\t\tconst operationsWithContext = [];\n\t\ttry {\n\t\t\tawait this.signatureVerifierModule.verifyActions(job.documentId, job.branch, actions);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t};\n\t\t}\n\t\tfor (const action of actions) if (action.timestampUtcMs && !isValidISOTimestamp(action.timestampUtcMs)) return {\n\t\t\tsuccess: false,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext,\n\t\t\terror: /* @__PURE__ */ new Error(`Invalid timestamp \"${action.timestampUtcMs}\" on action ${action.type} (id: ${action.id})`)\n\t\t};\n\t\tlet lastYield = performance.now();\n\t\tfor (let actionIndex = 0; actionIndex < actions.length; actionIndex++) {\n\t\t\tconst action = actions[actionIndex];\n\t\t\tconst skip = skipValues?.[actionIndex] ?? 0;\n\t\t\tconst sourceOperation = sourceOperations?.[actionIndex];\n\t\t\tconst result = documentScopeActions.includes(action.type) ? await this.documentActionHandler.execute(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal) : await this.executeRegularAction(job, action, startTime, indexTxn, stores, skip, sourceOperation, sourceRemote, signal);\n\t\t\tconst error = this.accumulateResultOrReturnError(result, generatedOperations, operationsWithContext);\n\t\t\tif (error !== null) return {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error.error\n\t\t\t};\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (signal?.aborted) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\tgeneratedOperations,\n\t\t\t\t\toperationsWithContext,\n\t\t\t\t\terror: /* @__PURE__ */ new Error(\"Aborted\")\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext\n\t\t};\n\t}\n\tasync executeRegularAction(job, action, startTime, indexTxn, stores, skip = 0, sourceOperation, sourceRemote = \"\", signal) {\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (docMeta.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tif (isUndoRedo(action) || action.type === \"PRUNE\" || action.type === \"NOOP\" && skip > 0) stores.writeCache.invalidate(job.documentId, job.scope, job.branch);\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet module;\n\t\ttry {\n\t\t\tconst moduleVersion = docMeta.state.version === 0 ? void 0 : docMeta.state.version;\n\t\t\tmodule = this.registry.getModule(document.header.documentType, moduleVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet updatedDocument;\n\t\ttry {\n\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\tconst reducerOptions = sourceOperation ? {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\treplayOptions: { operation: sourceOperation },\n\t\t\t\tprotocolVersion\n\t\t\t} : {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tprotocolVersion\n\t\t\t};\n\t\t\tupdatedDocument = module.reducer(document, action, void 0, reducerOptions);\n\t\t} catch (error) {\n\t\t\tconst contextMessage = `Failed to apply action to document:\\n Action type: ${action.type}\\n Document ID: ${job.documentId}\\n Document type: ${document.header.documentType}\\n Scope: ${job.scope}\\n Original error: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\tconst enhancedError = new Error(contextMessage);\n\t\t\tif (error instanceof Error && error.stack) enhancedError.stack = `${contextMessage}\\n\\nOriginal stack trace:\\n${error.stack}`;\n\t\t\treturn buildErrorResult(job, enhancedError, startTime);\n\t\t}\n\t\tconst scope = job.scope;\n\t\tconst operations = updatedDocument.operations[scope];\n\t\tif (operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"No operation generated from action\"), startTime);\n\t\tconst newOperation = operations[operations.length - 1];\n\t\tif (!isUndoRedo(action)) newOperation.skip = skip;\n\t\tconst resultingState = JSON.stringify({\n\t\t\t...updatedDocument.state,\n\t\t\theader: updatedDocument.header\n\t\t});\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(job.documentId, document.header.documentType, scope, job.branch, newOperation.index, (txn) => {\n\t\t\t\ttxn.addOperations(newOperation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error writing @Operation to IOperationStore: @Error\", newOperation, error);\n\t\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${error instanceof Error ? error.message : String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst storedOperation = storedOperations[0];\n\t\tupdatedDocument.header.revision = {\n\t\t\t...updatedDocument.header.revision,\n\t\t\t[scope]: storedOperation.index + 1\n\t\t};\n\t\tstores.writeCache.putState(job.documentId, scope, job.branch, storedOperation.index, updatedDocument);\n\t\tindexTxn.write([{\n\t\t\t...storedOperation,\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [storedOperation],\n\t\t\toperationsWithContext: [{\n\t\t\t\toperation: storedOperation,\n\t\t\t\tcontext: {\n\t\t\t\t\tdocumentId: job.documentId,\n\t\t\t\t\tscope,\n\t\t\t\t\tbranch: job.branch,\n\t\t\t\t\tdocumentType: document.header.documentType,\n\t\t\t\t\tresultingState,\n\t\t\t\t\tordinal: 0\n\t\t\t\t}\n\t\t\t}],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\tasync executeLoadJob(job, startTime, indexTxn, stores, signal) {\n\t\tif (job.operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"Load job must include at least one operation\"), startTime);\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch {}\n\t\tif (docMeta?.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tconst scope = job.scope;\n\t\tlet latestRevision;\n\t\ttry {\n\t\t\tlatestRevision = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).revision[scope] ?? 0;\n\t\t} catch {\n\t\t\tlatestRevision = 0;\n\t\t}\n\t\tfor (const operation of job.operations) if (operation.timestampUtcMs && !isValidISOTimestamp(operation.timestampUtcMs)) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`Invalid timestamp \"${operation.timestampUtcMs}\" on operation (index: ${operation.index})`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet minIncomingIndex = Number.POSITIVE_INFINITY;\n\t\tlet minIncomingTimestamp = job.operations[0]?.timestampUtcMs || \"\";\n\t\tfor (const operation of job.operations) {\n\t\t\tminIncomingIndex = Math.min(minIncomingIndex, operation.index);\n\t\t\tconst ts = operation.timestampUtcMs || \"\";\n\t\t\tif (ts < minIncomingTimestamp) minIncomingTimestamp = ts;\n\t\t}\n\t\tlet conflictingOps;\n\t\ttry {\n\t\t\tconflictingOps = (await stores.operationStore.getConflicting(job.documentId, scope, job.branch, minIncomingTimestamp, void 0, signal)).results;\n\t\t} catch {\n\t\t\tconflictingOps = [];\n\t\t}\n\t\tlet allOpsFromMinConflictingIndex = conflictingOps;\n\t\tif (conflictingOps.length > 0) {\n\t\t\tconst minConflictingIndex = Math.min(...conflictingOps.map((op) => op.index));\n\t\t\ttry {\n\t\t\t\tallOpsFromMinConflictingIndex = (await stores.operationStore.getSince(job.documentId, scope, job.branch, minConflictingIndex - 1, void 0, void 0, signal)).results;\n\t\t\t} catch {\n\t\t\t\tallOpsFromMinConflictingIndex = conflictingOps;\n\t\t\t}\n\t\t}\n\t\tconst incomingActionIds = new Set(job.operations.map((op) => op.action.id));\n\t\tconst nonSupersededOps = conflictingOps.filter((op) => {\n\t\t\tif (op.index < minIncomingIndex && !incomingActionIds.has(op.action.id)) return false;\n\t\t\tfor (const laterOp of allOpsFromMinConflictingIndex) if (laterOp.index > op.index && laterOp.skip > 0) {\n\t\t\t\tif (laterOp.index - laterOp.skip <= op.index) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\tconst existingOpsToReshuffle = nonSupersededOps;\n\t\tif (existingOpsToReshuffle.length > this.config.maxSkipThreshold) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`Excessive reshuffle detected: existing op count of ${existingOpsToReshuffle.length} exceeds threshold of ${this.config.maxSkipThreshold}. This indicates a significant divergence between local and incoming operations.`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet skipCount = existingOpsToReshuffle.length;\n\t\tif (existingOpsToReshuffle.length > 0) {\n\t\t\tlet minLogicalIndex = Number.POSITIVE_INFINITY;\n\t\t\tfor (const op of existingOpsToReshuffle) {\n\t\t\t\tconst logical = op.index - op.skip;\n\t\t\t\tif (logical < minLogicalIndex) minLogicalIndex = logical;\n\t\t\t}\n\t\t\tconst logicalSkip = latestRevision - minLogicalIndex;\n\t\t\tif (logicalSkip > skipCount) skipCount = logicalSkip;\n\t\t}\n\t\tconst existingActionIds = new Set(nonSupersededOps.map((op) => op.action.id));\n\t\tconst seenIncomingActionIds = /* @__PURE__ */ new Set();\n\t\tconst incomingOpsToApply = job.operations.filter((op) => {\n\t\t\tif (existingActionIds.has(op.action.id)) return false;\n\t\t\tif (seenIncomingActionIds.has(op.action.id)) return false;\n\t\t\tseenIncomingActionIds.add(op.action.id);\n\t\t\treturn true;\n\t\t});\n\t\tif (incomingOpsToApply.length === 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst reshuffledOperations = existingOpsToReshuffle.length === 0 && skipCount === 0 ? incomingOpsToApply.slice().sort((a, b) => a.index - b.index).map((operation, i) => ({\n\t\t\t...operation,\n\t\t\tindex: latestRevision + i\n\t\t})) : reshuffleByTimestamp({\n\t\t\tindex: latestRevision,\n\t\t\tskip: skipCount\n\t\t}, existingOpsToReshuffle, incomingOpsToApply.map((operation) => ({\n\t\t\t...operation,\n\t\t\tid: operation.id\n\t\t})));\n\t\tfor (const operation of reshuffledOperations) if (operation.action.type === \"NOOP\") operation.skip = 1;\n\t\tconst actions = reshuffledOperations.map((operation) => operation.action);\n\t\tconst skipValues = reshuffledOperations.map((operation) => operation.skip);\n\t\tconst effectiveSourceRemote = skipCount > 0 ? \"\" : job.meta.sourceRemote || \"\";\n\t\tconst result = await this.processActions(job, actions, startTime, indexTxn, stores, skipValues, reshuffledOperations, effectiveSourceRemote, signal);\n\t\tif (!result.success) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: result.error,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\tif (scope === \"document\") stores.documentMetaCache.invalidate(job.documentId, job.branch);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: result.generatedOperations,\n\t\t\toperationsWithContext: result.operationsWithContext,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\taccumulateResultOrReturnError(result, generatedOperations, operationsWithContext) {\n\t\tif (!result.success) return result;\n\t\tif (result.operations && result.operations.length > 0) generatedOperations.push(...result.operations);\n\t\tif (result.operationsWithContext) operationsWithContext.push(...result.operationsWithContext);\n\t\treturn null;\n\t}\n};\n//#endregion\n//#region src/registry/implementation.ts\n/**\n* In-memory implementation of the IDocumentModelRegistry interface.\n* Manages document model modules with version-aware storage and upgrade manifest support.\n*/\nvar DocumentModelRegistry = class {\n\tmodules = [];\n\tmanifests = [];\n\tregisterModules(...modules) {\n\t\treturn modules.map((module) => {\n\t\t\ttry {\n\t\t\t\tconst documentType = module.documentModel.global.id;\n\t\t\t\tconst version = module.version ?? 1;\n\t\t\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\t\t\tconst existing = this.modules[i];\n\t\t\t\t\tconst existingType = existing.documentModel.global.id;\n\t\t\t\t\tconst existingVersion = existing.version ?? 1;\n\t\t\t\t\tif (existingType === documentType && existingVersion === version) throw new DuplicateModuleError(documentType, version);\n\t\t\t\t}\n\t\t\t\tthis.modules.push(module);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: module\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: module,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterModules(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.modules.some((m) => m.documentModel.global.id === documentType)) allFound = false;\n\t\t\tthis.modules = this.modules.filter((m) => m.documentModel.global.id !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetModule(documentType, version) {\n\t\tlet latestModule;\n\t\tlet latestVersion = -1;\n\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\tconst module = this.modules[i];\n\t\t\tconst moduleType = module.documentModel.global.id;\n\t\t\tconst moduleVersion = module.version ?? 1;\n\t\t\tif (moduleType === documentType) {\n\t\t\t\tif (version !== void 0 && moduleVersion === version) return module;\n\t\t\t\tif (moduleVersion > latestVersion) {\n\t\t\t\t\tlatestModule = module;\n\t\t\t\t\tlatestVersion = moduleVersion;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (version === void 0 && latestModule !== void 0) return latestModule;\n\t\tthrow new ModuleNotFoundError(documentType, version);\n\t}\n\tgetAllModules() {\n\t\treturn [...this.modules];\n\t}\n\tclear() {\n\t\tthis.modules = [];\n\t\tthis.manifests = [];\n\t}\n\tgetSupportedVersions(documentType) {\n\t\tconst versions = [];\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) versions.push(module.version ?? 1);\n\t\tif (versions.length === 0) throw new ModuleNotFoundError(documentType);\n\t\treturn versions.sort((a, b) => a - b);\n\t}\n\tgetLatestVersion(documentType) {\n\t\tlet latest = -1;\n\t\tlet found = false;\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) {\n\t\t\tfound = true;\n\t\t\tconst version = module.version ?? 1;\n\t\t\tif (version > latest) latest = version;\n\t\t}\n\t\tif (!found) throw new ModuleNotFoundError(documentType);\n\t\treturn latest;\n\t}\n\tregisterUpgradeManifests(...manifestsToRegister) {\n\t\treturn manifestsToRegister.map((manifestToRegister) => {\n\t\t\ttry {\n\t\t\t\tif (!manifestToRegister.documentType) throw new Error(\"Upgrade manifest is missing a documentType\");\n\t\t\t\tfor (const registeredManifest of this.manifests) if (registeredManifest.documentType === manifestToRegister.documentType) throw new DuplicateManifestError(manifestToRegister.documentType);\n\t\t\t\tthis.manifests.push(manifestToRegister);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: manifestToRegister\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: manifestToRegister,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterUpgradeManifests(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.manifests.some((m) => m.documentType === documentType)) allFound = false;\n\t\t\tthis.manifests = this.manifests.filter((m) => m.documentType !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetUpgradeManifest(documentType) {\n\t\tfor (let i = 0; i < this.manifests.length; i++) if (this.manifests[i].documentType === documentType) return this.manifests[i];\n\t\tthrow new ManifestNotFoundError(documentType);\n\t}\n\tcomputeUpgradePath(documentType, fromVersion, toVersion) {\n\t\tif (fromVersion === toVersion) return [];\n\t\tif (toVersion < fromVersion) throw new DowngradeNotSupportedError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst path = [];\n\t\tfor (let v = fromVersion + 1; v <= toVersion; v++) {\n\t\t\tconst key = `v${v}`;\n\t\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, v - 1, v);\n\t\t\tconst transition = manifest.upgrades[key];\n\t\t\tpath.push(transition);\n\t\t}\n\t\treturn path;\n\t}\n\tgetUpgradeReducer(documentType, fromVersion, toVersion) {\n\t\tif (toVersion !== fromVersion + 1) throw new InvalidUpgradeStepError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst key = `v${toVersion}`;\n\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, fromVersion, toVersion);\n\t\treturn manifest.upgrades[key].upgradeReducer;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/keyframe-store.ts\nvar KyselyKeyframeStore = class KyselyKeyframeStore {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyKeyframeStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync putKeyframe(documentId, scope, branch, revision, document, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.queryExecutor.insertInto(\"Keyframe\").values({\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope,\n\t\t\tbranch,\n\t\t\trevision,\n\t\t\tdocument\n\t\t}).onConflict((oc) => oc.columns([\n\t\t\t\"documentId\",\n\t\t\t\"scope\",\n\t\t\t\"branch\",\n\t\t\t\"revision\"\n\t\t]).doUpdateSet({ document })).execute();\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst row = await this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"revision\", \"<=\", targetRevision).orderBy(\"revision\", \"desc\").limit(1).executeTakeFirst();\n\t\tif (!row) return;\n\t\treturn {\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t};\n\t}\n\tasync listKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"revision\", \"asc\");\n\t\tif (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tif (branch !== void 0) query = query.where(\"branch\", \"=\", branch);\n\t\treturn (await query.execute()).map((row) => ({\n\t\t\tscope: row.scope,\n\t\t\tbranch: row.branch,\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t}));\n\t}\n\tasync deleteKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.deleteFrom(\"Keyframe\").where(\"documentId\", \"=\", documentId);\n\t\tif (scope !== void 0 && branch !== void 0) query = query.where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch);\n\t\telse if (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows || 0n);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/pagination.ts\nconst DEFAULT_LIMIT = 100;\nfunction paginateRows(rows, paging, cursorOf, toItem, refetch) {\n\tlet hasMore = false;\n\tlet items = rows;\n\tif (paging?.limit && rows.length > paging.limit) {\n\t\thasMore = true;\n\t\titems = rows.slice(0, paging.limit);\n\t}\n\tconst nextCursor = hasMore && items.length > 0 ? cursorOf(items[items.length - 1]).toString() : void 0;\n\tconst cursor = paging?.cursor || \"0\";\n\tconst limit = paging?.limit || DEFAULT_LIMIT;\n\treturn {\n\t\tresults: items.map(toItem),\n\t\toptions: {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t},\n\t\tnextCursor,\n\t\tnext: hasMore ? () => refetch(nextCursor, limit) : void 0\n\t};\n}\n//#endregion\n//#region src/storage/interfaces.ts\n/**\n* Thrown when an operation with the same identity already exists in the store.\n*/\nvar DuplicateOperationError = class extends Error {\n\tconstructor(description) {\n\t\tsuper(`Duplicate operation: ${description}`);\n\t\tthis.name = \"DuplicateOperationError\";\n\t}\n};\n/**\n* Thrown when a concurrent write conflict is detected during an atomic apply.\n*/\nvar OptimisticLockError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"OptimisticLockError\";\n\t}\n};\n/**\n* Thrown when the caller-provided revision does not match the current\n* stored revision, indicating a stale read.\n*/\nvar RevisionMismatchError = class extends Error {\n\tconstructor(expected, actual) {\n\t\tsuper(`Revision mismatch: expected ${expected}, got ${actual}`);\n\t\tthis.name = \"RevisionMismatchError\";\n\t}\n};\n//#endregion\n//#region src/storage/txn.ts\nvar AtomicTransaction = class {\n\toperations = [];\n\tconstructor(documentId, documentType, scope, branch, baseRevision) {\n\t\tthis.documentId = documentId;\n\t\tthis.documentType = documentType;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.baseRevision = baseRevision;\n\t}\n\taddOperations(...operations) {\n\t\tfor (const op of operations) this.operations.push({\n\t\t\tjobId: v4(),\n\t\t\topId: op.id,\n\t\t\tprevOpId: \"\",\n\t\t\tdocumentId: this.documentId,\n\t\t\tdocumentType: this.documentType,\n\t\t\tscope: this.scope,\n\t\t\tbranch: this.branch,\n\t\t\ttimestampUtcMs: new Date(op.timestampUtcMs),\n\t\t\tindex: op.index,\n\t\t\taction: JSON.stringify(op.action),\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || null,\n\t\t\thash: op.hash\n\t\t});\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/store.ts\nvar _UniqueConstraintContext = class extends Error {\n\tconstructor(documentId, scope, branch, revision, stagedOps) {\n\t\tsuper(\"unique constraint\");\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.revision = revision;\n\t\tthis.stagedOps = stagedOps;\n\t\tthis.name = \"UniqueConstraintContext\";\n\t}\n};\nvar KyselyOperationStore = class KyselyOperationStore {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyOperationStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync apply(documentId, documentType, scope, branch, revision, fn, signal) {\n\t\tif (this.trx) {\n\t\t\tlet executeResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\texecuteResult = await this.executeApply(this.trx, documentId, documentType, scope, branch, revision, fn, signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn executeResult;\n\t\t} else {\n\t\t\tlet transactionResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\ttransactionResult = await this.db.transaction().execute(async (trx) => {\n\t\t\t\t\treturn this.executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal);\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn transactionResult;\n\t\t}\n\t}\n\tasync resolveUniqueConstraint(ctx) {\n\t\tlet replayOps = null;\n\t\ttry {\n\t\t\treplayOps = await this.findIdempotentReplay(this.db, ctx.documentId, ctx.scope, ctx.branch, ctx.revision, ctx.stagedOps);\n\t\t} catch {}\n\t\tif (replayOps !== null) return replayOps;\n\t\tconst op = ctx.stagedOps[0];\n\t\tthrow new DuplicateOperationError(`${op.opId} at index ${op.index} with skip ${op.skip}`);\n\t}\n\tasync executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst atomicTxn = new AtomicTransaction(documentId, documentType, scope, branch, revision);\n\t\tawait fn(atomicTxn);\n\t\tconst operations = atomicTxn.getOperations();\n\t\tif (operations.length === 0) return [];\n\t\tconst latestOp = await trx.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).orderBy(\"index\", \"desc\").limit(1).executeTakeFirst();\n\t\tconst currentRevision = latestOp ? latestOp.index : -1;\n\t\tif (currentRevision !== revision - 1) {\n\t\t\tlet replayOps = null;\n\t\t\ttry {\n\t\t\t\treplayOps = await this.findIdempotentReplay(trx, documentId, scope, branch, revision, operations);\n\t\t\t} catch {}\n\t\t\tif (replayOps !== null) return replayOps;\n\t\t\tthrow new RevisionMismatchError(currentRevision + 1, revision);\n\t\t}\n\t\tlet prevOpId = latestOp?.opId || \"\";\n\t\tfor (const op of operations) {\n\t\t\top.prevOpId = prevOpId;\n\t\t\tprevOpId = op.opId;\n\t\t}\n\t\ttry {\n\t\t\tawait trx.insertInto(\"Operation\").values(operations).execute();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message.includes(\"unique constraint\")) throw new _UniqueConstraintContext(documentId, scope, branch, revision, operations);\n\t\t\tthrow error;\n\t\t}\n\t\treturn operations.map((op) => ({\n\t\t\tindex: op.index,\n\t\t\ttimestampUtcMs: op.timestampUtcMs.toISOString(),\n\t\t\thash: op.hash,\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || void 0,\n\t\t\tid: op.opId,\n\t\t\taction: JSON.parse(op.action)\n\t\t}));\n\t}\n\tasync findIdempotentReplay(executor, documentId, scope, branch, revision, stagedOps) {\n\t\tconst minIndex = revision;\n\t\tconst maxIndex = revision + stagedOps.length - 1;\n\t\tconst storedRows = await executor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">=\", minIndex).where(\"index\", \"<=\", maxIndex).orderBy(\"index\", \"asc\").execute();\n\t\tif (storedRows.length !== stagedOps.length) return null;\n\t\tfor (let i = 0; i < stagedOps.length; i++) {\n\t\t\tconst staged = stagedOps[i];\n\t\t\tconst stored = storedRows[i];\n\t\t\tif (stored.opId !== staged.opId || stored.index !== staged.index || stored.skip !== staged.skip) return null;\n\t\t}\n\t\treturn storedRows.map((row) => this.rowToOperation(row));\n\t}\n\tasync getSince(documentId, scope, branch, revision, filter, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">\", revision).orderBy(\"index\", \"asc\");\n\t\tif (filter) {\n\t\t\tif (filter.actionTypes && filter.actionTypes.length > 0) {\n\t\t\t\tconst actionTypesArray = filter.actionTypes.map((t) => `'${t.replace(/'/g, \"''\")}'`).join(\",\");\n\t\t\t\tquery = query.where(sql`action->>'type' = ANY(ARRAY[${sql.raw(actionTypesArray)}]::text[])`);\n\t\t\t}\n\t\t\tif (filter.timestampFrom) query = query.where(\"timestampUtcMs\", \">=\", new Date(filter.timestampFrom));\n\t\t\tif (filter.timestampTo) query = query.where(\"timestampUtcMs\", \"<=\", new Date(filter.timestampTo));\n\t\t\tif (filter.sinceRevision !== void 0) query = query.where(\"index\", \">=\", filter.sinceRevision);\n\t\t}\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"index\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index, (row) => this.rowToOperation(row), (cursor, limit) => this.getSince(documentId, scope, branch, revision, filter, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getSinceId(id, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"id\", \">\", id).orderBy(\"id\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"id\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.id, (row) => this.rowToOperationWithContext(row), (cursor, limit) => this.getSinceId(id, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getConflicting(documentId, scope, branch, minTimestamp, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"timestampUtcMs\", \">=\", new Date(minTimestamp)).orderBy(\"index\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"index\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index, (row) => this.rowToOperation(row), (cursor, limit) => this.getConflicting(documentId, scope, branch, minTimestamp, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getRevisions(documentId, branch, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst scopeRevisions = await this.queryExecutor.selectFrom(\"Operation as o1\").select([\n\t\t\t\"o1.scope\",\n\t\t\t\"o1.index\",\n\t\t\t\"o1.timestampUtcMs\"\n\t\t]).where(\"o1.documentId\", \"=\", documentId).where(\"o1.branch\", \"=\", branch).where((eb) => eb(\"o1.index\", \"=\", eb.selectFrom(\"Operation as o2\").select((eb2) => eb2.fn.max(\"o2.index\").as(\"maxIndex\")).where(\"o2.documentId\", \"=\", eb.ref(\"o1.documentId\")).where(\"o2.branch\", \"=\", eb.ref(\"o1.branch\")).where(\"o2.scope\", \"=\", eb.ref(\"o1.scope\")))).execute();\n\t\tconst revision = {};\n\t\tlet latestTimestamp = (/* @__PURE__ */ new Date(0)).toISOString();\n\t\tfor (const row of scopeRevisions) {\n\t\t\trevision[row.scope] = row.index + 1;\n\t\t\tconst timestamp = row.timestampUtcMs.toISOString();\n\t\t\tif (timestamp > latestTimestamp) latestTimestamp = timestamp;\n\t\t}\n\t\treturn {\n\t\t\trevision,\n\t\t\tlatestTimestamp\n\t\t};\n\t}\n\trowToOperation(row) {\n\t\treturn {\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs.toISOString(),\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\terror: row.error || void 0,\n\t\t\tid: row.opId,\n\t\t\taction: row.action\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: this.rowToOperation(row),\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.id\n\t\t\t}\n\t\t};\n\t}\n};\n//#endregion\n//#region src/storage/pool-instrumentation.ts\n/**\n* Wraps an existing pg.Pool with acquire-wait timing and an event\n* subscription surface. The pool is mutated in place: pool.connect()\n* is replaced with a timing wrapper so all callers (Kysely included)\n* pick up the instrumentation transparently.\n*/\nfunction instrumentPgPool(pool, name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tconst originalConnect = pool.connect.bind(pool);\n\tconst wrappedConnect = async () => {\n\t\tconst start = performance.now();\n\t\tconst client = await originalConnect();\n\t\tconst durationMs = performance.now() - start;\n\t\tfor (const listener of listeners) try {\n\t\t\tlistener(durationMs);\n\t\t} catch {}\n\t\treturn client;\n\t};\n\tpool.connect = wrappedConnect;\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn {\n\t\t\t\tsize: pool.totalCount,\n\t\t\t\tidle: pool.idleCount,\n\t\t\t\twaiting: pool.waitingCount\n\t\t\t};\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t}\n\t};\n}\nfunction createForwardingPoolInstrumentation(name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tlet stats = {\n\t\tsize: 0,\n\t\tidle: 0,\n\t\twaiting: 0\n\t};\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn stats;\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tpushSamples(durations) {\n\t\t\tfor (const durationMs of durations) for (const listener of listeners) try {\n\t\t\t\tlistener(durationMs);\n\t\t\t} catch {}\n\t\t},\n\t\tupdateStats(next) {\n\t\t\tstats = next;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/storage/migrations/001_create_operation_table.ts\nvar _001_create_operation_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$13 });\nasync function up$13(db) {\n\tawait db.schema.createTable(\"Operation\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"jobId\", \"text\", (col) => col.notNull()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"prevOpId\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"timestamptz\", (col) => col.notNull()).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"error\", \"text\").addColumn(\"hash\", \"text\", (col) => col.notNull()).addUniqueConstraint(\"unique_revision\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"index\"\n\t]).addUniqueConstraint(\"unique_operation_instance\", [\n\t\t\"opId\",\n\t\t\"index\",\n\t\t\"skip\"\n\t]).execute();\n\tawait db.schema.createIndex(\"streamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"id\"\n\t]).execute();\n\tawait db.schema.createIndex(\"branchlessStreamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"id\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/002_create_keyframe_table.ts\nvar _002_create_keyframe_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$12 });\nasync function up$12(db) {\n\tawait db.schema.createTable(\"Keyframe\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"revision\", \"integer\", (col) => col.notNull()).addColumn(\"document\", \"jsonb\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_keyframe\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n\tawait db.schema.createIndex(\"keyframe_lookup\").on(\"Keyframe\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/003_create_document_table.ts\nvar _003_create_document_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$11 });\nasync function up$11(db) {\n\tawait db.schema.createTable(\"Document\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/004_create_document_relationship_table.ts\nvar _004_create_document_relationship_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$10 });\nasync function up$10(db) {\n\tawait db.schema.createTable(\"DocumentRelationship\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"sourceId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"targetId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"relationshipType\", \"text\", (col) => col.notNull()).addColumn(\"metadata\", \"jsonb\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_source_target_type\", [\n\t\t\"sourceId\",\n\t\t\"targetId\",\n\t\t\"relationshipType\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_relationship_source\").on(\"DocumentRelationship\").column(\"sourceId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_target\").on(\"DocumentRelationship\").column(\"targetId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_type\").on(\"DocumentRelationship\").column(\"relationshipType\").execute();\n}\n//#endregion\n//#region src/storage/migrations/005_create_indexer_state_table.ts\nvar _005_create_indexer_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$9 });\nasync function up$9(db) {\n\tawait db.schema.createTable(\"IndexerState\").addColumn(\"id\", \"integer\", (col) => col.primaryKey().generatedAlwaysAsIdentity()).addColumn(\"lastOperationId\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/006_create_document_snapshot_table.ts\nvar _006_create_document_snapshot_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$8 });\nasync function up$8(db) {\n\tawait db.schema.createTable(\"DocumentSnapshot\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"slug\", \"text\").addColumn(\"name\", \"text\").addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"content\", \"jsonb\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"lastOperationIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationHash\", \"text\", (col) => col.notNull()).addColumn(\"lastUpdatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"snapshotVersion\", \"integer\", (col) => col.notNull().defaultTo(1)).addColumn(\"identifiers\", \"jsonb\").addColumn(\"metadata\", \"jsonb\").addColumn(\"isDeleted\", \"boolean\", (col) => col.notNull().defaultTo(false)).addColumn(\"deletedAt\", \"timestamptz\").addUniqueConstraint(\"unique_doc_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"slug\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_doctype_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"documentType\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_last_updated\").on(\"DocumentSnapshot\").column(\"lastUpdatedAt\").execute();\n\tawait db.schema.createIndex(\"idx_is_deleted\").on(\"DocumentSnapshot\").column(\"isDeleted\").execute();\n}\n//#endregion\n//#region src/storage/migrations/007_create_slug_mapping_table.ts\nvar _007_create_slug_mapping_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$7 });\nasync function up$7(db) {\n\tawait db.schema.createTable(\"SlugMapping\").addColumn(\"slug\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_docid_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_documentid\").on(\"SlugMapping\").column(\"documentId\").execute();\n}\n//#endregion\n//#region src/storage/migrations/008_create_view_state_table.ts\nvar _008_create_view_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$6 });\nasync function up$6(db) {\n\tawait db.schema.createTable(\"ViewState\").addColumn(\"readModelId\", \"text\", (col) => col.primaryKey()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/009_create_operation_index_tables.ts\nvar _009_create_operation_index_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$5 });\nasync function up$5(db) {\n\tawait db.schema.createTable(\"document_collections\").addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"collectionId\", \"text\", (col) => col.notNull()).addColumn(\"joinedOrdinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"leftOrdinal\", \"bigint\").addPrimaryKeyConstraint(\"document_collections_pkey\", [\"documentId\", \"collectionId\"]).execute();\n\tawait db.schema.createIndex(\"idx_document_collections_collectionId\").on(\"document_collections\").column(\"collectionId\").execute();\n\tawait db.schema.createIndex(\"idx_doc_collections_collection_range\").on(\"document_collections\").columns([\"collectionId\", \"joinedOrdinal\"]).execute();\n\tawait db.schema.createTable(\"operation_index_operations\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"hash\", \"text\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_document\").on(\"operation_index_operations\").columns([\n\t\t\"documentId\",\n\t\t\"branch\",\n\t\t\"scope\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_ordinal\").on(\"operation_index_operations\").column(\"ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/010_create_sync_tables.ts\nvar _010_create_sync_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$4 });\nasync function up$4(db) {\n\tawait db.schema.createTable(\"sync_remotes\").addColumn(\"name\", \"text\", (col) => col.primaryKey()).addColumn(\"collection_id\", \"text\", (col) => col.notNull()).addColumn(\"channel_type\", \"text\", (col) => col.notNull()).addColumn(\"channel_id\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"remote_name\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"channel_parameters\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'{}'::jsonb`)).addColumn(\"filter_document_ids\", \"jsonb\").addColumn(\"filter_scopes\", \"jsonb\").addColumn(\"filter_branch\", \"text\", (col) => col.notNull().defaultTo(\"main\")).addColumn(\"push_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"push_last_success_utc_ms\", \"text\").addColumn(\"push_last_failure_utc_ms\", \"text\").addColumn(\"push_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"pull_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"pull_last_success_utc_ms\", \"text\").addColumn(\"pull_last_failure_utc_ms\", \"text\").addColumn(\"pull_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_remotes_collection\").on(\"sync_remotes\").column(\"collection_id\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.primaryKey().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/011_add_cursor_type_column.ts\nvar _011_add_cursor_type_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$3 });\nasync function up$3(db) {\n\tawait db.deleteFrom(\"sync_cursors\").where(\"remote_name\", \"like\", \"outbox::%\").execute();\n\tawait db.deleteFrom(\"sync_remotes\").where(\"name\", \"like\", \"outbox::%\").execute();\n\tawait db.schema.dropTable(\"sync_cursors\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"cursor_type\", \"text\", (col) => col.notNull().defaultTo(\"inbox\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addPrimaryKeyConstraint(\"sync_cursors_pk\", [\"remote_name\", \"cursor_type\"]).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/012_add_source_remote_column.ts\nvar _012_add_source_remote_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$2 });\nasync function up$2(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").addColumn(\"sourceRemote\", \"text\", (col) => col.notNull().defaultTo(\"\")).execute();\n}\n//#endregion\n//#region src/storage/migrations/013_create_sync_dead_letters_table.ts\nvar _013_create_sync_dead_letters_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$1 });\nasync function up$1(db) {\n\tawait db.schema.createTable(\"sync_dead_letters\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"id\", \"text\", (col) => col.unique().notNull()).addColumn(\"job_id\", \"text\", (col) => col.notNull()).addColumn(\"job_dependencies\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"remote_name\", \"text\", (col) => col.notNull().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"scopes\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"operations\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"error_source\", \"text\", (col) => col.notNull()).addColumn(\"error_message\", \"text\", (col) => col.notNull()).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_dead_letters_remote\").on(\"sync_dead_letters\").column(\"remote_name\").execute();\n}\n//#endregion\n//#region src/storage/migrations/014_create_processor_cursor_table.ts\nvar _014_create_processor_cursor_table_exports = /* @__PURE__ */ __exportAll({ up: () => up });\nasync function up(db) {\n\tawait db.schema.createTable(\"ProcessorCursor\").addColumn(\"processorId\", \"text\", (col) => col.primaryKey()).addColumn(\"factoryId\", \"text\", (col) => col.notNull()).addColumn(\"driveId\", \"text\", (col) => col.notNull()).addColumn(\"processorIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(sql`0`)).addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(sql`'active'`)).addColumn(\"lastError\", \"text\").addColumn(\"lastErrorTimestamp\", \"timestamptz\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/migrator.ts\nconst REACTOR_SCHEMA = \"reactor\";\nconst migrations = {\n\t\"001_create_operation_table\": _001_create_operation_table_exports,\n\t\"002_create_keyframe_table\": _002_create_keyframe_table_exports,\n\t\"003_create_document_table\": _003_create_document_table_exports,\n\t\"004_create_document_relationship_table\": _004_create_document_relationship_table_exports,\n\t\"005_create_indexer_state_table\": _005_create_indexer_state_table_exports,\n\t\"006_create_document_snapshot_table\": _006_create_document_snapshot_table_exports,\n\t\"007_create_slug_mapping_table\": _007_create_slug_mapping_table_exports,\n\t\"008_create_view_state_table\": _008_create_view_state_table_exports,\n\t\"009_create_operation_index_tables\": _009_create_operation_index_tables_exports,\n\t\"010_create_sync_tables\": _010_create_sync_tables_exports,\n\t\"011_add_cursor_type_column\": _011_add_cursor_type_column_exports,\n\t\"012_add_source_remote_column\": _012_add_source_remote_column_exports,\n\t\"013_create_sync_dead_letters_table\": _013_create_sync_dead_letters_table_exports,\n\t\"014_create_processor_cursor_table\": _014_create_processor_cursor_table_exports\n};\nvar ProgrammaticMigrationProvider = class {\n\tgetMigrations() {\n\t\treturn Promise.resolve(migrations);\n\t}\n};\nasync function runMigrations(db, schema = REACTOR_SCHEMA) {\n\ttry {\n\t\tawait sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tmigrationsExecuted: [],\n\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Failed to create schema\")\n\t\t};\n\t}\n\tconst migrator = new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t});\n\tlet error;\n\tlet results;\n\ttry {\n\t\tconst result = await migrator.migrateToLatest();\n\t\terror = result.error;\n\t\tresults = result.results;\n\t} catch (e) {\n\t\terror = e;\n\t\tresults = [];\n\t}\n\tconst migrationsExecuted = results?.map((result) => result.migrationName) ?? [];\n\tif (error) return {\n\t\tsuccess: false,\n\t\tmigrationsExecuted,\n\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Unknown migration error\")\n\t};\n\treturn {\n\t\tsuccess: true,\n\t\tmigrationsExecuted\n\t};\n}\nasync function getMigrationStatus(db, schema = REACTOR_SCHEMA) {\n\treturn await new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t}).getMigrations();\n}\n//#endregion\n//#region src/core/drive-container-types.ts\nconst DEFAULT_DRIVE_CONTAINER_TYPES = new Set([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"]);\n//#endregion\nexport { parsePagingOptions as A, DuplicateManifestError as C, DocumentDeletedError as D, ModuleNotFoundError as E, __exportAll as M, DocumentNotFoundError as O, CollectionMembershipCache as S, InvalidModuleError as T, KyselyWriteCache as _, createForwardingPoolInstrumentation as a, createConsistencyToken as b, DuplicateOperationError as c, KyselyKeyframeStore as d, DocumentModelRegistry as f, EventBus as g, KyselyExecutionScope as h, runMigrations as i, throwIfAborted as j, matchesScope as k, OptimisticLockError as l, DriveCollectionId as m, REACTOR_SCHEMA as n, instrumentPgPool as o, SimpleJobExecutor as p, getMigrationStatus as r, KyselyOperationStore as s, DEFAULT_DRIVE_CONTAINER_TYPES as t, RevisionMismatchError as u, KyselyOperationIndex as v, DuplicateModuleError as w, createEmptyConsistencyToken as x, DocumentMetaCache as y };\n\n//# sourceMappingURL=drive-container-types-BxnXaOAp.js.map","import { BaseDocumentHeaderSchema, BaseDocumentStateSchema, baseCreateDocument, baseLoadFromInput, baseSaveToFileHandle, createAction, createBaseState, createReducer, createState as createState$1, defaultBaseState, isDocumentAction } from \"../document-model/index.js\";\nimport { z } from \"zod\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region document-drive/constants.ts\nconst driveDocumentFileExtension = \"phdd\";\n//#endregion\n//#region document-drive/gen/schema/zod.ts\nconst isDefinedNonNullAny = (v) => v !== void 0 && v !== null;\nconst definedNonNullAnySchema = z.any().refine((v) => isDefinedNonNullAny(v));\nconst TransmitterTypeSchema = z.enum([\n\t\"Internal\",\n\t\"MatrixConnect\",\n\t\"PullResponder\",\n\t\"RESTWebhook\",\n\t\"SecureConnect\",\n\t\"SwitchboardPush\"\n]);\nconst TriggerTypeSchema = z.enum([\"PullResponder\"]);\nfunction AddFileInputSchema() {\n\treturn z.object({\n\t\tdocumentType: z.string(),\n\t\tid: z.string(),\n\t\tname: z.string(),\n\t\tparentFolder: z.string().nullish()\n\t});\n}\nfunction AddFolderInputSchema() {\n\treturn z.object({\n\t\tid: z.string(),\n\t\tname: z.string(),\n\t\tparentFolder: z.string().nullish()\n\t});\n}\nfunction AddListenerInputSchema() {\n\treturn z.object({ listener: ListenerInputSchema() });\n}\nfunction AddTriggerInputSchema() {\n\treturn z.object({ trigger: TriggerInputSchema() });\n}\nfunction CopyNodeInputSchema() {\n\treturn z.object({\n\t\tsrcId: z.string(),\n\t\ttargetId: z.string(),\n\t\ttargetName: z.string().nullish(),\n\t\ttargetParentFolder: z.string().nullish()\n\t});\n}\nfunction DeleteNodeInputSchema() {\n\treturn z.object({ id: z.string() });\n}\nfunction DocumentDriveLocalStateSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"DocumentDriveLocalState\").optional(),\n\t\tavailableOffline: z.boolean(),\n\t\tlisteners: z.array(ListenerSchema()),\n\t\tsharingType: z.string().nullable(),\n\t\ttriggers: z.array(TriggerSchema())\n\t});\n}\nfunction DocumentDriveStateSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"DocumentDriveState\").optional(),\n\t\ticon: z.string().nullable(),\n\t\tname: z.string(),\n\t\tnodes: z.array(NodeSchema())\n\t});\n}\nfunction FileNodeSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"FileNode\").optional(),\n\t\tdocumentType: z.string(),\n\t\tid: z.string(),\n\t\tkind: z.string(),\n\t\tname: z.string(),\n\t\tparentFolder: z.string().nullable()\n\t});\n}\nfunction FolderNodeSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"FolderNode\").optional(),\n\t\tid: z.string(),\n\t\tkind: z.string(),\n\t\tname: z.string(),\n\t\tparentFolder: z.string().nullable()\n\t});\n}\nfunction ListenerSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"Listener\").optional(),\n\t\tblock: z.boolean(),\n\t\tcallInfo: ListenerCallInfoSchema().nullable(),\n\t\tfilter: ListenerFilterSchema(),\n\t\tlabel: z.string().nullable(),\n\t\tlistenerId: z.string(),\n\t\tsystem: z.boolean()\n\t});\n}\nfunction ListenerInputSchema() {\n\treturn z.object({\n\t\tblock: z.boolean(),\n\t\tcallInfo: ListenerCallInfoInputSchema().nullish(),\n\t\tfilter: ListenerFilterInputSchema(),\n\t\tlabel: z.string().nullish(),\n\t\tlistenerId: z.string(),\n\t\tsystem: z.boolean()\n\t});\n}\nfunction ListenerCallInfoSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"ListenerCallInfo\").optional(),\n\t\tdata: z.string().nullable(),\n\t\tname: z.string().nullable(),\n\t\ttransmitterType: TransmitterTypeSchema.nullable()\n\t});\n}\nfunction ListenerCallInfoInputSchema() {\n\treturn z.object({\n\t\tdata: z.string().nullish(),\n\t\tname: z.string().nullish(),\n\t\ttransmitterType: TransmitterTypeSchema.nullish()\n\t});\n}\nfunction ListenerFilterSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"ListenerFilter\").optional(),\n\t\tbranch: z.array(z.string()).nullable(),\n\t\tdocumentId: z.array(z.string()).nullable(),\n\t\tdocumentType: z.array(z.string()),\n\t\tscope: z.array(z.string()).nullable()\n\t});\n}\nfunction ListenerFilterInputSchema() {\n\treturn z.object({\n\t\tbranch: z.array(z.string()).nullish(),\n\t\tdocumentId: z.array(z.string()).nullish(),\n\t\tdocumentType: z.array(z.string()).nullish(),\n\t\tscope: z.array(z.string()).nullish()\n\t});\n}\nfunction MoveNodeInputSchema() {\n\treturn z.object({\n\t\tsrcFolder: z.string(),\n\t\ttargetParentFolder: z.string().nullish()\n\t});\n}\nfunction NodeSchema() {\n\treturn z.union([FileNodeSchema(), FolderNodeSchema()]);\n}\nfunction PullResponderTriggerDataSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"PullResponderTriggerData\").optional(),\n\t\tinterval: z.string(),\n\t\tlistenerId: z.string(),\n\t\turl: z.string()\n\t});\n}\nfunction PullResponderTriggerDataInputSchema() {\n\treturn z.object({\n\t\tinterval: z.string(),\n\t\tlistenerId: z.string(),\n\t\turl: z.string()\n\t});\n}\nfunction RemoveListenerInputSchema() {\n\treturn z.object({ listenerId: z.string() });\n}\nfunction RemoveTriggerInputSchema() {\n\treturn z.object({ triggerId: z.string() });\n}\nfunction SetAvailableOfflineInputSchema() {\n\treturn z.object({ availableOffline: z.boolean() });\n}\nfunction SetDriveIconInputSchema() {\n\treturn z.object({ icon: z.string() });\n}\nfunction SetDriveNameInputSchema() {\n\treturn z.object({ name: z.string() });\n}\nfunction SetSharingTypeInputSchema() {\n\treturn z.object({ type: z.string() });\n}\nfunction TriggerSchema() {\n\treturn z.object({\n\t\t__typename: z.literal(\"Trigger\").optional(),\n\t\tdata: TriggerDataSchema().nullable(),\n\t\tid: z.string(),\n\t\ttype: TriggerTypeSchema\n\t});\n}\nfunction TriggerInputSchema() {\n\treturn z.object({\n\t\tdata: PullResponderTriggerDataInputSchema().nullish(),\n\t\tid: z.string(),\n\t\ttype: TriggerTypeSchema\n\t});\n}\nfunction TriggerDataSchema() {\n\treturn PullResponderTriggerDataSchema();\n}\nfunction UpdateFileInputSchema() {\n\treturn z.object({\n\t\tdocumentType: z.string().nullish(),\n\t\tid: z.string(),\n\t\tname: z.string().nullish(),\n\t\tparentFolder: z.string().nullish()\n\t});\n}\nfunction UpdateNodeInputSchema() {\n\treturn z.object({\n\t\tid: z.string(),\n\t\tname: z.string().nullish(),\n\t\tparentFolder: z.string().nullish()\n\t});\n}\n//#endregion\n//#region document-drive/gen/node/creators.ts\nfunction addFile(input) {\n\tif (input && typeof input === \"object\" && \"synchronizationUnits\" in input) return createAction(\"ADD_FILE\", { ...input }, void 0, void 0, \"global\");\n\treturn createAction(\"ADD_FILE\", { ...input }, void 0, AddFileInputSchema, \"global\");\n}\nconst addFolder = (input) => createAction(\"ADD_FOLDER\", { ...input }, void 0, AddFolderInputSchema, \"global\");\nconst deleteNode = (input) => createAction(\"DELETE_NODE\", { ...input }, void 0, DeleteNodeInputSchema, \"global\");\nconst updateFile = (input) => createAction(\"UPDATE_FILE\", { ...input }, void 0, UpdateFileInputSchema, \"global\");\nconst updateNode = (input) => createAction(\"UPDATE_NODE\", { ...input }, void 0, UpdateNodeInputSchema, \"global\");\nconst copyNode = (input) => createAction(\"COPY_NODE\", { ...input }, void 0, CopyNodeInputSchema, \"global\");\nconst moveNode = (input) => createAction(\"MOVE_NODE\", { ...input }, void 0, MoveNodeInputSchema, \"global\");\n//#endregion\n//#region document-drive/gen/drive/creators.ts\nconst setDriveName = (input) => createAction(\"SET_DRIVE_NAME\", { ...input }, void 0, SetDriveNameInputSchema, \"global\");\nconst setDriveIcon = (input) => createAction(\"SET_DRIVE_ICON\", { ...input }, void 0, SetDriveIconInputSchema, \"global\");\nconst setSharingType = (input) => createAction(\"SET_SHARING_TYPE\", { ...input }, void 0, SetSharingTypeInputSchema, \"local\");\nconst setAvailableOffline = (input) => createAction(\"SET_AVAILABLE_OFFLINE\", { ...input }, void 0, SetAvailableOfflineInputSchema, \"local\");\nconst addListener = (input) => createAction(\"ADD_LISTENER\", { ...input }, void 0, AddListenerInputSchema, \"local\");\nconst removeListener = (input) => createAction(\"REMOVE_LISTENER\", { ...input }, void 0, RemoveListenerInputSchema, \"local\");\nconst addTrigger = (input) => createAction(\"ADD_TRIGGER\", { ...input }, void 0, AddTriggerInputSchema, \"local\");\nconst removeTrigger = (input) => createAction(\"REMOVE_TRIGGER\", { ...input }, void 0, RemoveTriggerInputSchema, \"local\");\n//#endregion\n//#region document-drive/gen/creators.ts\nvar creators_exports = /* @__PURE__ */ __exportAll({\n\taddFile: () => addFile,\n\taddFolder: () => addFolder,\n\taddListener: () => addListener,\n\taddTrigger: () => addTrigger,\n\tcopyNode: () => copyNode,\n\tdeleteNode: () => deleteNode,\n\tmoveNode: () => moveNode,\n\tremoveListener: () => removeListener,\n\tremoveTrigger: () => removeTrigger,\n\tsetAvailableOffline: () => setAvailableOffline,\n\tsetDriveIcon: () => setDriveIcon,\n\tsetDriveName: () => setDriveName,\n\tsetSharingType: () => setSharingType,\n\tupdateFile: () => updateFile,\n\tupdateNode: () => updateNode\n});\n//#endregion\n//#region document-drive/gen/document-model.ts\nconst driveDocumentModel = {\n\tid: \"powerhouse/document-drive\",\n\tname: \"DocumentDrive\",\n\textension: \"phdd\",\n\tdescription: \"\",\n\tauthor: {\n\t\tname: \"Powerhouse Inc\",\n\t\twebsite: \"https://www.powerhouse.inc/\"\n\t},\n\tspecifications: [{\n\t\tversion: 1,\n\t\tchangeLog: [],\n\t\tstate: {\n\t\t\tglobal: {\n\t\t\t\tschema: \"type FolderNode {\\n id: String!\\n name: String!\\n kind: String!\\n parentFolder: String\\n}\\n\\ntype FileNode {\\n id: String!\\n name: String!\\n kind: String!\\n documentType: String!\\n parentFolder: String\\n}\\n\\nunion Node = FolderNode | FileNode\\n\\ntype DocumentDriveState {\\n name: String!\\n nodes: [Node!]!\\n icon: String\\n}\",\n\t\t\t\tinitialValue: \"\\\"{\\\\\\\"name\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"nodes\\\\\\\":[],\\\\\\\"icon\\\\\\\":null}\\\"\",\n\t\t\t\texamples: []\n\t\t\t},\n\t\t\tlocal: {\n\t\t\t\tschema: \"type ListenerFilter {\\n documentType: [String!]!\\n documentId: [ID!]\\n scope: [String!]\\n branch: [String!]\\n}\\n\\nenum TransmitterType {\\n Internal,\\n SwitchboardPush,\\n PullResponder,\\n SecureConnect, \\n MatrixConnect,\\n RESTWebhook\\n}\\n\\ntype ListenerCallInfo {\\n transmitterType: TransmitterType\\n name: String\\n data: String\\n}\\n\\ntype Listener {\\n listenerId: ID!\\n label: String\\n block: Boolean!\\n system: Boolean!\\n filter: ListenerFilter!\\n callInfo: ListenerCallInfo\\n}\\n\\nenum TriggerType {\\n PullResponder\\n}\\n\\ntype PullResponderTriggerData {\\n listenerId: ID!\\n url: String!\\n interval: String!\\n}\\n\\nunion TriggerData = PullResponderTriggerData\\n\\ntype Trigger {\\n id: ID!\\n type: TriggerType!\\n data: TriggerData\\n}\\n\\ntype DocumentDriveLocalState{\\n sharingType: String\\n listeners: [Listener!]!\\n triggers: [Trigger!]!\\n availableOffline: Boolean!\\n}\",\n\t\t\t\tinitialValue: \"\\\"{ \\\\\\\"listeners\\\\\\\": [], \\\\\\\"triggers\\\\\\\": [], \\\\\\\"sharingType\\\\\\\": \\\\\\\"private\\\\\\\", \\\\\\\"availableOffline\\\\\\\": false}\\\"\",\n\t\t\t\texamples: []\n\t\t\t}\n\t\t},\n\t\tmodules: [{\n\t\t\tid: \"GRzuvv78tBvmB6ciitokLfonNHA=\",\n\t\t\tname: \"Node\",\n\t\t\tdescription: \"\",\n\t\t\toperations: [\n\t\t\t\t{\n\t\t\t\t\tid: \"7xiTdxonc9yEASR8sfV/KnbSV10=\",\n\t\t\t\t\tname: \"ADD_FILE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input AddFileInput {\\n id: ID!\\n name: String!\\n documentType: String!\\n parentFolder: ID\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"4lzNMMKKdIAtEU6i12xLgi9hp+U=\",\n\t\t\t\t\tname: \"ADD_FOLDER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input AddFolderInput {\\n id: ID!\\n name: String!\\n parentFolder: ID\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"53jH2/3TWTTcgCJiv2C+BmuC6i0=\",\n\t\t\t\t\tname: \"DELETE_NODE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input DeleteNodeInput {\\n id: ID!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"pNn+Y1/HVq/GNMk7t0u3g3gtMLE=\",\n\t\t\t\t\tname: \"UPDATE_FILE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input UpdateFileInput {\\n id: ID!\\n parentFolder: ID\\n name: String\\n documentType: String\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"P0x1M8Mnt+Q/+9nggkwgVbfybsc=\",\n\t\t\t\t\tname: \"UPDATE_NODE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input UpdateNodeInput {\\n id: ID!\\n parentFolder: ID\\n name: String\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"vnQ7OB5b3wGLgjhbgJqAIpA+JLE=\",\n\t\t\t\t\tname: \"COPY_NODE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input CopyNodeInput {\\n srcId: ID!\\n targetId: ID!\\n targetName: String\\n targetParentFolder: ID\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"VNyiD/sNGzk6k9A1Qe7s8dmrJxA=\",\n\t\t\t\t\tname: \"MOVE_NODE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input MoveNodeInput {\\n srcFolder: ID!\\n targetParentFolder: ID\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t}\n\t\t\t]\n\t\t}, {\n\t\t\tid: \"0dHwHlxOM9x0vMZ+gLnKxf2qTEo=\",\n\t\t\tname: \"Drive\",\n\t\t\tdescription: \"\",\n\t\t\toperations: [\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z1dsU=\",\n\t\t\t\t\tname: \"SET_DRIVE_NAME\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetDriveNameInput {\\n name: String!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z30dsU=\",\n\t\t\t\t\tname: \"SET_DRIVE_ICON\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetDriveIconInput {\\n icon: String!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z2dsU=\",\n\t\t\t\t\tname: \"SET_SHARING_TYPE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetSharingTypeInput {\\n type: String!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z3dsU=\",\n\t\t\t\t\tname: \"SET_AVAILABLE_OFFLINE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetAvailableOfflineInput {\\n availableOffline: Boolean!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z9dsU=\",\n\t\t\t\t\tname: \"ADD_LISTENER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input ListenerFilterInput {\\n documentType: [String!]\\n documentId: [ID!]\\n scope: [String!]\\n branch: [String!]\\n}\\n\\ninput ListenerCallInfoInput {\\n transmitterType: TransmitterType\\n name: String\\n data: String\\n}\\n\\ninput ListenerInput {\\n listenerId: ID!\\n label: String\\n block: Boolean!\\n system: Boolean!\\n filter: ListenerFilterInput!\\n callInfo: ListenerCallInfoInput\\n}\\n\\ninput AddListenerInput {\\n listener: ListenerInput!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z10dsU=\",\n\t\t\t\t\tname: \"REMOVE_LISTENER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input RemoveListenerInput {\\n listenerId: String!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z20dsU=\",\n\t\t\t\t\tname: \"ADD_TRIGGER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input PullResponderTriggerDataInput {\\n listenerId: ID!\\n url: String!\\n interval: String!\\n}\\n\\ninput TriggerInput {\\n id: ID!\\n type: TriggerType!\\n data: PullResponderTriggerDataInput\\n}\\n\\ninput AddTriggerInput {\\n trigger: TriggerInput!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"qGCiPGpTt/cyz3HzyrBn92z30dsU=\",\n\t\t\t\t\tname: \"REMOVE_TRIGGER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input RemoveTriggerInput {\\n triggerId: String!\\n}\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t}\n\t\t\t]\n\t\t}]\n\t}]\n};\n//#endregion\n//#region document-drive/gen/document-type.ts\nconst driveDocumentType = \"powerhouse/document-drive\";\n//#endregion\n//#region document-drive/gen/document-schema.ts\n/** Schema for validating the header object of a Drive document */\nconst DriveDocumentHeaderSchema = BaseDocumentHeaderSchema.extend({ documentType: z.literal(driveDocumentType) });\n/** Schema for validating the state object of a Drive document */\nconst DrivePHStateSchema = BaseDocumentStateSchema.extend({\n\tglobal: DocumentDriveStateSchema(),\n\tlocal: DocumentDriveLocalStateSchema()\n});\nconst DriveDocumentSchema = z.object({\n\theader: DriveDocumentHeaderSchema,\n\tstate: DrivePHStateSchema,\n\tinitialState: DrivePHStateSchema\n});\n/** Simple helper function to check if a state object is a Drive document state object */\nfunction isDriveState(state) {\n\treturn DrivePHStateSchema.safeParse(state).success;\n}\n/** Simple helper function to assert that a document state object is a Drive document state object */\nfunction assertIsDriveState(state) {\n\tDrivePHStateSchema.parse(state);\n}\n/** Simple helper function to check if a document is a Drive document */\nfunction isDriveDocument(document) {\n\treturn DriveDocumentSchema.safeParse(document).success;\n}\n/** Simple helper function to assert that a document is a Drive document */\nfunction assertIsDriveDocument(document) {\n\tDriveDocumentSchema.parse(document);\n}\n//#endregion\n//#region document-drive/gen/ph-factories.ts\n/**\n* Factory methods for creating DocumentDriveDocument instances\n*/\nfunction defaultGlobalState() {\n\treturn {\n\t\ticon: null,\n\t\tname: \"\",\n\t\tnodes: []\n\t};\n}\nfunction defaultLocalState() {\n\treturn {\n\t\tavailableOffline: false,\n\t\tlisteners: [],\n\t\tsharingType: null,\n\t\ttriggers: []\n\t};\n}\nfunction defaultPHState() {\n\treturn {\n\t\t...defaultBaseState(),\n\t\tglobal: defaultGlobalState(),\n\t\tlocal: defaultLocalState()\n\t};\n}\nfunction createGlobalState(state) {\n\treturn {\n\t\t...defaultGlobalState(),\n\t\t...state || {}\n\t};\n}\nfunction createLocalState(state) {\n\treturn {\n\t\t...defaultLocalState(),\n\t\t...state || {}\n\t};\n}\nfunction createState(baseState, globalState, localState) {\n\treturn {\n\t\t...createBaseState(baseState?.auth, baseState?.document),\n\t\tglobal: createGlobalState(globalState),\n\t\tlocal: createLocalState(localState)\n\t};\n}\n//#endregion\n//#region document-drive/src/reducers/drive.ts\nconst driveReducer = {\n\tsetDriveNameOperation(state, action, dispatch) {\n\t\tstate.name = action.input.name;\n\t},\n\tsetDriveIconOperation(state, action, dispatch) {\n\t\tstate.icon = action.input.icon;\n\t},\n\tsetSharingTypeOperation(state, action, dispatch) {\n\t\tstate.sharingType = action.input.type;\n\t},\n\tsetAvailableOfflineOperation(state, action, dispatch) {\n\t\tstate.availableOffline = action.input.availableOffline;\n\t},\n\taddListenerOperation(state, action, dispatch) {\n\t\tconst { listener: input } = action.input;\n\t\tif (state.listeners.find((l) => l.listenerId === input.listenerId)) throw new Error(`A listener with Id: ${input.listenerId} already exists`);\n\t\tconst listener = {\n\t\t\tlistenerId: input.listenerId,\n\t\t\tlabel: input.label ?? null,\n\t\t\tblock: input.block,\n\t\t\tsystem: input.system,\n\t\t\tfilter: {\n\t\t\t\tdocumentType: input.filter.documentType ?? null,\n\t\t\t\tdocumentId: input.filter.documentId ?? null,\n\t\t\t\tscope: input.filter.scope ?? null,\n\t\t\t\tbranch: input.filter.branch ?? null\n\t\t\t},\n\t\t\tcallInfo: input.callInfo ? {\n\t\t\t\ttransmitterType: input.callInfo.transmitterType ?? null,\n\t\t\t\tname: input.callInfo.name ?? null,\n\t\t\t\tdata: input.callInfo.data ?? null\n\t\t\t} : null\n\t\t};\n\t\tstate.listeners.push(listener);\n\t},\n\tremoveListenerOperation(state, action, dispatch) {\n\t\tstate.listeners = state.listeners.filter((listener) => listener.listenerId !== action.input.listenerId);\n\t},\n\taddTriggerOperation(state, action, dispatch) {\n\t\tconst { trigger: input } = action.input;\n\t\tif (state.triggers.find((t) => t.id === input.id)) throw new Error(`A trigger with Id: ${input.id} already exists`);\n\t\tconst trigger = {\n\t\t\tid: input.id,\n\t\t\ttype: input.type,\n\t\t\tdata: input.data ? { ...input.data } : null\n\t\t};\n\t\tstate.triggers.push(trigger);\n\t},\n\tremoveTriggerOperation(state, action, dispatch) {\n\t\tstate.triggers = state.triggers.filter((trigger) => trigger.id !== action.input.triggerId);\n\t}\n};\n//#endregion\n//#region document-drive/src/utils.ts\nfunction isFileNode(node) {\n\treturn node.kind === \"file\";\n}\nfunction isFolderNode(node) {\n\treturn node.kind === \"folder\";\n}\nfunction getAncestors(node, allNodes) {\n\tif (!node.parentFolder) return [];\n\telse {\n\t\tconst parentNode = allNodes.find((_node) => _node.id === node.parentFolder);\n\t\tif (!parentNode) throw new Error(`Parent node with id ${node.parentFolder} not found`);\n\t\treturn [parentNode, ...getAncestors(parentNode, allNodes)];\n\t}\n}\nfunction getDescendants(node, allNodes) {\n\tconst children = allNodes.filter((_node) => _node.parentFolder === node.id);\n\tconst descendants = children.map((child) => getDescendants(child, allNodes));\n\treturn [...children, ...descendants.flat()];\n}\n/**\n* Generates a copy of nodes based on the provided source and target information.\n* @param src - The source information for generating the copy.\n* @param idGenerator - The function used to generate new IDs for the copied nodes.\n* @param nodes - The array of nodes to copy from.\n* @returns An array of copied nodes with updated IDs and parent folders.\n* @throws Error if the root node with the specified ID is not found.\n*/\nfunction generateNodesCopy(src, idGenerator, nodes) {\n\tconst rootNode = nodes.find((node) => node.id === src.srcId);\n\tif (!rootNode) throw new Error(`Node with id ${src.srcId} not found`);\n\tconst nodesToCopy = [{\n\t\t...rootNode,\n\t\tname: src.targetName || rootNode.name,\n\t\tparentFolder: src.targetParentFolder || null\n\t}, ...getDescendants(rootNode, nodes)];\n\tconst ids = {};\n\tif (src.targetParentFolder) ids[src.targetParentFolder] = src.targetParentFolder;\n\tconst getNewNodeId = (node) => {\n\t\tlet newId = ids[node.id];\n\t\tif (!newId) {\n\t\t\tconst oldId = node.id;\n\t\t\tnewId = idGenerator(node);\n\t\t\tids[oldId] = newId;\n\t\t}\n\t\treturn newId;\n\t};\n\treturn nodesToCopy.map((node) => ({\n\t\tsrcId: node.id,\n\t\ttargetId: getNewNodeId(node),\n\t\ttargetName: node.name,\n\t\ttargetParentFolder: node.parentFolder ? ids[node.parentFolder] : null\n\t}));\n}\nfunction getNextCopyNumber(files, baseFilename) {\n\tlet maxNumber = 0;\n\tconst regex = new RegExp(`^${escapeRegExp(baseFilename)} \\\\(copy\\\\)(?: (\\\\d+))?$`);\n\tfor (const file of files) {\n\t\tconst match = file.match(regex);\n\t\tif (match) {\n\t\t\tconst number = match[1] ? parseInt(match[1], 10) : 1;\n\t\t\tif (number > maxNumber) maxNumber = number;\n\t\t}\n\t}\n\treturn maxNumber + 1;\n}\nfunction escapeRegExp(string) {\n\treturn string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\nfunction handleTargetNameCollisions(params) {\n\tconst { nodes, targetParentFolder, srcName, srcKind } = params;\n\tconst targetNodeChildrenNames = nodes.filter((node) => targetParentFolder === \"\" ? node.parentFolder === null : node.parentFolder === targetParentFolder).filter((node) => node.kind === srcKind).map((node) => node.name);\n\treturn targetNodeChildrenNames.includes(srcName) ? `${srcName} (copy) ${getNextCopyNumber(targetNodeChildrenNames, srcName)}` : srcName;\n}\nconst isValidName = (name) => {\n\treturn name.trim().length > 0 && !/[\\u0000-\\u001F\\u007F]/.test(name);\n};\n//#endregion\n//#region document-drive/src/reducers/node.ts\nconst nodeReducer = {\n\taddFileOperation(state, action, dispatch) {\n\t\tif (state.nodes.find((node) => node.id === action.input.id)) throw new Error(`Node with id ${action.input.id} already exists!`);\n\t\tif (!isValidName(action.input.name)) throw new Error(`Invalid name: '${action.input.name}'. Names must not be empty or contain control characters.`);\n\t\tconst name = handleTargetNameCollisions({\n\t\t\tnodes: state.nodes,\n\t\t\tsrcName: action.input.name,\n\t\t\tsrcKind: \"file\",\n\t\t\ttargetParentFolder: action.input.parentFolder || null\n\t\t});\n\t\tconst fileNode = {\n\t\t\tid: action.input.id,\n\t\t\tname,\n\t\t\tkind: \"file\",\n\t\t\tparentFolder: action.input.parentFolder ?? null,\n\t\t\tdocumentType: action.input.documentType\n\t\t};\n\t\tstate.nodes.push(fileNode);\n\t\tstate.nodes.sort((a, b) => a.id.localeCompare(b.id));\n\t\tdispatch?.({\n\t\t\ttype: \"CREATE_CHILD_DOCUMENT\",\n\t\t\tinput: {\n\t\t\t\tid: action.input.id,\n\t\t\t\tdocumentType: action.input.documentType\n\t\t\t}\n\t\t});\n\t},\n\taddFolderOperation(state, action) {\n\t\tif (state.nodes.find((node) => node.id === action.input.id)) throw new Error(`Node with id ${action.input.id} already exists!`);\n\t\tif (!isValidName(action.input.name)) throw new Error(`Invalid name: '${action.input.name}'. Names must not be empty or contain control characters.`);\n\t\tconst name = handleTargetNameCollisions({\n\t\t\tnodes: state.nodes,\n\t\t\tsrcName: action.input.name,\n\t\t\tsrcKind: \"folder\",\n\t\t\ttargetParentFolder: action.input.parentFolder || null\n\t\t});\n\t\tstate.nodes.push({\n\t\t\t...action.input,\n\t\t\tname,\n\t\t\tkind: \"folder\",\n\t\t\tparentFolder: action.input.parentFolder ?? null\n\t\t});\n\t\tstate.nodes.sort((a, b) => a.id.localeCompare(b.id));\n\t},\n\tdeleteNodeOperation(state, action, dispatch) {\n\t\tconst node = state.nodes.find((node) => node.id === action.input.id);\n\t\tif (!node) throw new Error(`Node with id ${action.input.id} not found`);\n\t\tconst descendants = getDescendants(node, state.nodes);\n\t\tstate.nodes = state.nodes.filter((node) => node.id !== action.input.id && !descendants.find((descendant) => descendant.id === node.id));\n\t\t[node, ...descendants].filter((node) => isFileNode(node)).forEach((node) => {\n\t\t\tdispatch?.({\n\t\t\t\ttype: \"DELETE_CHILD_DOCUMENT\",\n\t\t\t\tinput: { id: node.id }\n\t\t\t});\n\t\t});\n\t},\n\tupdateFileOperation(state, action) {\n\t\tif (action.input.name && !isValidName(action.input.name)) throw new Error(`Invalid name: '${action.input.name}'. Names must not be empty or contain control characters.`);\n\t\tstate.nodes = state.nodes.map((node) => node.id === action.input.id ? {\n\t\t\t...node,\n\t\t\tname: handleTargetNameCollisions({\n\t\t\t\tnodes: state.nodes.filter((n) => n.id !== action.input.id),\n\t\t\t\tsrcName: action.input.name ?? node.name,\n\t\t\t\tsrcKind: \"file\",\n\t\t\t\ttargetParentFolder: action.input.parentFolder ?? node.parentFolder\n\t\t\t}),\n\t\t\tdocumentType: action.input.documentType ?? node.documentType\n\t\t} : node);\n\t\tstate.nodes.sort((a, b) => a.id.localeCompare(b.id));\n\t},\n\tupdateNodeOperation(state, action) {\n\t\tif (action.input.name && !isValidName(action.input.name)) throw new Error(`Invalid name: '${action.input.name}'. Names must not be empty or contain control characters.`);\n\t\tstate.nodes = state.nodes.map((node) => node.id === action.input.id ? {\n\t\t\t...node,\n\t\t\tname: handleTargetNameCollisions({\n\t\t\t\tnodes: state.nodes.filter((n) => n.id !== action.input.id),\n\t\t\t\tsrcName: action.input.name ?? node.name,\n\t\t\t\tsrcKind: node.kind === \"file\" ? \"file\" : \"folder\",\n\t\t\t\ttargetParentFolder: action.input.parentFolder ?? node.parentFolder\n\t\t\t}),\n\t\t\tparentFolder: action.input.parentFolder === null ? null : node.parentFolder\n\t\t} : node);\n\t\tstate.nodes.sort((a, b) => a.id.localeCompare(b.id));\n\t},\n\tcopyNodeOperation(state, action, dispatch) {\n\t\tconst node = state.nodes.find((node) => node.id === action.input.srcId);\n\t\tif (!node) throw new Error(`Node with id ${action.input.srcId} not found`);\n\t\tif (state.nodes.find((node) => node.id === action.input.targetId)) throw new Error(`Node with id ${action.input.targetId} already exists`);\n\t\tconst name = handleTargetNameCollisions({\n\t\t\tnodes: state.nodes,\n\t\t\tsrcName: action.input.targetName || node.name,\n\t\t\tsrcKind: node.kind === \"file\" ? \"file\" : \"folder\",\n\t\t\ttargetParentFolder: action.input.targetParentFolder || null\n\t\t});\n\t\tconst newNode = {\n\t\t\t...node,\n\t\t\tid: action.input.targetId,\n\t\t\tslug: action.input.targetId,\n\t\t\tname,\n\t\t\tparentFolder: action.input.targetParentFolder || null\n\t\t};\n\t\tstate.nodes.push(newNode);\n\t\tstate.nodes.sort((a, b) => a.id.localeCompare(b.id));\n\t\tif (isFileNode(newNode)) dispatch?.({\n\t\t\ttype: \"COPY_CHILD_DOCUMENT\",\n\t\t\tinput: {\n\t\t\t\tid: action.input.srcId,\n\t\t\t\tnewId: action.input.targetId\n\t\t\t}\n\t\t});\n\t},\n\tmoveNodeOperation(state, action) {\n\t\tif (action.input.srcFolder === action.input.targetParentFolder) throw new Error(\"Circular Reference Error: Attempting to move a node to its current parent folder\");\n\t\tconst node = state.nodes.find((node) => node.id === action.input.srcFolder);\n\t\tif (!node) throw new Error(`Node with id ${action.input.srcFolder} not found`);\n\t\tconst name = handleTargetNameCollisions({\n\t\t\tnodes: state.nodes,\n\t\t\tsrcName: node.name,\n\t\t\tsrcKind: node.kind === \"file\" ? \"file\" : \"folder\",\n\t\t\ttargetParentFolder: action.input.targetParentFolder || null\n\t\t});\n\t\tif (isFolderNode(node)) {\n\t\t\tif (getDescendants(node, state.nodes).find((descendant) => descendant.id === action.input.targetParentFolder)) throw new Error(\"Circular Reference Error: Cannot move a folder to one of its descendants\");\n\t\t}\n\t\tstate.nodes = state.nodes.map((node) => {\n\t\t\tif (node.id === action.input.srcFolder) return {\n\t\t\t\t...node,\n\t\t\t\tname,\n\t\t\t\tparentFolder: action.input.targetParentFolder || null\n\t\t\t};\n\t\t\treturn node;\n\t\t});\n\t\tstate.nodes.sort((a, b) => a.id.localeCompare(b.id));\n\t}\n};\n//#endregion\n//#region document-drive/gen/reducer.ts\nconst driveStateReducer = (state, action, dispatch) => {\n\tif (isDocumentAction(action)) return state;\n\tconst typedAction = action;\n\tswitch (typedAction.type) {\n\t\tcase \"ADD_FILE\":\n\t\t\tAddFileInputSchema().parse(typedAction.input);\n\t\t\tnodeReducer.addFileOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"ADD_FOLDER\":\n\t\t\tAddFolderInputSchema().parse(typedAction.input);\n\t\t\tnodeReducer.addFolderOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"DELETE_NODE\":\n\t\t\tDeleteNodeInputSchema().parse(typedAction.input);\n\t\t\tnodeReducer.deleteNodeOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"UPDATE_FILE\":\n\t\t\tUpdateFileInputSchema().parse(typedAction.input);\n\t\t\tnodeReducer.updateFileOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"UPDATE_NODE\":\n\t\t\tUpdateNodeInputSchema().parse(typedAction.input);\n\t\t\tnodeReducer.updateNodeOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"COPY_NODE\":\n\t\t\tCopyNodeInputSchema().parse(typedAction.input);\n\t\t\tnodeReducer.copyNodeOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"MOVE_NODE\":\n\t\t\tMoveNodeInputSchema().parse(typedAction.input);\n\t\t\tnodeReducer.moveNodeOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"SET_DRIVE_NAME\":\n\t\t\tSetDriveNameInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.setDriveNameOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"SET_DRIVE_ICON\":\n\t\t\tSetDriveIconInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.setDriveIconOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"SET_SHARING_TYPE\":\n\t\t\tSetSharingTypeInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.setSharingTypeOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"SET_AVAILABLE_OFFLINE\":\n\t\t\tSetAvailableOfflineInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.setAvailableOfflineOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"ADD_LISTENER\":\n\t\t\tAddListenerInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.addListenerOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"REMOVE_LISTENER\":\n\t\t\tRemoveListenerInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.removeListenerOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"ADD_TRIGGER\":\n\t\t\tAddTriggerInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.addTriggerOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tcase \"REMOVE_TRIGGER\":\n\t\t\tRemoveTriggerInputSchema().parse(typedAction.input);\n\t\t\tdriveReducer.removeTriggerOperation(state[typedAction.scope], action, dispatch);\n\t\t\tbreak;\n\t\tdefault: return state;\n\t}\n};\nconst driveDocumentReducer = createReducer(driveStateReducer);\n//#endregion\n//#region document-drive/gen/utils.ts\nconst initialGlobalState = {\n\tname: \"\",\n\tnodes: [],\n\ticon: null\n};\nconst initialLocalState = {\n\tlisteners: [],\n\ttriggers: [],\n\tsharingType: \"private\",\n\tavailableOffline: false\n};\nconst driveCreateState = (state) => {\n\treturn {\n\t\t...defaultBaseState(),\n\t\tglobal: {\n\t\t\t...initialGlobalState,\n\t\t\t...state?.global\n\t\t},\n\t\tlocal: {\n\t\t\t...initialLocalState,\n\t\t\t...state?.local\n\t\t}\n\t};\n};\nconst driveCreateDocument = (state) => {\n\treturn baseCreateDocument(driveCreateState, state, driveDocumentType);\n};\nconst driveSaveToFileHandle = (document, input) => {\n\treturn baseSaveToFileHandle(document, input);\n};\nconst driveLoadFromInput = (input) => {\n\treturn baseLoadFromInput(input, driveDocumentReducer);\n};\nconst isStateOfType = (state) => {\n\treturn isDriveState(state);\n};\nconst assertIsStateOfType = (state) => {\n\tassertIsDriveState(state);\n};\nconst isDocumentOfType = (document) => {\n\treturn isDriveDocument(document);\n};\nconst assertIsDocumentOfType = (document) => {\n\tassertIsDriveDocument(document);\n};\n//#endregion\n//#region document-drive/module.ts\nconst driveDocumentModelModule = {\n\tactions: creators_exports,\n\treducer: driveDocumentReducer,\n\tdocumentModel: createState$1(defaultBaseState(), driveDocumentModel),\n\tutils: {\n\t\tfileExtension: driveDocumentFileExtension,\n\t\tcreateState: driveCreateState,\n\t\tcreateDocument: driveCreateDocument,\n\t\tloadFromInput: driveLoadFromInput,\n\t\tsaveToFileHandle: driveSaveToFileHandle,\n\t\tisStateOfType,\n\t\tassertIsStateOfType,\n\t\tisDocumentOfType,\n\t\tassertIsDocumentOfType\n\t}\n};\n//#endregion\nexport { AddFileInputSchema, AddFolderInputSchema, AddListenerInputSchema, AddTriggerInputSchema, CopyNodeInputSchema, DeleteNodeInputSchema, DocumentDriveLocalStateSchema, DocumentDriveStateSchema, DriveDocumentHeaderSchema, DriveDocumentSchema, DrivePHStateSchema, FileNodeSchema, FolderNodeSchema, ListenerCallInfoInputSchema, ListenerCallInfoSchema, ListenerFilterInputSchema, ListenerFilterSchema, ListenerInputSchema, ListenerSchema, MoveNodeInputSchema, NodeSchema, PullResponderTriggerDataInputSchema, PullResponderTriggerDataSchema, RemoveListenerInputSchema, RemoveTriggerInputSchema, SetAvailableOfflineInputSchema, SetDriveIconInputSchema, SetDriveNameInputSchema, SetSharingTypeInputSchema, TransmitterTypeSchema, TriggerDataSchema, TriggerInputSchema, TriggerSchema, TriggerTypeSchema, UpdateFileInputSchema, UpdateNodeInputSchema, addFile, addFolder, addListener, addTrigger, assertIsDocumentOfType, assertIsDriveDocument, assertIsDriveState, assertIsStateOfType, copyNode, createGlobalState, createLocalState, createState, defaultGlobalState, defaultLocalState, defaultPHState, definedNonNullAnySchema, deleteNode, driveCreateDocument, driveCreateState, driveDocumentFileExtension, driveDocumentModel, driveDocumentModelModule, driveDocumentReducer, driveDocumentType, driveLoadFromInput, driveReducer, driveSaveToFileHandle, escapeRegExp, generateNodesCopy, getAncestors, getDescendants, getNextCopyNumber, handleTargetNameCollisions, initialGlobalState, initialLocalState, isDefinedNonNullAny, isDocumentOfType, isDriveDocument, isDriveState, isFileNode, isFolderNode, isStateOfType, isValidName, moveNode, nodeReducer, removeListener, removeTrigger, setAvailableOffline, setDriveIcon, setDriveName, setSharingType, updateFile, updateNode };\n\n//# sourceMappingURL=index.js.map","import { A as parsePagingOptions, C as DuplicateManifestError, D as DocumentDeletedError, E as ModuleNotFoundError, O as DocumentNotFoundError, S as CollectionMembershipCache, T as InvalidModuleError, _ as KyselyWriteCache, a as createForwardingPoolInstrumentation, b as createConsistencyToken, c as DuplicateOperationError, d as KyselyKeyframeStore, f as DocumentModelRegistry, g as EventBus, h as KyselyExecutionScope, i as runMigrations, j as throwIfAborted, k as matchesScope, l as OptimisticLockError, m as DriveCollectionId, n as REACTOR_SCHEMA, o as instrumentPgPool, p as SimpleJobExecutor, r as getMigrationStatus, s as KyselyOperationStore, t as DEFAULT_DRIVE_CONTAINER_TYPES, u as RevisionMismatchError, v as KyselyOperationIndex, w as DuplicateModuleError, x as createEmptyConsistencyToken, y as DocumentMetaCache } from \"./drive-container-types-BxnXaOAp.js\";\nimport { n as ReactorEventTypes, t as EventBusAggregateError } from \"./types-CxSpmNGK.js\";\nimport { i as WorkerInitFailedError, r as WorkerExitedError, t as WorkerAbortTimeoutError } from \"./errors-D3S6Eysd.js\";\nimport { a as ReadModelCoordinator, i as KyselyDocumentView, n as ConsistencyTracker, o as BaseReadModel, r as makeConsistencyKey, t as KyselyDocumentIndexer } from \"./document-indexer-B2iLRB0o.js\";\nimport { n as errorToInfo, r as sanitizeArg, t as createForwardingLogger } from \"./forwarding-logger-BBkMSxuJ.js\";\nimport { t as workerEntryPath } from \"./worker-XYrQaEmt.js\";\nimport { actions, actions as documentActions, createPresignedHeader, generateId, hashDocumentStateForScope, replayDocument } from \"@powerhousedao/shared/document-model\";\nimport { addFile, addFolder, copyNode, deleteNode, driveCreateDocument, generateNodesCopy, getDescendants, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from \"@powerhousedao/shared/document-drive\";\nimport { v4 } from \"uuid\";\nimport { ConsoleLogger } from \"document-model\";\nimport { sql } from \"kysely\";\nimport { RelationalDbProcessor, createRelationalDb } from \"@powerhousedao/shared/processors\";\n//#region src/actions/index.ts\n/**\n* Creates a CREATE_DOCUMENT action for document creation.\n*/\nfunction createDocumentAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"CREATE_DOCUMENT\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\n/**\n* Creates an UPGRADE_DOCUMENT action to set initial document state.\n*/\nfunction upgradeDocumentAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"UPGRADE_DOCUMENT\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\n/**\n* Creates a DELETE_DOCUMENT action for document deletion.\n*/\nfunction deleteDocumentAction(documentId) {\n\tconst input = { documentId };\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"DELETE_DOCUMENT\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\n/**\n* Creates an ADD_RELATIONSHIP action that records a directed edge from\n* `sourceId` to `targetId` with an arbitrary `relationshipType` and optional\n* `metadata`. The edge is opaque to the reactor — consumers (e.g. reactor-drive)\n* define their own type strings such as `\"drive/child\"` and attach\n* domain-specific metadata.\n*/\nfunction addRelationshipAction(sourceId, targetId, relationshipType, metadata) {\n\tconst input = {\n\t\tsourceId,\n\t\ttargetId,\n\t\trelationshipType,\n\t\t...metadata !== void 0 ? { metadata } : {}\n\t};\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"ADD_RELATIONSHIP\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\n/**\n* Creates an UPDATE_RELATIONSHIP action to replace a relationship's metadata\n* without losing its createdAt ordering.\n*/\nfunction updateRelationshipAction(sourceId, targetId, relationshipType, metadata) {\n\tconst input = {\n\t\tsourceId,\n\t\ttargetId,\n\t\trelationshipType,\n\t\tmetadata\n\t};\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"UPDATE_RELATIONSHIP\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\n/**\n* Creates a REMOVE_RELATIONSHIP action to remove a parent-child relationship.\n*/\nfunction removeRelationshipAction(sourceId, targetId, relationshipType = \"child\") {\n\tconst input = {\n\t\tsourceId,\n\t\ttargetId,\n\t\trelationshipType\n\t};\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"REMOVE_RELATIONSHIP\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\n//#endregion\n//#region src/core/utils.ts\n/**\n* Validates structural properties shared by all batch requests:\n* duplicate keys, missing dependencies, and dependency cycles.\n*/\nfunction validateBatchStructure(jobs) {\n\tconst keys = /* @__PURE__ */ new Set();\n\tfor (const job of jobs) {\n\t\tif (keys.has(job.key)) throw new Error(`Duplicate plan key: ${job.key}`);\n\t\tkeys.add(job.key);\n\t}\n\tfor (const job of jobs) for (const depKey of job.dependsOn) if (!keys.has(depKey)) throw new Error(`Job '${job.key}' depends on non-existent key: ${depKey}`);\n\tconst visited = /* @__PURE__ */ new Set();\n\tconst recStack = /* @__PURE__ */ new Set();\n\tconst detectCycle = (key) => {\n\t\tvisited.add(key);\n\t\trecStack.add(key);\n\t\tconst job = jobs.find((j) => j.key === key);\n\t\tif (job) {\n\t\t\tfor (const depKey of job.dependsOn) if (!visited.has(depKey)) {\n\t\t\t\tif (detectCycle(depKey)) return true;\n\t\t\t} else if (recStack.has(depKey)) return true;\n\t\t}\n\t\trecStack.delete(key);\n\t\treturn false;\n\t};\n\tfor (const job of jobs) if (!visited.has(job.key)) {\n\t\tif (detectCycle(job.key)) throw new Error(`Dependency cycle detected involving key: ${job.key}`);\n\t}\n}\n/**\n* Validates a batch mutation request for common errors\n*/\nfunction validateBatchRequest(jobs) {\n\tvalidateBatchStructure(jobs);\n\tfor (const job of jobs) if (job.actions.length === 0) throw new Error(`Job '${job.key}' has empty actions array`);\n}\n/**\n* Validates a batch load request for common errors\n*/\nfunction validateBatchLoadRequest(jobs) {\n\tvalidateBatchStructure(jobs);\n\tfor (const job of jobs) if (job.operations.length === 0) throw new Error(`Job '${job.key}' has empty operations array`);\n}\n/**\n* Validates that all actions in a job match the declared scope\n*/\nfunction validateActionScopes(job) {\n\tfor (const action of job.actions) {\n\t\tconst actionScope = action.scope || \"global\";\n\t\tif (actionScope !== job.scope) throw new Error(`Job '${job.key}' declares scope '${job.scope}' but action has scope '${actionScope}'`);\n\t}\n}\n/**\n* Validates that all operations in a job match the declared scope\n*/\nfunction validateOperationScopes(job) {\n\tfor (const operation of job.operations) {\n\t\tconst operationScope = operation.action.scope || \"global\";\n\t\tif (operationScope !== job.scope) throw new Error(`Job '${job.key}' declares scope '${job.scope}' but operation has scope '${operationScope}'`);\n\t}\n}\n/**\n* Performs topological sort on jobs based on dependencies\n*/\nfunction topologicalSort(jobs) {\n\tconst result = [];\n\tconst visited = /* @__PURE__ */ new Set();\n\tconst visit = (key) => {\n\t\tif (visited.has(key)) return;\n\t\tvisited.add(key);\n\t\tconst job = jobs.find((j) => j.key === key);\n\t\tif (job) for (const depKey of job.dependsOn) visit(depKey);\n\t\tresult.push(key);\n\t};\n\tfor (const job of jobs) visit(job.key);\n\treturn result;\n}\n/**\n* Converts an Error or string to ErrorInfo\n*/\nfunction toErrorInfo$1(error) {\n\tif (error instanceof Error) return {\n\t\tmessage: error.message,\n\t\tstack: error.stack || (/* @__PURE__ */ new Error()).stack || \"\"\n\t};\n\treturn {\n\t\tmessage: error,\n\t\tstack: (/* @__PURE__ */ new Error()).stack || \"\"\n\t};\n}\n/**\n* Filters paged results by document type\n*/\nfunction filterByType(results, type) {\n\treturn {\n\t\tresults: results.results.filter((document) => document.header.documentType === type),\n\t\toptions: results.options,\n\t\tnextCursor: results.nextCursor,\n\t\tnext: results.next ? async () => {\n\t\t\treturn filterByType(await results.next(), type);\n\t\t} : void 0\n\t};\n}\n/**\n* Validates that all operations share the same scope.\n* Throws an error if any operation has a different scope.\n*/\nfunction getSharedOperationScope(operations) {\n\tif (operations.length === 0) throw new Error(\"No operations provided\");\n\tconst baseScope = operations[0].action.scope;\n\tfor (const [index, operation] of operations.entries()) {\n\t\tconst scope = operation.action.scope;\n\t\tif (scope !== baseScope) throw new Error(`All operations in load must share the same scope. Expected '${baseScope}', received '${scope}' at position ${index}`);\n\t}\n\treturn baseScope;\n}\n/**\n* Validates that all actions share the same scope.\n* Throws an error if any action has a different scope.\n*/\nfunction getSharedActionScope(actions) {\n\tif (actions.length === 0) throw new Error(\"No actions provided\");\n\tconst baseScope = actions[0].scope;\n\tfor (const action of actions) if (action.scope !== baseScope) throw new Error(`All actions must share the same scope. Expected '${baseScope}', received '${action.scope}'`);\n\treturn baseScope;\n}\n/**\n* Signs an action with the provided signer.\n* If the action already has valid signatures, it is returned unchanged.\n*/\nconst signAction = async (action, signer, signal) => {\n\tconst existingSignatures = action.context?.signer?.signatures;\n\tif (existingSignatures && existingSignatures.length > 0) return action;\n\tconst signature = await signer.signAction(action, signal);\n\treturn {\n\t\t...action,\n\t\tcontext: {\n\t\t\t...action.context,\n\t\t\tsigner: {\n\t\t\t\tuser: {\n\t\t\t\t\taddress: signer.user?.address || \"\",\n\t\t\t\t\tnetworkId: signer.user?.networkId || \"\",\n\t\t\t\t\tchainId: signer.user?.chainId || 0\n\t\t\t\t},\n\t\t\t\tapp: {\n\t\t\t\t\tname: signer.app?.name || \"\",\n\t\t\t\t\tkey: signer.app?.key || \"\"\n\t\t\t\t},\n\t\t\t\tsignatures: [signature]\n\t\t\t}\n\t\t}\n\t};\n};\n/**\n* Signs multiple actions with the provided signer\n*/\nconst signActions = async (actions, signer, signal) => {\n\treturn Promise.all(actions.map((action) => signAction(action, signer, signal)));\n};\nfunction buildSingleJobMeta(jobId, callerMeta) {\n\treturn {\n\t\t...callerMeta,\n\t\tbatchId: v4(),\n\t\tbatchJobIds: [jobId]\n\t};\n}\n//#endregion\n//#region src/shared/types.ts\n/**\n* Enum that determines deletion propagation.\n*/\nlet PropagationMode = /* @__PURE__ */ function(PropagationMode) {\n\tPropagationMode[\"None\"] = \"none\";\n\tPropagationMode[\"Cascade\"] = \"cascade\";\n\treturn PropagationMode;\n}({});\n/**\n* Enum that describes the type of relationship change.\n*/\nlet RelationshipChangeType = /* @__PURE__ */ function(RelationshipChangeType) {\n\tRelationshipChangeType[\"Added\"] = \"added\";\n\tRelationshipChangeType[\"Removed\"] = \"removed\";\n\treturn RelationshipChangeType;\n}({});\n/**\n* Job execution statuses\n*/\nlet JobStatus = /* @__PURE__ */ function(JobStatus) {\n\t/** Job is queued but not yet started */\n\tJobStatus[\"PENDING\"] = \"PENDING\";\n\t/** Job is currently being executed */\n\tJobStatus[\"RUNNING\"] = \"RUNNING\";\n\t/** Operations have been written to the operation store (JOB_WRITE_READY event) */\n\tJobStatus[\"WRITE_READY\"] = \"WRITE_READY\";\n\t/** Read models have finished indexing operations (JOB_READ_READY event) */\n\tJobStatus[\"READ_READY\"] = \"READ_READY\";\n\t/** Job failed (may be retried) */\n\tJobStatus[\"FAILED\"] = \"FAILED\";\n\treturn JobStatus;\n}({});\n//#endregion\n//#region src/client/drive-client.ts\n/**\n* Implementation of {@link IDriveClient}.\n*\n* Holds a back-reference to its parent {@link IReactorClient} for read and\n* single-document write primitives, plus direct access to {@link IReactor}\n* for batch execution. The back-reference is captured but never invoked\n* during construction, so the partial-`this` hazard does not apply.\n*/\nvar DriveClient = class {\n\tconstructor(client, logger, reactor, signer) {\n\t\tthis.client = client;\n\t\tthis.logger = logger;\n\t\tthis.reactor = reactor;\n\t\tthis.signer = signer;\n\t}\n\tasync create(input, signal) {\n\t\tthis.logger.verbose(\"drives.create(@input)\", input);\n\t\tconst driveDoc = driveCreateDocument({ global: {\n\t\t\tname: input.global.name || \"\",\n\t\t\ticon: input.global.icon ?? null,\n\t\t\tnodes: []\n\t\t} });\n\t\tif (input.preferredEditor) driveDoc.header.meta = {\n\t\t\t...driveDoc.header.meta,\n\t\t\tpreferredEditor: input.preferredEditor\n\t\t};\n\t\treturn this.client.create(driveDoc, void 0, signal);\n\t}\n\tasync addFile(driveIdentifier, document, parentFolder, signal) {\n\t\tthis.logger.verbose(\"drives.addFile(@driveIdentifier, @document, @parentFolder)\", driveIdentifier, document.header.id, parentFolder);\n\t\tconst documentId = document.header.id;\n\t\tconst documentActions = await signActions([\n\t\t\tcreateDocumentAction({\n\t\t\t\tmodel: document.header.documentType,\n\t\t\t\tversion: 0,\n\t\t\t\tdocumentId: document.header.id,\n\t\t\t\tsigning: {\n\t\t\t\t\tsignature: document.header.id,\n\t\t\t\t\tpublicKey: document.header.sig.publicKey,\n\t\t\t\t\tnonce: document.header.sig.nonce,\n\t\t\t\t\tcreatedAtUtcIso: document.header.createdAtUtcIso,\n\t\t\t\t\tdocumentType: document.header.documentType\n\t\t\t\t},\n\t\t\t\tslug: document.header.slug,\n\t\t\t\tname: document.header.name,\n\t\t\t\tbranch: document.header.branch,\n\t\t\t\tmeta: document.header.meta,\n\t\t\t\tprotocolVersions: document.header.protocolVersions ?? { \"base-reducer\": 2 }\n\t\t\t}),\n\t\t\tupgradeDocumentAction({\n\t\t\t\tdocumentId: document.header.id,\n\t\t\t\tmodel: document.header.documentType,\n\t\t\t\tfromVersion: 0,\n\t\t\t\ttoVersion: 1,\n\t\t\t\tinitialState: document.state\n\t\t\t}),\n\t\t\taddRelationshipAction(driveIdentifier, documentId, \"child\")\n\t\t], this.signer, signal);\n\t\tconst driveActions = await signActions([addFile({\n\t\t\tid: documentId,\n\t\t\tname: document.header.name || documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tparentFolder\n\t\t})], this.signer, signal);\n\t\tconst batchResult = await this.reactor.executeBatch({ jobs: [{\n\t\t\tkey: \"document\",\n\t\t\tdocumentId,\n\t\t\tscope: getSharedActionScope(documentActions),\n\t\t\tbranch: \"main\",\n\t\t\tactions: documentActions,\n\t\t\tdependsOn: []\n\t\t}, {\n\t\t\tkey: \"drive\",\n\t\t\tdocumentId: driveIdentifier,\n\t\t\tscope: getSharedActionScope(driveActions),\n\t\t\tbranch: \"main\",\n\t\t\tactions: driveActions,\n\t\t\tdependsOn: [\"document\"]\n\t\t}] }, signal);\n\t\tconst completedJobs = await Promise.all(Object.values(batchResult.jobs).map((job) => this.client.waitForJob(job, signal)));\n\t\tfor (const job of completedJobs) if (job.status === JobStatus.FAILED) throw new Error(job.error?.message);\n\t\treturn this.reactor.get(documentId);\n\t}\n\tasync addFolder(driveIdentifier, name, parentFolder, signal) {\n\t\tthis.logger.verbose(\"drives.addFolder(@driveIdentifier, @name, @parentFolder)\", driveIdentifier, name, parentFolder);\n\t\tconst folderId = generateId();\n\t\tconst node = (await this.client.execute(driveIdentifier, \"main\", [addFolder({\n\t\t\tid: folderId,\n\t\t\tname,\n\t\t\tparentFolder\n\t\t})], signal)).state.global.nodes.find((n) => n.id === folderId);\n\t\tif (!node || !isFolderNode(node)) throw new Error(\"Folder creation failed\");\n\t\treturn node;\n\t}\n\tasync removeNode(driveIdentifier, nodeId, signal) {\n\t\tthis.logger.verbose(\"drives.removeNode(@driveIdentifier, @nodeId)\", driveIdentifier, nodeId);\n\t\tconst drive = await this.client.get(driveIdentifier, void 0, signal);\n\t\tconst node = drive.state.global.nodes.find((n) => n.id === nodeId);\n\t\tif (!node) {\n\t\t\tif (!await this.documentExists(nodeId, signal)) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);\n\t\t\tawait this.removeFileNode(driveIdentifier, nodeId, signal);\n\t\t\treturn;\n\t\t}\n\t\tif (isFolderNode(node)) {\n\t\t\tconst fileDescendants = getDescendants(node, drive.state.global.nodes).filter(isFileNode);\n\t\t\tfor (const file of fileDescendants) await this.removeFileNode(driveIdentifier, file.id, signal);\n\t\t\tawait this.client.execute(driveIdentifier, \"main\", [deleteNode({ id: nodeId })], signal);\n\t\t\treturn;\n\t\t}\n\t\tawait this.removeFileNode(driveIdentifier, nodeId, signal);\n\t}\n\tasync renameNode(driveIdentifier, nodeId, name, signal) {\n\t\tthis.logger.verbose(\"drives.renameNode(@driveIdentifier, @nodeId, @name)\", driveIdentifier, nodeId, name);\n\t\tif ((await this.client.execute(nodeId, \"main\", [actions.setName({ name })], signal)).header.name !== name) throw new Error(\"Document rename did not apply\");\n\t\tconst node = (await this.client.execute(driveIdentifier, \"main\", [updateNode({\n\t\t\tid: nodeId,\n\t\t\tname\n\t\t})], signal)).state.global.nodes.find((n) => n.id === nodeId);\n\t\tif (!node) throw new Error(\"Node missing from drive after rename\");\n\t\treturn node;\n\t}\n\tasync setPreferredEditorOnNode(nodeId, preferredEditor, signal) {\n\t\tthis.logger.verbose(\"drives.setPreferredEditorOnNode(@nodeId, @preferredEditor)\", nodeId, preferredEditor);\n\t\treturn this.client.setPreferredEditor(nodeId, preferredEditor, \"main\", signal);\n\t}\n\tasync moveNode(driveIdentifier, srcNodeId, targetParentFolderId, signal) {\n\t\tthis.logger.verbose(\"drives.moveNode(@driveIdentifier, @srcNodeId, @targetParentFolderId)\", driveIdentifier, srcNodeId, targetParentFolderId);\n\t\treturn this.client.execute(driveIdentifier, \"main\", [moveNode({\n\t\t\tsrcFolder: srcNodeId,\n\t\t\ttargetParentFolder: targetParentFolderId\n\t\t})], signal);\n\t}\n\tasync copyNode(driveIdentifier, srcNodeId, targetParentFolderId, signal) {\n\t\tthis.logger.verbose(\"drives.copyNode(@driveIdentifier, @srcNodeId, @targetParentFolderId)\", driveIdentifier, srcNodeId, targetParentFolderId);\n\t\tconst drive = await this.client.get(driveIdentifier, void 0, signal);\n\t\tconst srcNode = drive.state.global.nodes.find((n) => n.id === srcNodeId);\n\t\tif (!srcNode) throw new Error(`Node ${srcNodeId} not found in drive ${driveIdentifier}`);\n\t\tconst copyPlan = generateNodesCopy({\n\t\t\tsrcId: srcNodeId,\n\t\t\ttargetParentFolder: targetParentFolderId,\n\t\t\ttargetName: srcNode.name\n\t\t}, () => generateId(), drive.state.global.nodes);\n\t\tconst resolvedNamesByTargetId = /* @__PURE__ */ new Map();\n\t\tfor (const entry of copyPlan) {\n\t\t\tconst node = drive.state.global.nodes.find((n) => n.id === entry.srcId);\n\t\t\tif (!node) continue;\n\t\t\tconst resolved = handleTargetNameCollisions({\n\t\t\t\tnodes: drive.state.global.nodes,\n\t\t\t\tsrcName: entry.targetName || node.name,\n\t\t\t\tsrcKind: isFileNode(node) ? \"file\" : \"folder\",\n\t\t\t\ttargetParentFolder: entry.targetParentFolder ?? null\n\t\t\t});\n\t\t\tresolvedNamesByTargetId.set(entry.targetId, resolved);\n\t\t}\n\t\tfor (const entry of copyPlan) {\n\t\t\tconst node = drive.state.global.nodes.find((n) => n.id === entry.srcId);\n\t\t\tif (!node || !isFileNode(node)) continue;\n\t\t\tconst srcDoc = await this.client.get(entry.srcId, void 0, signal);\n\t\t\tconst module = await this.client.getDocumentModelModule(srcDoc.header.documentType);\n\t\t\tconst duplicated = replayDocument(srcDoc.initialState, srcDoc.operations, module.reducer, createPresignedHeader(entry.targetId, srcDoc.header.documentType));\n\t\t\tconst resolvedName = resolvedNamesByTargetId.get(entry.targetId);\n\t\t\tif (resolvedName) duplicated.header.name = resolvedName;\n\t\t\tawait this.addFile(driveIdentifier, duplicated, entry.targetParentFolder ?? void 0, signal);\n\t\t}\n\t\treturn this.client.execute(driveIdentifier, \"main\", copyPlan.map((entry) => copyNode(entry)), signal);\n\t}\n\tasync getNode(driveIdentifier, nodeId, signal) {\n\t\tthis.logger.verbose(\"drives.getNode(@driveIdentifier, @nodeId)\", driveIdentifier, nodeId);\n\t\tconst node = (await this.client.get(driveIdentifier, void 0, signal)).state.global.nodes.find((n) => n.id === nodeId);\n\t\tif (!node) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);\n\t\treturn node;\n\t}\n\tasync listNodes(driveIdentifier, parentFolder, paging, signal) {\n\t\tthis.logger.verbose(\"drives.listNodes(@driveIdentifier, @parentFolder, @paging)\", driveIdentifier, parentFolder, paging);\n\t\tconst allNodes = (await this.client.get(driveIdentifier, void 0, signal)).state.global.nodes;\n\t\tconst filtered = parentFolder === void 0 ? [...allNodes] : allNodes.filter((n) => (n.parentFolder ?? null) === parentFolder);\n\t\tconst { offset: startIndex, limit } = parsePagingOptions(paging, filtered.length);\n\t\tconst effective = paging ?? {\n\t\t\tcursor: \"\",\n\t\t\tlimit\n\t\t};\n\t\tconst endIndex = startIndex + limit;\n\t\treturn {\n\t\t\tresults: filtered.slice(startIndex, endIndex),\n\t\t\toptions: effective,\n\t\t\t...endIndex < filtered.length ? { nextCursor: String(endIndex) } : {},\n\t\t\ttotalCount: filtered.length\n\t\t};\n\t}\n\tasync documentExists(documentId, signal) {\n\t\ttry {\n\t\t\tawait this.client.get(documentId, void 0, signal);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tasync removeFileNode(driveId, fileId, signal) {\n\t\tconst relationshipActions = await signActions([removeRelationshipAction(driveId, fileId, \"child\")], this.signer, signal);\n\t\tconst driveActions = await signActions([deleteNode({ id: fileId })], this.signer, signal);\n\t\tconst batchResult = await this.reactor.executeBatch({ jobs: [{\n\t\t\tkey: \"relationship\",\n\t\t\tdocumentId: driveId,\n\t\t\tscope: getSharedActionScope(relationshipActions),\n\t\t\tbranch: \"main\",\n\t\t\tactions: relationshipActions,\n\t\t\tdependsOn: []\n\t\t}, {\n\t\t\tkey: \"drive\",\n\t\t\tdocumentId: driveId,\n\t\t\tscope: getSharedActionScope(driveActions),\n\t\t\tbranch: \"main\",\n\t\t\tactions: driveActions,\n\t\t\tdependsOn: [\"relationship\"]\n\t\t}] }, signal);\n\t\tconst completedJobs = await Promise.all(Object.values(batchResult.jobs).map((job) => this.client.waitForJob(job, signal)));\n\t\tfor (const job of completedJobs) if (job.status === JobStatus.FAILED) throw new Error(job.error?.message);\n\t\tconst deleteJob = await this.reactor.deleteDocument(fileId, this.signer, signal);\n\t\tconst deleteCompleted = await this.client.waitForJob(deleteJob, signal);\n\t\tif (deleteCompleted.status === JobStatus.FAILED) throw new Error(deleteCompleted.error?.message);\n\t}\n};\n//#endregion\n//#region src/shared/awaiter.ts\n/**\n* Checks if a job status is terminal (job has finished).\n* WRITE_READY is not terminal - it's an intermediate state.\n* Only READ_READY and FAILED are truly terminal.\n*/\nfunction isTerminalStatus(status) {\n\treturn status === JobStatus.READ_READY || status === JobStatus.FAILED;\n}\n/**\n* Event-driven implementation of IJobAwaiter.\n* Subscribes to operation events to detect job completion without polling.\n*/\nvar JobAwaiter = class {\n\tpendingJobs = /* @__PURE__ */ new Map();\n\tunsubscribers = [];\n\tconstructor(eventBus, getJobStatus) {\n\t\tthis.eventBus = eventBus;\n\t\tthis.getJobStatus = getJobStatus;\n\t\tthis.subscribeToEvents();\n\t}\n\tsubscribeToEvents() {\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY, async (_type, event) => {\n\t\t\tawait this.handleWriteReady(event);\n\t\t}));\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_READ_READY, async (_type, event) => {\n\t\t\tawait this.handleReadReady(event);\n\t\t}));\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_FAILED, async (_type, event) => {\n\t\t\tawait this.handleJobFailed(event);\n\t\t}));\n\t}\n\tshutdown() {\n\t\tfor (const unsubscribe of this.unsubscribers) unsubscribe();\n\t\tthis.unsubscribers = [];\n\t\tfor (const [, waiters] of this.pendingJobs) for (const waiter of waiters) waiter.reject(/* @__PURE__ */ new Error(\"JobAwaiter destroyed\"));\n\t\tthis.pendingJobs.clear();\n\t}\n\tasync waitForJob(jobId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst currentStatus = await this.getJobStatus(jobId, signal);\n\t\tif (isTerminalStatus(currentStatus.status)) return currentStatus;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst waiter = {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\tsignal\n\t\t\t};\n\t\t\tconst existingWaiters = this.pendingJobs.get(jobId) || [];\n\t\t\texistingWaiters.push(waiter);\n\t\t\tthis.pendingJobs.set(jobId, existingWaiters);\n\t\t\tif (signal) {\n\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\tconst waiters = this.pendingJobs.get(jobId);\n\t\t\t\t\tif (waiters) {\n\t\t\t\t\t\tconst index = waiters.indexOf(waiter);\n\t\t\t\t\t\tif (index !== -1) {\n\t\t\t\t\t\t\twaiters.splice(index, 1);\n\t\t\t\t\t\t\tif (waiters.length === 0) this.pendingJobs.delete(jobId);\n\t\t\t\t\t\t\twaiter.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tsignal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t}\n\t\t});\n\t}\n\tasync handleWriteReady(event) {\n\t\tconst jobId = event.jobId;\n\t\tawait this.checkAndResolveWaiters(jobId);\n\t}\n\tasync handleReadReady(event) {\n\t\tconst jobId = event.jobId;\n\t\tawait this.checkAndResolveWaiters(jobId);\n\t}\n\tasync handleJobFailed(event) {\n\t\tawait this.checkAndResolveWaiters(event.jobId);\n\t}\n\tasync checkAndResolveWaiters(jobId) {\n\t\tconst waiters = this.pendingJobs.get(jobId);\n\t\tif (!waiters || waiters.length === 0) return;\n\t\ttry {\n\t\t\tconst activeWaiters = waiters.filter((w) => !w.signal?.aborted);\n\t\t\tif (activeWaiters.length === 0) {\n\t\t\t\tthis.pendingJobs.delete(jobId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst jobInfo = await this.getJobStatus(jobId, activeWaiters[0].signal);\n\t\t\tif (isTerminalStatus(jobInfo.status)) {\n\t\t\t\tthis.pendingJobs.delete(jobId);\n\t\t\t\tfor (const waiter of activeWaiters) waiter.resolve(jobInfo);\n\t\t\t\tfor (const waiter of waiters) if (waiter.signal?.aborted) waiter.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.pendingJobs.delete(jobId);\n\t\t\tfor (const waiter of waiters) waiter.reject(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n};\n//#endregion\n//#region src/client/cursor.ts\nconst COMPOSITE_PREFIX = \"c:\";\n/**\n* Returns true if the cursor is a composite multi-scope cursor.\n*/\nfunction isCompositeCursor(cursor) {\n\treturn cursor.startsWith(COMPOSITE_PREFIX);\n}\n/**\n* Encodes per-scope cursors into a single composite cursor string.\n* Only scopes that still have more results should be included.\n*/\nfunction encodeCompositeCursor(scopeCursors) {\n\treturn COMPOSITE_PREFIX + JSON.stringify(scopeCursors);\n}\n/**\n* Decodes a composite cursor string into a map of scope to cursor.\n* Throws if the cursor is not a valid composite cursor.\n*/\nfunction decodeCompositeCursor(cursor) {\n\tif (!cursor.startsWith(COMPOSITE_PREFIX)) throw new Error(\"Invalid composite cursor format\");\n\tconst json = cursor.slice(2);\n\ttry {\n\t\tconst parsed = JSON.parse(json);\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) throw new Error(\"Invalid composite cursor format\");\n\t\treturn parsed;\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) throw new Error(\"Invalid composite cursor format\", { cause: error });\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/client/types.ts\n/**\n* Describes the types of document changes that can occur.\n*/\nlet DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {\n\tDocumentChangeType[\"Created\"] = \"created\";\n\tDocumentChangeType[\"Deleted\"] = \"deleted\";\n\tDocumentChangeType[\"Updated\"] = \"updated\";\n\tDocumentChangeType[\"ParentAdded\"] = \"parent_added\";\n\tDocumentChangeType[\"ParentRemoved\"] = \"parent_removed\";\n\tDocumentChangeType[\"ChildAdded\"] = \"child_added\";\n\tDocumentChangeType[\"ChildRemoved\"] = \"child_removed\";\n\treturn DocumentChangeType;\n}({});\n//#endregion\n//#region src/client/reactor-client.ts\n/**\n* ReactorClient implementation that wraps lower-level APIs to provide\n* a simpler interface for document operations.\n*\n* Features:\n* - Wraps Jobs with Promises for easier async handling\n* - Manages signing of submitted Action objects\n* - Provides quality-of-life functions for common tasks\n* - Wraps subscription interface with ViewFilters\n*/\nvar ReactorClient = class {\n\tlogger;\n\treactor;\n\tsigner;\n\tsubscriptionManager;\n\tjobAwaiter;\n\tdocumentIndexer;\n\tdocumentView;\n\tdrives;\n\tconstructor(logger, reactor, signer, subscriptionManager, jobAwaiter, documentIndexer, documentView) {\n\t\tthis.logger = logger;\n\t\tthis.reactor = reactor;\n\t\tthis.signer = signer;\n\t\tthis.subscriptionManager = subscriptionManager;\n\t\tthis.jobAwaiter = jobAwaiter;\n\t\tthis.documentIndexer = documentIndexer;\n\t\tthis.documentView = documentView;\n\t\tthis.drives = new DriveClient(this, logger, reactor, signer);\n\t\tthis.logger.verbose(\"ReactorClient initialized\");\n\t}\n\t/**\n\t* Retrieves a list of document model modules.\n\t*/\n\tasync getDocumentModelModules(namespace, paging, signal) {\n\t\tthis.logger.verbose(\"getDocumentModels(@namespace, @paging)\", namespace, paging);\n\t\treturn this.reactor.getDocumentModels(namespace, paging, signal);\n\t}\n\t/**\n\t* Retrieves a specific document model module by document type.\n\t*\n\t* @param documentType - The document type identifier\n\t* @returns The document model module\n\t*/\n\tasync getDocumentModelModule(documentType) {\n\t\tconst module = (await this.reactor.getDocumentModels()).results.find((m) => m.documentModel.global.id === documentType);\n\t\tif (!module) throw new Error(`Document model module not found for type: ${documentType}`);\n\t\treturn module;\n\t}\n\t/**\n\t* Retrieves a specific PHDocument\n\t*/\n\tasync get(identifier, view, signal) {\n\t\tthis.logger.verbose(\"get(@identifier, @view)\", identifier, view);\n\t\treturn await this.reactor.getByIdOrSlug(identifier, view, void 0, signal);\n\t}\n\t/**\n\t* Resolves an identifier (id or slug) to the canonical document id, using the\n\t* same lookup as the data path. Resolves against the \"main\" branch. Throws if\n\t* the identifier cannot be resolved or is ambiguous.\n\t*/\n\tasync resolveIdOrSlug(identifier, signal) {\n\t\treturn this.documentView.resolveIdOrSlug(identifier, void 0, void 0, signal);\n\t}\n\t/**\n\t* Retrieves operations for a document\n\t*/\n\tasync getOperations(documentIdentifier, view, filter, paging, signal) {\n\t\tthis.logger.verbose(\"getOperations(@documentIdentifier, @view, @filter, @paging)\", documentIdentifier, view, filter, paging);\n\t\tconst documentId = await this.documentView.resolveIdOrSlug(documentIdentifier, view, void 0, signal);\n\t\tif (paging?.cursor && isCompositeCursor(paging.cursor)) return this.getOperationsWithCompositeCursor(documentId, view, filter, paging, signal);\n\t\tconst operationsByScope = await this.reactor.getOperations(documentId, view, filter, paging, void 0, signal);\n\t\tconst scopeEntries = Object.entries(operationsByScope);\n\t\tconst effectivePaging = paging || {\n\t\t\tcursor: \"0\",\n\t\t\tlimit: 100\n\t\t};\n\t\tif (scopeEntries.length <= 1) {\n\t\t\tconst allOperations = scopeEntries.length === 1 ? [...scopeEntries[0][1].results] : [];\n\t\t\tallOperations.sort((a, b) => a.index - b.index);\n\t\t\treturn {\n\t\t\t\tresults: allOperations,\n\t\t\t\toptions: effectivePaging,\n\t\t\t\tnextCursor: scopeEntries.length === 1 ? scopeEntries[0][1].nextCursor : void 0\n\t\t\t};\n\t\t}\n\t\tconst allOperations = [];\n\t\tconst activeCursors = {};\n\t\tfor (const [scopeName, scopeResults] of scopeEntries) {\n\t\t\tallOperations.push(...scopeResults.results);\n\t\t\tif (scopeResults.nextCursor) activeCursors[scopeName] = scopeResults.nextCursor;\n\t\t}\n\t\tallOperations.sort((a, b) => a.index - b.index);\n\t\treturn {\n\t\t\tresults: allOperations,\n\t\t\toptions: effectivePaging,\n\t\t\tnextCursor: Object.keys(activeCursors).length > 0 ? encodeCompositeCursor(activeCursors) : void 0\n\t\t};\n\t}\n\tasync getOperationsWithCompositeCursor(documentId, view, filter, paging, signal) {\n\t\tconst scopeCursors = decodeCompositeCursor(paging.cursor);\n\t\tconst allOperations = [];\n\t\tconst activeCursors = {};\n\t\tfor (const [scopeName, cursor] of Object.entries(scopeCursors)) {\n\t\t\tconst scopeView = {\n\t\t\t\t...view,\n\t\t\t\tscopes: [scopeName]\n\t\t\t};\n\t\t\tconst scopePaging = {\n\t\t\t\tcursor,\n\t\t\t\tlimit: paging.limit\n\t\t\t};\n\t\t\tconst scopeResult = (await this.reactor.getOperations(documentId, scopeView, filter, scopePaging, void 0, signal))[scopeName];\n\t\t\tallOperations.push(...scopeResult.results);\n\t\t\tif (scopeResult.nextCursor) activeCursors[scopeName] = scopeResult.nextCursor;\n\t\t}\n\t\tallOperations.sort((a, b) => a.index - b.index);\n\t\treturn {\n\t\t\tresults: allOperations,\n\t\t\toptions: paging,\n\t\t\tnextCursor: Object.keys(activeCursors).length > 0 ? encodeCompositeCursor(activeCursors) : void 0\n\t\t};\n\t}\n\t/**\n\t* Retrieves outgoing relationships of a given type from a source document.\n\t*/\n\tasync getOutgoingRelationships(sourceIdentifier, relationshipType, view, paging, signal) {\n\t\tthis.logger.verbose(\"getOutgoingRelationships(@sourceIdentifier, @relationshipType, @view, @paging)\", sourceIdentifier, relationshipType, view, paging);\n\t\tconst sourceId = await this.documentView.resolveIdOrSlug(sourceIdentifier, view, void 0, signal);\n\t\tconst targetIds = (await this.documentIndexer.getOutgoing(sourceId, [relationshipType], void 0, void 0, signal)).results.map((rel) => rel.targetId);\n\t\tif (targetIds.length === 0) return {\n\t\t\tresults: [],\n\t\t\toptions: paging || {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: 0\n\t\t\t}\n\t\t};\n\t\treturn this.reactor.find({ ids: targetIds }, view, paging, void 0, signal);\n\t}\n\t/**\n\t* Retrieves incoming relationships of a given type to a target document.\n\t*/\n\tasync getIncomingRelationships(targetIdentifier, relationshipType, view, paging, signal) {\n\t\tthis.logger.verbose(\"getIncomingRelationships(@targetIdentifier, @relationshipType, @view, @paging)\", targetIdentifier, relationshipType, view, paging);\n\t\tconst targetId = await this.documentView.resolveIdOrSlug(targetIdentifier, view, void 0, signal);\n\t\tconst sourceIds = (await this.documentIndexer.getIncoming(targetId, [relationshipType], void 0, void 0, signal)).results.map((rel) => rel.sourceId);\n\t\tif (sourceIds.length === 0) return {\n\t\t\tresults: [],\n\t\t\toptions: paging || {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: 0\n\t\t\t}\n\t\t};\n\t\treturn this.reactor.find({ ids: sourceIds }, view, paging, void 0, signal);\n\t}\n\t/**\n\t* Filters documents by criteria and returns a list of them\n\t*/\n\tasync find(search, view, paging, signal) {\n\t\tthis.logger.verbose(\"find(@search, @view, @paging)\", search, view, paging);\n\t\treturn this.reactor.find(search, view, paging, void 0, signal);\n\t}\n\t/**\n\t* Creates a document and waits for completion\n\t*/\n\tasync create(document, parentIdentifier, signal) {\n\t\tthis.logger.verbose(\"create(@id, @parentIdentifier)\", document.header.id, parentIdentifier);\n\t\tconst documentId = document.header.id;\n\t\tconst createActions = await signActions([createDocumentAction({\n\t\t\tmodel: document.header.documentType,\n\t\t\tversion: 0,\n\t\t\tdocumentId,\n\t\t\tsigning: {\n\t\t\t\tsignature: documentId,\n\t\t\t\tpublicKey: document.header.sig.publicKey,\n\t\t\t\tnonce: document.header.sig.nonce,\n\t\t\t\tcreatedAtUtcIso: document.header.createdAtUtcIso,\n\t\t\t\tdocumentType: document.header.documentType\n\t\t\t},\n\t\t\tslug: document.header.slug,\n\t\t\tname: document.header.name,\n\t\t\tbranch: document.header.branch,\n\t\t\tmeta: document.header.meta,\n\t\t\tprotocolVersions: document.header.protocolVersions ?? { \"base-reducer\": 2 }\n\t\t}), upgradeDocumentAction({\n\t\t\tdocumentId,\n\t\t\tmodel: document.header.documentType,\n\t\t\tfromVersion: 0,\n\t\t\ttoVersion: document.state.document.version,\n\t\t\tinitialState: document.state\n\t\t})], this.signer, signal);\n\t\tconst jobs = [{\n\t\t\tkey: \"create\",\n\t\t\tdocumentId,\n\t\t\tscope: getSharedActionScope(createActions),\n\t\t\tbranch: \"main\",\n\t\t\tactions: createActions,\n\t\t\tdependsOn: []\n\t\t}];\n\t\tif (parentIdentifier) {\n\t\t\tconst parentActions = await signActions([addRelationshipAction(parentIdentifier, documentId, \"child\")], this.signer, signal);\n\t\t\tjobs.push({\n\t\t\t\tkey: \"parent\",\n\t\t\t\tdocumentId: parentIdentifier,\n\t\t\t\tscope: getSharedActionScope(parentActions),\n\t\t\t\tbranch: \"main\",\n\t\t\t\tactions: parentActions,\n\t\t\t\tdependsOn: [\"create\"]\n\t\t\t});\n\t\t}\n\t\tconst batchResult = await this.reactor.executeBatch({ jobs }, signal);\n\t\tconst completedJobs = await Promise.all(Object.values(batchResult.jobs).map((job) => this.waitForJob(job, signal)));\n\t\tfor (const job of completedJobs) if (job.status === JobStatus.FAILED) throw new Error(job.error?.message);\n\t\treturn await this.reactor.get(documentId);\n\t}\n\t/**\n\t* Creates an empty document and waits for completion\n\t*/\n\tasync createEmpty(documentModelType, options, signal) {\n\t\tthis.logger.verbose(\"createEmpty(@documentModelType, @options)\", documentModelType, options);\n\t\tconst matchingModules = (await this.reactor.getDocumentModels(void 0, void 0, signal)).results.filter((m) => m.documentModel.global.id === documentModelType);\n\t\tlet module;\n\t\tif (options?.documentModelVersion !== void 0) {\n\t\t\tmodule = matchingModules.find((m) => m.version === options.documentModelVersion);\n\t\t\tif (!module) throw new Error(`Document model not found for type: ${documentModelType} with version: ${options.documentModelVersion}`);\n\t\t} else {\n\t\t\tmodule = matchingModules.reduce((latest, current) => {\n\t\t\t\tif (latest === void 0) return current;\n\t\t\t\treturn (current.version ?? 0) > (latest.version ?? 0) ? current : latest;\n\t\t\t}, void 0);\n\t\t\tif (!module) throw new Error(`Document model not found for type: ${documentModelType}`);\n\t\t}\n\t\tconst document = module.utils.createDocument();\n\t\tdocument.state.document.version = module.version ?? 1;\n\t\treturn this.create(document, options?.parentIdentifier, signal);\n\t}\n\t/**\n\t* Creates an empty document in a drive as a single batched operation.\n\t* Delegates to {@link IDriveClient.addFile}.\n\t*\n\t* @deprecated Use `client.drives.addFile` instead. This method will be\n\t* removed in a future release.\n\t*/\n\tasync createDocumentInDrive(driveId, document, parentFolder, signal) {\n\t\treturn this.drives.addFile(driveId, document, parentFolder, signal);\n\t}\n\t/**\n\t* Applies a list of actions to a document and waits for completion\n\t*/\n\tasync execute(documentIdentifier, branch, actions, signal) {\n\t\tthis.logger.verbose(\"execute(@documentIdentifier, @branch, @count actions)\", documentIdentifier, branch, actions.length);\n\t\tconst signedActions = await signActions(actions, this.signer, signal);\n\t\tconst jobInfo = await this.reactor.execute(documentIdentifier, branch, signedActions, signal);\n\t\tconst completedJob = await this.waitForJob(jobInfo, signal);\n\t\tif (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);\n\t\tconst view = { branch };\n\t\treturn await this.reactor.getByIdOrSlug(documentIdentifier, view, completedJob.consistencyToken, signal);\n\t}\n\t/**\n\t* Submits a list of actions to a document\n\t*/\n\tasync executeAsync(documentIdentifier, branch, actions, signal) {\n\t\tthis.logger.verbose(\"executeAsync(@documentIdentifier, @branch, @count actions)\", documentIdentifier, branch, actions.length);\n\t\tconst signedActions = await signActions(actions, this.signer, signal);\n\t\treturn this.reactor.execute(documentIdentifier, branch, signedActions, signal);\n\t}\n\tasync executeBatch(request, signal) {\n\t\tthis.logger.verbose(\"executeBatch(@count jobs)\", request.jobs.length);\n\t\tconst signedJobs = await Promise.all(request.jobs.map(async (job) => ({\n\t\t\t...job,\n\t\t\tactions: await signActions(job.actions, this.signer, signal)\n\t\t})));\n\t\tconst batchResult = await this.reactor.executeBatch({ jobs: signedJobs }, signal);\n\t\tconst completedJobs = await Promise.all(Object.values(batchResult.jobs).map((job) => this.waitForJob(job, signal)));\n\t\tfor (const job of completedJobs) if (job.status === JobStatus.FAILED) throw new Error(job.error?.message);\n\t\treturn batchResult;\n\t}\n\t/**\n\t* Renames a document and waits for completion\n\t*/\n\tasync rename(documentIdentifier, name, branch = \"main\", signal) {\n\t\tthis.logger.verbose(\"rename(@documentIdentifier, @name, @branch)\", documentIdentifier, name, branch);\n\t\treturn this.execute(documentIdentifier, branch, [actions.setName(name)], signal);\n\t}\n\t/**\n\t* Updates the preferred editor recorded in the document header meta.\n\t* Pass `null` to clear it.\n\t*/\n\tasync setPreferredEditor(documentIdentifier, preferredEditor, branch = \"main\", signal) {\n\t\tthis.logger.verbose(\"setPreferredEditor(@documentIdentifier, @preferredEditor, @branch)\", documentIdentifier, preferredEditor, branch);\n\t\treturn this.execute(documentIdentifier, branch, [actions.setPreferredEditor(preferredEditor)], signal);\n\t}\n\t/**\n\t* Adds multiple documents as children to another and waits for completion\n\t*/\n\tasync addRelationship(sourceIdentifier, targetIdentifier, relationshipType, branch = \"main\", signal) {\n\t\tthis.logger.verbose(\"addRelationship(@sourceIdentifier, @targetIdentifier, @relationshipType, @branch)\", sourceIdentifier, targetIdentifier, relationshipType, branch);\n\t\tconst jobInfo = await this.reactor.addRelationship(sourceIdentifier, targetIdentifier, relationshipType, branch, this.signer, signal);\n\t\tconst completedJob = await this.waitForJob(jobInfo, signal);\n\t\tif (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);\n\t\treturn await this.reactor.getByIdOrSlug(sourceIdentifier, { branch }, completedJob.consistencyToken, signal);\n\t}\n\t/**\n\t* Removes a relationship between two documents and waits for completion.\n\t*/\n\tasync removeRelationship(sourceIdentifier, targetIdentifier, relationshipType, branch = \"main\", signal) {\n\t\tthis.logger.verbose(\"removeRelationship(@sourceIdentifier, @targetIdentifier, @relationshipType, @branch)\", sourceIdentifier, targetIdentifier, relationshipType, branch);\n\t\tconst jobInfo = await this.reactor.removeRelationship(sourceIdentifier, targetIdentifier, relationshipType, branch, this.signer, signal);\n\t\tconst completedJob = await this.waitForJob(jobInfo, signal);\n\t\tif (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);\n\t\treturn await this.reactor.getByIdOrSlug(sourceIdentifier, { branch }, completedJob.consistencyToken, signal);\n\t}\n\t/**\n\t* Moves a relationship from one source document to another and waits for completion.\n\t*/\n\tasync moveRelationship(sourceParentIdentifier, targetParentIdentifier, targetIdentifier, relationshipType, branch = \"main\", signal) {\n\t\tthis.logger.verbose(\"moveRelationship(@sourceParentIdentifier, @targetParentIdentifier, @targetIdentifier, @relationshipType, @branch)\", sourceParentIdentifier, targetParentIdentifier, targetIdentifier, relationshipType, branch);\n\t\tconst removeJobInfo = await this.reactor.removeRelationship(sourceParentIdentifier, targetIdentifier, relationshipType, branch, this.signer, signal);\n\t\tconst removeCompletedJob = await this.waitForJob(removeJobInfo, signal);\n\t\tif (removeCompletedJob.status === JobStatus.FAILED) throw new Error(removeCompletedJob.error?.message);\n\t\tconst addJobInfo = await this.reactor.addRelationship(targetParentIdentifier, targetIdentifier, relationshipType, branch, this.signer, signal);\n\t\tconst addCompletedJob = await this.waitForJob(addJobInfo, signal);\n\t\tif (addCompletedJob.status === JobStatus.FAILED) throw new Error(addCompletedJob.error?.message);\n\t\treturn {\n\t\t\tsource: await this.reactor.getByIdOrSlug(sourceParentIdentifier, { branch }, removeCompletedJob.consistencyToken, signal),\n\t\t\ttarget: await this.reactor.getByIdOrSlug(targetParentIdentifier, { branch }, addCompletedJob.consistencyToken, signal)\n\t\t};\n\t}\n\tasync loadBatch(request, signal) {\n\t\tthis.logger.verbose(\"loadBatch(@count jobs)\", request.jobs.length);\n\t\tconst result = await this.reactor.loadBatch(request, signal);\n\t\tconst completedJobs = await Promise.all(Object.entries(result.jobs).map(async ([key, jobInfo]) => {\n\t\t\treturn [key, await this.waitForJob(jobInfo, signal)];\n\t\t}));\n\t\tfor (const [, completedJob] of completedJobs) if (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);\n\t\treturn { jobs: Object.fromEntries(completedJobs) };\n\t}\n\t/**\n\t* Deletes a document and waits for completion\n\t*/\n\tasync deleteDocument(identifier, propagate, signal) {\n\t\tthis.logger.verbose(\"deleteDocument(@identifier, @propagate)\", identifier, propagate);\n\t\tconst jobs = [];\n\t\tif (propagate === PropagationMode.Cascade) {\n\t\t\tconst toDelete = new Set([identifier]);\n\t\t\tlet changed = true;\n\t\t\twhile (changed) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tchanged = false;\n\t\t\t\tconst orphans = await this.documentIndexer.getOrphanedChildren([...toDelete], [\"child\"], signal);\n\t\t\t\tfor (const id of orphans) if (!toDelete.has(id)) {\n\t\t\t\t\ttoDelete.add(id);\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const descendantId of toDelete) {\n\t\t\t\tif (descendantId === identifier) continue;\n\t\t\t\tconst removalJobs = await this.removeAllIncomingRelationships(descendantId, signal);\n\t\t\t\tjobs.push(...removalJobs);\n\t\t\t\tconst jobInfo = await this.reactor.deleteDocument(descendantId, this.signer, signal);\n\t\t\t\tjobs.push(jobInfo);\n\t\t\t}\n\t\t}\n\t\tconst removalJobs = await this.removeAllIncomingRelationships(identifier, signal);\n\t\tjobs.push(...removalJobs);\n\t\tconst jobInfo = await this.reactor.deleteDocument(identifier, this.signer, signal);\n\t\tjobs.push(jobInfo);\n\t\tconst completedJobs = await Promise.all(jobs.map((job) => this.waitForJob(job, signal)));\n\t\tfor (const completedJob of completedJobs) if (completedJob.status === JobStatus.FAILED) throw new Error(completedJob.error?.message);\n\t}\n\t/**\n\t* Deletes documents and waits for completion\n\t*/\n\tasync deleteDocuments(identifiers, propagate, signal) {\n\t\tthis.logger.verbose(\"deleteDocuments(@count identifiers, @propagate)\", identifiers.length, propagate);\n\t\tconst deletePromises = identifiers.map((identifier) => this.deleteDocument(identifier, propagate, signal));\n\t\tawait Promise.all(deletePromises);\n\t}\n\t/**\n\t* Retrieves the status of a job\n\t*/\n\tasync getJobStatus(jobId, signal) {\n\t\tthis.logger.verbose(\"getJobStatus(@jobId)\", jobId);\n\t\treturn this.reactor.getJobStatus(jobId, signal);\n\t}\n\t/**\n\t* Waits for a job to complete\n\t*/\n\tasync waitForJob(jobId, signal) {\n\t\tconst id = typeof jobId === \"string\" ? jobId : jobId.id;\n\t\tthis.logger.verbose(\"waitForJob(@id)\", id);\n\t\treturn this.jobAwaiter.waitForJob(id, signal);\n\t}\n\t/**\n\t* Subscribes to changes for documents matching specified filters\n\t*/\n\tsubscribe(search, callback, view) {\n\t\tthis.logger.verbose(\"subscribe(@search, @view)\", search, view);\n\t\tconst unsubscribeCreated = this.subscriptionManager.onDocumentCreated((result) => {\n\t\t\t(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst documents = await Promise.all(result.results.map((id) => this.reactor.get(id, view, void 0, void 0)));\n\t\t\t\t\tcallback({\n\t\t\t\t\t\ttype: DocumentChangeType.Created,\n\t\t\t\t\t\tdocuments\n\t\t\t\t\t});\n\t\t\t\t} catch {}\n\t\t\t})();\n\t\t}, search);\n\t\tconst unsubscribeDeleted = this.subscriptionManager.onDocumentDeleted((documentIds) => {\n\t\t\tcallback({\n\t\t\t\ttype: DocumentChangeType.Deleted,\n\t\t\t\tdocuments: [],\n\t\t\t\tcontext: { childId: documentIds[0] }\n\t\t\t});\n\t\t}, search);\n\t\tconst unsubscribeUpdated = this.subscriptionManager.onDocumentStateUpdated((result) => {\n\t\t\tcallback({\n\t\t\t\ttype: DocumentChangeType.Updated,\n\t\t\t\tdocuments: result.results\n\t\t\t});\n\t\t}, search, view);\n\t\tconst unsubscribeRelationship = this.subscriptionManager.onRelationshipChanged((parentId, childId, changeType) => {\n\t\t\tcallback({\n\t\t\t\ttype: changeType === RelationshipChangeType.Added ? DocumentChangeType.ChildAdded : DocumentChangeType.ChildRemoved,\n\t\t\t\tdocuments: [],\n\t\t\t\tcontext: {\n\t\t\t\t\tparentId,\n\t\t\t\t\tchildId\n\t\t\t\t}\n\t\t\t});\n\t\t}, search);\n\t\treturn () => {\n\t\t\tunsubscribeCreated();\n\t\t\tunsubscribeDeleted();\n\t\t\tunsubscribeUpdated();\n\t\t\tunsubscribeRelationship();\n\t\t};\n\t}\n\tasync removeAllIncomingRelationships(documentId, signal) {\n\t\tconst incoming = await this.documentIndexer.getIncoming(documentId, void 0, void 0, void 0, signal);\n\t\tconst jobs = [];\n\t\tfor (const rel of incoming.results) {\n\t\t\tconst jobInfo = await this.reactor.removeRelationship(rel.sourceId, documentId, rel.relationshipType, \"main\", this.signer, signal);\n\t\t\tjobs.push(jobInfo);\n\t\t}\n\t\treturn jobs;\n\t}\n};\n//#endregion\n//#region src/queue/types.ts\n/**\n* State of a job in the queue\n*/\nlet JobQueueState = /* @__PURE__ */ function(JobQueueState) {\n\tJobQueueState[JobQueueState[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n\tJobQueueState[JobQueueState[\"PREPROCESSING\"] = 0] = \"PREPROCESSING\";\n\tJobQueueState[JobQueueState[\"PENDING\"] = 1] = \"PENDING\";\n\tJobQueueState[JobQueueState[\"READY\"] = 2] = \"READY\";\n\tJobQueueState[JobQueueState[\"RUNNING\"] = 3] = \"RUNNING\";\n\tJobQueueState[JobQueueState[\"RESOLVED\"] = 4] = \"RESOLVED\";\n\treturn JobQueueState;\n}({});\n/**\n* Event types for the queue system\n*/\nconst QueueEventTypes = { JOB_AVAILABLE: 1e4 };\n//#endregion\n//#region src/executor/job-result-handler.ts\nfunction toErrorInfo(error) {\n\tif (error instanceof Error) return {\n\t\tmessage: error.message,\n\t\tstack: error.stack || (/* @__PURE__ */ new Error()).stack || \"\"\n\t};\n\treturn {\n\t\tmessage: error,\n\t\tstack: (/* @__PURE__ */ new Error()).stack || \"\"\n\t};\n}\nvar JobResultHandler = class {\n\tconstructor(queue, jobTracker, eventBus, resolver, logger) {\n\t\tthis.queue = queue;\n\t\tthis.jobTracker = jobTracker;\n\t\tthis.eventBus = eventBus;\n\t\tthis.resolver = resolver;\n\t\tthis.logger = logger;\n\t}\n\tasync handleResult(handle, result, callbacks) {\n\t\tif (result.success) {\n\t\t\thandle.complete();\n\t\t\tif (this.hasCreateDocumentAction(handle.job)) await callbacks.flushDeferredFor(handle.job.documentId);\n\t\t\treturn;\n\t\t}\n\t\tif (result.error && ModuleNotFoundError.isError(result.error)) {\n\t\t\tlet modelLoaded = false;\n\t\t\ttry {\n\t\t\t\tawait this.resolver.ensureModelLoaded(result.error.documentType);\n\t\t\t\tmodelLoaded = true;\n\t\t\t} catch {}\n\t\t\tif (modelLoaded) {\n\t\t\t\tconst errorInfo = toErrorInfo(result.error);\n\t\t\t\ttry {\n\t\t\t\t\tawait this.queue.retryJob(handle.job.id, errorInfo);\n\t\t\t\t\treturn;\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t}\n\t\tif (result.error && DocumentNotFoundError.isError(result.error)) {\n\t\t\thandle.defer();\n\t\t\tcallbacks.deferJob(handle.job.documentId, handle.job);\n\t\t\treturn;\n\t\t}\n\t\tif (result.error && DocumentDeletedError.isError(result.error)) {\n\t\t\tconst errorInfo = toErrorInfo(result.error);\n\t\t\tthis.jobTracker.markFailed(handle.job.id, errorInfo, handle.job);\n\t\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\t\tjobId: handle.job.id,\n\t\t\t\terror: result.error,\n\t\t\t\tjob: handle.job\n\t\t\t}).catch(() => {});\n\t\t\thandle.fail(errorInfo);\n\t\t\treturn;\n\t\t}\n\t\tconst retryCount = handle.job.retryCount || 0;\n\t\tif (retryCount < (handle.job.maxRetries || 0)) {\n\t\t\tconst currentErrorInfo = result.error ? toErrorInfo(result.error) : toErrorInfo(\"Unknown error\");\n\t\t\ttry {\n\t\t\t\tawait this.queue.retryJob(handle.job.id, currentErrorInfo);\n\t\t\t} catch (error) {\n\t\t\t\tconst retryErrorInfo = toErrorInfo(error instanceof Error ? error : \"Failed to retry job\");\n\t\t\t\tthis.jobTracker.markFailed(handle.job.id, retryErrorInfo, handle.job);\n\t\t\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\t\t\tjobId: handle.job.id,\n\t\t\t\t\terror: result.error ?? new Error(retryErrorInfo.message),\n\t\t\t\t\tjob: handle.job\n\t\t\t\t}).catch(() => {});\n\t\t\t\thandle.fail(retryErrorInfo);\n\t\t\t}\n\t\t} else {\n\t\t\tconst currentErrorInfo = result.error ? toErrorInfo(result.error) : toErrorInfo(\"Unknown error\");\n\t\t\tconst fullErrorInfo = this.formatErrorHistory(handle.job.errorHistory, currentErrorInfo, retryCount + 1);\n\t\t\tthis.jobTracker.markFailed(handle.job.id, fullErrorInfo, handle.job);\n\t\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\t\tjobId: handle.job.id,\n\t\t\t\terror: result.error ?? new Error(fullErrorInfo.message),\n\t\t\t\tjob: handle.job\n\t\t\t}).catch(() => {});\n\t\t\thandle.fail(fullErrorInfo);\n\t\t}\n\t}\n\thasCreateDocumentAction(job) {\n\t\tfor (const action of job.actions) if (action.type === \"CREATE_DOCUMENT\") return true;\n\t\tfor (const operation of job.operations) if (operation.action.type === \"CREATE_DOCUMENT\") return true;\n\t\treturn false;\n\t}\n\tformatErrorHistory(errorHistory, currentError, totalAttempts) {\n\t\tconst allErrors = [...errorHistory, currentError];\n\t\tif (allErrors.length === 1) return currentError;\n\t\tconst messageLines = [`Job failed after ${totalAttempts} attempts:`];\n\t\tconst stackLines = [];\n\t\tallErrors.forEach((error, index) => {\n\t\t\tmessageLines.push(`[Attempt ${index + 1}] ${error.message}`);\n\t\t\tstackLines.push(`[Attempt ${index + 1}] Stack trace:\\n${error.stack}`);\n\t\t});\n\t\treturn {\n\t\t\tmessage: messageLines.join(\"\\n\"),\n\t\t\tstack: stackLines.join(\"\\n\\n\")\n\t\t};\n\t}\n};\n//#endregion\n//#region src/executor/types.ts\n/**\n* Event types for the job executor\n*/\nconst JobExecutorEventTypes = {\n\tJOB_STARTED: 2e4,\n\tJOB_COMPLETED: 20001,\n\tJOB_FAILED: 20002,\n\tEXECUTOR_STARTED: 20003,\n\tEXECUTOR_STOPPED: 20004\n};\n//#endregion\n//#region src/executor/worker-pool-router.ts\n/**\n* Sticky-by-document routing for the executor worker pool.\n*\n* Hashes `documentId` to a stable bucket so every job on a given document\n* lands on the same worker. The queue already enforces \"at most one job\n* executing per document at a time\", so a sticky worker always sees a fresh\n* post-commit snapshot before its next job on that document — which keeps\n* the per-worker `IWriteCache` and `IDocumentMetaCache` coherent for free.\n*\n* The hash is FNV-1a 32-bit: deterministic, dependency-free, and stable\n* across processes (so the same routing decision can be reproduced anywhere\n* the documentId is known).\n*\n* @see Executor Worker Pool Design wiki page\n* (Powerhouse board wiki id: d400d711-f07e-4389-a226-4e9fdd4fa8ba)\n*/\nconst FNV_OFFSET_BASIS = 2166136261;\nconst FNV_PRIME = 16777619;\nfunction hashDocumentId(documentId) {\n\tlet hash = FNV_OFFSET_BASIS;\n\tfor (let i = 0; i < documentId.length; i++) {\n\t\thash ^= documentId.charCodeAt(i);\n\t\thash = Math.imul(hash, FNV_PRIME);\n\t}\n\treturn hash >>> 0;\n}\nfunction bucketFor(documentId, numWorkers) {\n\tif (numWorkers < 1) throw new Error(`bucketFor: numWorkers must be >= 1 (got ${numWorkers})`);\n\treturn hashDocumentId(documentId) % numWorkers;\n}\n//#endregion\n//#region src/executor/worker-pool-job-executor-manager.ts\n/**\n* Action types whose application invalidates the parent's collection\n* membership cache. Mirrors the in-process invalidation pattern in\n* `document-action-handler.ts` (the worker pool relocates that work to\n* the parent because the cache lives there).\n*/\nconst MEMBERSHIP_INVALIDATING_ACTIONS = new Set([\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\",\n\t\"DELETE_DOCUMENT\"\n]);\n/**\n* Manages a pool of executor workers and dispatches jobs across them with\n* sticky-by-documentId routing. Replaces `SimpleJobExecutorManager` when\n* the worker pool is enabled.\n*\n* Responsibilities that stay on the parent (not in the worker):\n* - Dequeueing from `IQueue` and routing to the matching worker bucket.\n* - Emitting `JOB_RUNNING` and `JOB_WRITE_READY` events; the worker's\n* local event bus is a no-op stub.\n* - Maintaining the deferred-jobs map for `DocumentNotFoundError`.\n* - Owning the authoritative `ICollectionMembershipCache` — workers do\n* not query it. Each result enriches the outgoing `JOB_WRITE_READY`\n* with `collectionMemberships` and invalidates targets named by\n* relationship/delete operations before the lookup.\n*\n* @see Executor Worker Pool Design wiki page\n* (Powerhouse board wiki id: d400d711-f07e-4389-a226-4e9fdd4fa8ba)\n*/\nvar WorkerPoolJobExecutorManager = class {\n\tworkers = [];\n\tisRunning = false;\n\tactiveJobs = 0;\n\ttotalJobsProcessed = 0;\n\tunsubscribe;\n\tdeferredJobs = /* @__PURE__ */ new Map();\n\tresultHandler;\n\tjobTimeoutMs;\n\tconstructor(workerFactory, eventBus, queue, jobTracker, logger, resolver, collectionMembershipCache, jobTimeoutMs = 3e4) {\n\t\tthis.workerFactory = workerFactory;\n\t\tthis.eventBus = eventBus;\n\t\tthis.queue = queue;\n\t\tthis.jobTracker = jobTracker;\n\t\tthis.logger = logger;\n\t\tthis.resolver = resolver;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.jobTimeoutMs = jobTimeoutMs;\n\t\tthis.resultHandler = new JobResultHandler(queue, jobTracker, eventBus, resolver, logger);\n\t}\n\tasync start(numWorkers) {\n\t\tif (this.isRunning) throw new Error(\"WorkerPoolJobExecutorManager is already running\");\n\t\tif (numWorkers < 1) throw new Error(\"Number of workers must be at least 1\");\n\t\tthis.workers = Array.from({ length: numWorkers }, (_, i) => this.workerFactory(i));\n\t\tawait Promise.all(this.workers.map((w) => w.start()));\n\t\tthis.unsubscribe = this.eventBus.subscribe(QueueEventTypes.JOB_AVAILABLE, async () => {\n\t\t\tawait this.tryDispatchAll();\n\t\t});\n\t\tthis.isRunning = true;\n\t\tawait this.tryDispatchAll();\n\t}\n\tasync stop(graceful = true) {\n\t\tif (!this.isRunning) return;\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t\tthis.unsubscribe = void 0;\n\t\t}\n\t\tif (graceful) while (this.activeJobs > 0) await new Promise((resolve) => setTimeout(resolve, 10));\n\t\tfor (const [, jobs] of this.deferredJobs) for (const job of jobs) {\n\t\t\tconst errorInfo = toErrorInfo(new DocumentNotFoundError(job.documentId));\n\t\t\tthis.jobTracker.markFailed(job.id, errorInfo, job);\n\t\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\t\tjobId: job.id,\n\t\t\t\terror: new DocumentNotFoundError(job.documentId),\n\t\t\t\tjob\n\t\t\t}).catch(() => {});\n\t\t}\n\t\tthis.deferredJobs.clear();\n\t\tawait Promise.all(this.workers.map((w) => w.shutdown(graceful).catch((err) => {\n\t\t\tthis.logger.warn(\"worker shutdown failed: @Error\", err);\n\t\t})));\n\t\tthis.workers = [];\n\t\tthis.isRunning = false;\n\t}\n\t/**\n\t* Worker-pool mode has no in-process `IJobExecutor` instances — the\n\t* executors live in worker threads behind `IExecutorWorker` handles.\n\t* Returns an empty array; callers that need pool-aware introspection\n\t* should use `getStatus()` instead.\n\t*/\n\tgetExecutors() {\n\t\treturn [];\n\t}\n\t/**\n\t* Broadcasts a `load-model` request to every running worker in parallel.\n\t* Rejects with the first worker's failure if any worker rejects (after\n\t* waiting for all in-flight broadcasts to settle). Workers that already\n\t* have the model registered respond with a `DuplicateModuleError`-rooted\n\t* failure; those are treated as success on the broadcast level so that\n\t* a model registered on some workers but not others still converges.\n\t*/\n\tasync loadModel(entry) {\n\t\tif (this.workers.length === 0) return;\n\t\tconst failures = (await Promise.allSettled(this.workers.map((w) => w.loadModel(entry)))).filter((r) => r.status === \"rejected\").filter((r) => !isDuplicateModuleFailure(r.reason));\n\t\tif (failures.length === 0) return;\n\t\tfor (const f of failures) this.logger.error(\"worker failed to load model @entry: @error\", entry, f.reason);\n\t\tthrow failures[0].reason instanceof Error ? failures[0].reason : new Error(String(failures[0].reason));\n\t}\n\tgetStatus() {\n\t\treturn {\n\t\t\tisRunning: this.isRunning,\n\t\t\tnumExecutors: this.workers.length,\n\t\t\tactiveJobs: this.activeJobs,\n\t\t\ttotalJobsProcessed: this.totalJobsProcessed\n\t\t};\n\t}\n\tasync tryDispatchAll() {\n\t\tif (!this.isRunning && this.workers.length === 0) return;\n\t\tawait Promise.all(this.workers.map((worker) => this.tryDispatchFor(worker)));\n\t}\n\tasync tryDispatchFor(worker) {\n\t\tif (!worker.isIdle()) return;\n\t\tconst index = worker.index;\n\t\tconst numWorkers = this.workers.length;\n\t\tconst predicate = (meta) => bucketFor(meta.documentId, numWorkers) === index;\n\t\tlet handle;\n\t\ttry {\n\t\t\thandle = await this.queue.dequeueNextMatching(predicate);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error dequeueing next job: @Error\", error);\n\t\t\treturn;\n\t\t}\n\t\tif (!handle) return;\n\t\thandle.start();\n\t\tthis.activeJobs++;\n\t\tthis.jobTracker.markRunning(handle.job.id);\n\t\tconst runningEvent = {\n\t\t\tjobId: handle.job.id,\n\t\t\tjobMeta: handle.job.meta\n\t\t};\n\t\tthis.eventBus.emit(ReactorEventTypes.JOB_RUNNING, runningEvent).catch(() => {});\n\t\tconst workerId = worker.workerId;\n\t\tconst startedEvent = {\n\t\t\tjob: handle.job,\n\t\t\tstartedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tworkerId\n\t\t};\n\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_STARTED, startedEvent).catch(() => {});\n\t\tconst signal = AbortSignal.timeout(this.jobTimeoutMs);\n\t\tlet outcome;\n\t\ttry {\n\t\t\toutcome = await worker.execute(handle.job, signal);\n\t\t} catch (error) {\n\t\t\tconst errorInfo = toErrorInfo(error instanceof Error ? error : String(error));\n\t\t\tif (isWorkerTransportError(error)) {\n\t\t\t\tawait this.handleWorkerTransportFailure(worker, handle.job, errorInfo);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thandle.fail(errorInfo);\n\t\t\tthis.activeJobs--;\n\t\t\tthis.jobTracker.markFailed(handle.job.id, errorInfo, handle.job);\n\t\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\t\tjobId: handle.job.id,\n\t\t\t\terror: new Error(errorInfo.message),\n\t\t\t\tjob: handle.job\n\t\t\t}).catch(() => {});\n\t\t\tconst failedEvent = {\n\t\t\t\tjob: handle.job,\n\t\t\t\terror: errorInfo.message,\n\t\t\t\twillRetry: false,\n\t\t\t\tretryCount: 0,\n\t\t\t\tworkerId\n\t\t\t};\n\t\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_FAILED, failedEvent).catch(() => {});\n\t\t\tawait this.tryDispatchFor(worker);\n\t\t\treturn;\n\t\t}\n\t\tif (outcome.result.success) {\n\t\t\tthis.totalJobsProcessed++;\n\t\t\tconst completedEvent = {\n\t\t\t\tjob: handle.job,\n\t\t\t\tresult: outcome.result,\n\t\t\t\tworkerId\n\t\t\t};\n\t\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_COMPLETED, completedEvent).catch(() => {});\n\t\t} else {\n\t\t\tconst failedEvent = {\n\t\t\t\tjob: handle.job,\n\t\t\t\terror: outcome.result.error?.message ?? \"unknown\",\n\t\t\t\twillRetry: false,\n\t\t\t\tretryCount: 0,\n\t\t\t\tworkerId\n\t\t\t};\n\t\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_FAILED, failedEvent).catch(() => {});\n\t\t}\n\t\tif (outcome.result.success && outcome.writeReady) this.emitWriteReady(handle.job, outcome.writeReady).catch((error) => {\n\t\t\tthis.logger.error(\"emitWriteReady failed for job @jobId: @Error\", { jobId: handle.job.id }, error);\n\t\t});\n\t\tawait this.resultHandler.handleResult(handle, outcome.result, {\n\t\t\tdeferJob: (documentId, job) => {\n\t\t\t\tconst existing = this.deferredJobs.get(documentId) ?? [];\n\t\t\t\texisting.push(job);\n\t\t\t\tthis.deferredJobs.set(documentId, existing);\n\t\t\t},\n\t\t\tflushDeferredFor: (documentId) => this.flushDeferredJobs(documentId)\n\t\t});\n\t\tthis.activeJobs--;\n\t\tawait this.tryDispatchFor(worker);\n\t}\n\tasync emitWriteReady(job, payload) {\n\t\tthis.invalidateMembershipsFor(payload.operations);\n\t\tconst documentIds = [...new Set(payload.operations.map((op) => op.context.documentId))];\n\t\tlet collectionMemberships = {};\n\t\ttry {\n\t\t\tcollectionMemberships = await this.collectionMembershipCache.getCollectionsForDocuments(documentIds);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to load collection memberships for JOB_WRITE_READY: @Error\", error);\n\t\t}\n\t\tconst event = {\n\t\t\tjobId: job.id,\n\t\t\toperations: payload.operations,\n\t\t\tjobMeta: payload.jobMeta,\n\t\t\tcollectionMemberships\n\t\t};\n\t\ttry {\n\t\t\tawait this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY, event);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to emit JOB_WRITE_READY event: @Error\", error);\n\t\t}\n\t}\n\tinvalidateMembershipsFor(operations) {\n\t\tfor (const op of operations) {\n\t\t\tconst actionType = op.operation.action.type;\n\t\t\tif (!MEMBERSHIP_INVALIDATING_ACTIONS.has(actionType)) continue;\n\t\t\tconst target = extractMembershipTarget(op);\n\t\t\tif (target) this.collectionMembershipCache.invalidate(target);\n\t\t}\n\t}\n\t/**\n\t* Handle a worker-transport failure (worker exited / init failed / abort\n\t* timed out) detected while `worker.execute` was in flight. Re-enqueues\n\t* the in-flight job via `queue.retryJob` so it is retried on a healthy\n\t* worker, then replaces the dead worker with a fresh handle and resumes\n\t* dispatch on the same bucket. Does NOT emit JOB_FAILED — the job is\n\t* not failed, only the worker is.\n\t*/\n\tasync handleWorkerTransportFailure(dead, job, errorInfo) {\n\t\tthis.logger.warn(\"worker transport error during execute; retrying job @jobId on a replacement worker: @error\", {\n\t\t\tjobId: job.id,\n\t\t\tworkerId: dead.workerId\n\t\t}, errorInfo.message);\n\t\tthis.activeJobs--;\n\t\tawait this.replaceWorker(dead);\n\t\ttry {\n\t\t\tawait this.queue.retryJob(job.id, errorInfo);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"failed to re-enqueue job after worker transport error: @Error\", error);\n\t\t}\n\t}\n\t/**\n\t* Replace a dead worker at its existing pool index with a fresh handle\n\t* produced by `workerFactory`. Awaits `start()` on the replacement so it\n\t* is ready before dispatch resumes. On replacement failure the slot is\n\t* left empty (the index becomes a hole that subsequent retries will\n\t* route to no worker) and the error is logged — the manager keeps\n\t* running so other buckets continue to make progress.\n\t*/\n\tasync replaceWorker(dead) {\n\t\tconst deadIndex = dead.index;\n\t\tif (this.workers[deadIndex] !== dead) return;\n\t\tlet fresh;\n\t\ttry {\n\t\t\tfresh = this.workerFactory(deadIndex);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"workerFactory threw while replacing dead worker at index @index: @Error\", deadIndex, error);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait fresh.start();\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"replacement worker at index @index failed to start: @Error\", deadIndex, error);\n\t\t\treturn;\n\t\t}\n\t\tthis.workers[deadIndex] = fresh;\n\t\tawait this.tryDispatchFor(fresh);\n\t}\n\tasync flushDeferredJobs(documentId) {\n\t\tconst jobs = this.deferredJobs.get(documentId);\n\t\tif (!jobs || jobs.length === 0) return;\n\t\tthis.deferredJobs.delete(documentId);\n\t\tfor (const job of jobs) try {\n\t\t\tawait this.queue.enqueue(job);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error re-enqueuing deferred job: @Error\", error);\n\t\t}\n\t}\n};\nfunction isWorkerTransportError(error) {\n\treturn error instanceof WorkerExitedError || error instanceof WorkerInitFailedError || error instanceof WorkerAbortTimeoutError;\n}\nfunction isDuplicateModuleFailure(reason) {\n\tif (!(reason instanceof Error)) return false;\n\tif (reason.name === \"DuplicateModuleError\") return true;\n\tconst cause = reason.cause;\n\treturn cause instanceof Error && cause.name === \"DuplicateModuleError\";\n}\nfunction extractMembershipTarget(op) {\n\tconst actionType = op.operation.action.type;\n\tconst input = op.operation.action.input;\n\tif (actionType === \"ADD_RELATIONSHIP\" || actionType === \"REMOVE_RELATIONSHIP\" || actionType === \"UPDATE_RELATIONSHIP\") return input?.targetId;\n\tif (actionType === \"DELETE_DOCUMENT\") return input?.documentId ?? op.context.documentId;\n}\n//#endregion\n//#region src/executor/simple-job-executor-manager.ts\n/**\n* Manages multiple job executors and coordinates job distribution.\n* Listens for job available events and dispatches jobs to executors.\n*/\nvar SimpleJobExecutorManager = class {\n\texecutors = [];\n\tisRunning = false;\n\tactiveJobs = 0;\n\ttotalJobsProcessed = 0;\n\tunsubscribe;\n\tdeferredJobs = /* @__PURE__ */ new Map();\n\tresultHandler;\n\tjobTimeoutMs;\n\tconstructor(executorFactory, eventBus, queue, jobTracker, logger, resolver, jobTimeoutMs = 3e4) {\n\t\tthis.executorFactory = executorFactory;\n\t\tthis.eventBus = eventBus;\n\t\tthis.queue = queue;\n\t\tthis.jobTracker = jobTracker;\n\t\tthis.logger = logger;\n\t\tthis.resolver = resolver;\n\t\tthis.jobTimeoutMs = jobTimeoutMs;\n\t\tthis.resultHandler = new JobResultHandler(queue, jobTracker, eventBus, resolver, logger);\n\t}\n\tasync start(numExecutors) {\n\t\tif (this.isRunning) throw new Error(\"JobExecutorManager is already running\");\n\t\tif (numExecutors < 1) throw new Error(\"Number of executors must be at least 1\");\n\t\tthis.executors = [];\n\t\tfor (let i = 0; i < numExecutors; i++) this.executors.push(this.executorFactory());\n\t\tthis.unsubscribe = this.eventBus.subscribe(QueueEventTypes.JOB_AVAILABLE, async () => {\n\t\t\tif (this.activeJobs < this.executors.length) await this.processNextJob();\n\t\t});\n\t\tthis.isRunning = true;\n\t\tawait this.processExistingJobs();\n\t}\n\tasync stop(graceful = true) {\n\t\tif (!this.isRunning) return;\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t\tthis.unsubscribe = void 0;\n\t\t}\n\t\tif (graceful) while (this.activeJobs > 0) await new Promise((resolve) => setTimeout(resolve, 100));\n\t\tfor (const [, jobs] of this.deferredJobs) for (const job of jobs) {\n\t\t\tconst errorInfo = toErrorInfo(new DocumentNotFoundError(job.documentId));\n\t\t\tthis.jobTracker.markFailed(job.id, errorInfo, job);\n\t\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\t\tjobId: job.id,\n\t\t\t\terror: new DocumentNotFoundError(job.documentId),\n\t\t\t\tjob\n\t\t\t}).catch(() => {});\n\t\t}\n\t\tthis.deferredJobs.clear();\n\t\tthis.executors = [];\n\t\tthis.isRunning = false;\n\t}\n\tgetExecutors() {\n\t\treturn [...this.executors];\n\t}\n\tgetStatus() {\n\t\treturn {\n\t\t\tisRunning: this.isRunning,\n\t\t\tnumExecutors: this.executors.length,\n\t\t\tactiveJobs: this.activeJobs,\n\t\t\ttotalJobsProcessed: this.totalJobsProcessed\n\t\t};\n\t}\n\tasync processNextJob() {\n\t\tlet handle;\n\t\ttry {\n\t\t\thandle = await this.queue.dequeueNext();\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error dequeueing next job: @Error\", error);\n\t\t\treturn;\n\t\t}\n\t\tif (!handle) return;\n\t\thandle.start();\n\t\tthis.activeJobs++;\n\t\tthis.jobTracker.markRunning(handle.job.id);\n\t\tconst runningEvent = {\n\t\t\tjobId: handle.job.id,\n\t\t\tjobMeta: handle.job.meta\n\t\t};\n\t\tthis.eventBus.emit(ReactorEventTypes.JOB_RUNNING, runningEvent).catch(() => {});\n\t\tconst executorIndex = this.totalJobsProcessed % this.executors.length;\n\t\tconst executor = this.executors[executorIndex];\n\t\tconst workerId = `in-process-${executorIndex}`;\n\t\tconst startedEvent = {\n\t\t\tjob: handle.job,\n\t\t\tstartedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tworkerId\n\t\t};\n\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_STARTED, startedEvent).catch(() => {});\n\t\tconst signal = AbortSignal.timeout(this.jobTimeoutMs);\n\t\tconst toError = (reason) => reason instanceof Error ? reason : new Error(String(reason));\n\t\tconst abortPromise = new Promise((_, reject) => {\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(toError(signal.reason));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal.addEventListener(\"abort\", () => reject(toError(signal.reason)), { once: true });\n\t\t});\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await Promise.race([executor.executeJob(handle.job, signal), abortPromise]);\n\t\t} catch (error) {\n\t\t\tconst errorInfo = toErrorInfo(error instanceof Error ? error : String(error));\n\t\t\thandle.fail(errorInfo);\n\t\t\tthis.activeJobs--;\n\t\t\tthis.jobTracker.markFailed(handle.job.id, errorInfo, handle.job);\n\t\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\t\tjobId: handle.job.id,\n\t\t\t\terror: new Error(errorInfo.message),\n\t\t\t\tjob: handle.job\n\t\t\t}).catch(() => {});\n\t\t\tconst failedEvent = {\n\t\t\t\tjob: handle.job,\n\t\t\t\terror: errorInfo.message,\n\t\t\t\twillRetry: false,\n\t\t\t\tretryCount: 0,\n\t\t\t\tworkerId\n\t\t\t};\n\t\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_FAILED, failedEvent).catch(() => {});\n\t\t\tawait this.checkForMoreJobs();\n\t\t\treturn;\n\t\t}\n\t\tif (result.success) this.totalJobsProcessed++;\n\t\tif (result.success) {\n\t\t\tconst completedEvent = {\n\t\t\t\tjob: handle.job,\n\t\t\t\tresult,\n\t\t\t\tworkerId\n\t\t\t};\n\t\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_COMPLETED, completedEvent).catch(() => {});\n\t\t} else {\n\t\t\tconst failedEvent = {\n\t\t\t\tjob: handle.job,\n\t\t\t\terror: result.error?.message ?? \"unknown\",\n\t\t\t\twillRetry: false,\n\t\t\t\tretryCount: 0,\n\t\t\t\tworkerId\n\t\t\t};\n\t\t\tthis.eventBus.emit(JobExecutorEventTypes.JOB_FAILED, failedEvent).catch(() => {});\n\t\t}\n\t\tawait this.resultHandler.handleResult(handle, result, {\n\t\t\tdeferJob: (documentId, job) => {\n\t\t\t\tconst existing = this.deferredJobs.get(documentId) ?? [];\n\t\t\t\texisting.push(job);\n\t\t\t\tthis.deferredJobs.set(documentId, existing);\n\t\t\t},\n\t\t\tflushDeferredFor: (documentId) => this.flushDeferredJobs(documentId)\n\t\t});\n\t\tthis.activeJobs--;\n\t\tawait this.checkForMoreJobs();\n\t}\n\tasync checkForMoreJobs() {\n\t\tif (!this.isRunning) return;\n\t\tlet hasMore;\n\t\ttry {\n\t\t\thasMore = await this.queue.hasJobs();\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error checking for more jobs: @Error\", error);\n\t\t\treturn;\n\t\t}\n\t\tif (hasMore) await this.processNextJob();\n\t}\n\tasync processExistingJobs() {\n\t\tlet hasJobs;\n\t\ttry {\n\t\t\thasJobs = await this.queue.hasJobs();\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error checking for existing jobs: @Error\", error);\n\t\t\treturn;\n\t\t}\n\t\tif (hasJobs) {\n\t\t\tconst promises = [];\n\t\t\tfor (let i = 0; i < Math.min(this.executors.length, 5); i++) promises.push(this.processNextJob());\n\t\t\ttry {\n\t\t\t\tawait Promise.all(promises);\n\t\t\t} catch (error) {\n\t\t\t\tthis.logger.error(\"Error processing existing jobs: @Error\", error);\n\t\t\t}\n\t\t}\n\t}\n\tasync flushDeferredJobs(documentId) {\n\t\tconst jobs = this.deferredJobs.get(documentId);\n\t\tif (!jobs || jobs.length === 0) return;\n\t\tthis.deferredJobs.delete(documentId);\n\t\tfor (const job of jobs) try {\n\t\t\tawait this.queue.enqueue(job);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error re-enqueuing deferred job: @Error\", error);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/job-tracker/in-memory-job-tracker.ts\n/**\n* In-memory implementation of IJobTracker.\n* Maintains job status in a Map for synchronous access.\n* Subscribes to operation events to update job states.\n*/\nvar InMemoryJobTracker = class {\n\tjobs = /* @__PURE__ */ new Map();\n\tunsubscribers = [];\n\tconstructor(eventBus) {\n\t\tthis.eventBus = eventBus;\n\t\tthis.subscribeToEvents();\n\t}\n\tsubscribeToEvents() {\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY, (_type, event) => {\n\t\t\tthis.handleWriteReady(event);\n\t\t}));\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_READ_READY, (_type, event) => {\n\t\t\tthis.handleReadReady(event);\n\t\t}));\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_FAILED, (_type, event) => {\n\t\t\tthis.handleJobFailed(event);\n\t\t}));\n\t}\n\thandleWriteReady(event) {\n\t\tconst jobId = event.jobId;\n\t\tconst job = this.jobs.get(jobId);\n\t\tif (job && job.status === JobStatus.RUNNING) {\n\t\t\tconst consistencyToken = createConsistencyToken(event.operations);\n\t\t\tthis.jobs.set(jobId, {\n\t\t\t\t...job,\n\t\t\t\tstatus: JobStatus.WRITE_READY,\n\t\t\t\tconsistencyToken\n\t\t\t});\n\t\t}\n\t}\n\thandleReadReady(event) {\n\t\tconst jobId = event.jobId;\n\t\tconst job = this.jobs.get(jobId);\n\t\tif (job && job.status === JobStatus.WRITE_READY) this.jobs.set(jobId, {\n\t\t\t...job,\n\t\t\tstatus: JobStatus.READ_READY\n\t\t});\n\t}\n\thandleJobFailed(event) {\n\t\tthis.markFailed(event.jobId, {\n\t\t\tmessage: event.error.message,\n\t\t\tstack: event.error.stack || \"\"\n\t\t}, event.job);\n\t}\n\tshutdown() {\n\t\tfor (const unsubscribe of this.unsubscribers) unsubscribe();\n\t\tthis.unsubscribers = [];\n\t}\n\tregisterJob(jobInfo) {\n\t\tthis.jobs.set(jobInfo.id, { ...jobInfo });\n\t}\n\tmarkRunning(jobId) {\n\t\tconst job = this.jobs.get(jobId);\n\t\tif (!job) {\n\t\t\tthis.jobs.set(jobId, {\n\t\t\t\tid: jobId,\n\t\t\t\tdocumentId: \"\",\n\t\t\t\tstatus: JobStatus.RUNNING,\n\t\t\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\tconsistencyToken: createEmptyConsistencyToken(),\n\t\t\t\tmeta: {\n\t\t\t\t\tbatchId: jobId,\n\t\t\t\t\tbatchJobIds: [jobId]\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.jobs.set(jobId, {\n\t\t\t...job,\n\t\t\tstatus: JobStatus.RUNNING\n\t\t});\n\t}\n\tmarkFailed(jobId, error, job) {\n\t\tconst existing = this.jobs.get(jobId);\n\t\tif (!existing) {\n\t\t\tthis.jobs.set(jobId, {\n\t\t\t\tid: jobId,\n\t\t\t\tdocumentId: job?.documentId ?? \"\",\n\t\t\t\tstatus: JobStatus.FAILED,\n\t\t\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\tcompletedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\terror,\n\t\t\t\tjob,\n\t\t\t\tconsistencyToken: createEmptyConsistencyToken(),\n\t\t\t\tmeta: {\n\t\t\t\t\tbatchId: jobId,\n\t\t\t\t\tbatchJobIds: [jobId]\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.jobs.set(jobId, {\n\t\t\t...existing,\n\t\t\tstatus: JobStatus.FAILED,\n\t\t\tcompletedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\terror,\n\t\t\tjob,\n\t\t\tconsistencyToken: createEmptyConsistencyToken()\n\t\t});\n\t}\n\tgetJobStatus(jobId) {\n\t\tconst job = this.jobs.get(jobId);\n\t\treturn job ? { ...job } : null;\n\t}\n};\n//#endregion\n//#region src/processors/utils.ts\nfunction isDriveDeletion(op) {\n\treturn op.operation.action.type === \"DELETE_DOCUMENT\";\n}\nfunction extractDriveHeader(op) {\n\tif (!op.context.resultingState) return void 0;\n\treturn JSON.parse(op.context.resultingState).header;\n}\nfunction extractDeletedDocumentId(op) {\n\treturn op.operation.action.input.documentId ?? op.context.documentId;\n}\nfunction createMinimalDriveHeader(driveId, documentType) {\n\treturn {\n\t\tid: driveId,\n\t\tdocumentType,\n\t\tsig: {\n\t\t\tpublicKey: {},\n\t\t\tnonce: \"\"\n\t\t},\n\t\tslug: \"\",\n\t\tname: \"\",\n\t\tbranch: \"main\",\n\t\trevision: {},\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tlastModifiedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString()\n\t};\n}\nfunction matchesFilter(op, filter) {\n\tif (filter.documentType && filter.documentType.length > 0) {\n\t\tif (!filter.documentType.includes(op.context.documentType)) return false;\n\t}\n\tif (filter.scope && filter.scope.length > 0) {\n\t\tif (!filter.scope.includes(op.context.scope)) return false;\n\t}\n\tif (filter.branch && filter.branch.length > 0) {\n\t\tif (!filter.branch.includes(op.context.branch)) return false;\n\t}\n\tif (filter.documentId && filter.documentId.length > 0) {\n\t\tif (!filter.documentId.includes(\"*\") && !filter.documentId.includes(op.context.documentId)) return false;\n\t}\n\treturn true;\n}\n//#endregion\n//#region src/processors/processor-manager.ts\n/**\n* Manages processor lifecycle based on operations.\n* Extends BaseReadModel to receive operations from ReadModelCoordinator.\n*\n* Responsibilities:\n* 1. Detect drive creation from CREATE_DOCUMENT operations\n* 2. Create processors for each drive using registered factories\n* 3. Route operations to matching processors based on filters\n* 4. Clean up processors when drives are deleted or factories are unregistered\n* 5. Track per-processor cursors for failure recovery and backfill\n*/\nvar ProcessorManager = class extends BaseReadModel {\n\tfactoryRegistry = /* @__PURE__ */ new Map();\n\tprocessorsByDrive = /* @__PURE__ */ new Map();\n\tfactoryToProcessors = /* @__PURE__ */ new Map();\n\tknownDrives = /* @__PURE__ */ new Map();\n\tcursorCache = /* @__PURE__ */ new Map();\n\tlogger;\n\tdriveContainerTypes;\n\tconstructor(db, operationIndex, writeCache, consistencyTracker, logger, driveContainerTypes) {\n\t\tsuper(db, operationIndex, writeCache, consistencyTracker, {\n\t\t\treadModelId: \"processor-manager\",\n\t\t\trebuildStateOnInit: true\n\t\t});\n\t\tthis.logger = logger;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t}\n\tasync init() {\n\t\tawait super.init();\n\t\tawait this.loadAllCursors();\n\t\tawait this.discoverExistingDrives();\n\t}\n\tasync commitOperations(items) {\n\t\tawait this.detectAndRegisterNewDrives(items);\n\t\tawait this.detectAndCleanupDeletedDrives(items);\n\t\tawait this.routeOperationsToProcessors(items);\n\t}\n\tasync registerFactory(identifier, factory) {\n\t\tif (this.factoryRegistry.has(identifier)) await this.unregisterFactory(identifier);\n\t\tthis.factoryRegistry.set(identifier, factory);\n\t\tthis.factoryToProcessors.set(identifier, /* @__PURE__ */ new Map());\n\t\tfor (const [driveId, documentType] of this.knownDrives) {\n\t\t\tconst driveHeader = createMinimalDriveHeader(driveId, documentType);\n\t\t\tawait this.createProcessorsForDrive(driveId, identifier, factory, driveHeader);\n\t\t}\n\t}\n\tasync unregisterFactory(identifier) {\n\t\tconst factoryProcessors = this.factoryToProcessors.get(identifier);\n\t\tif (!factoryProcessors) return;\n\t\tfor (const [driveId, tracked] of factoryProcessors) {\n\t\t\tfor (const t of tracked) await this.safeDisconnect(t.record.processor);\n\t\t\tconst driveProcessors = this.processorsByDrive.get(driveId);\n\t\t\tif (driveProcessors) {\n\t\t\t\tconst remaining = driveProcessors.filter((p) => !tracked.includes(p));\n\t\t\t\tif (remaining.length > 0) this.processorsByDrive.set(driveId, remaining);\n\t\t\t\telse this.processorsByDrive.delete(driveId);\n\t\t\t}\n\t\t}\n\t\tawait this.deleteProcessorCursors({ factoryId: identifier });\n\t\tthis.factoryToProcessors.delete(identifier);\n\t\tthis.factoryRegistry.delete(identifier);\n\t}\n\tget(processorId) {\n\t\tfor (const tracked of this.allTrackedProcessors()) if (tracked.processorId === processorId) return tracked;\n\t}\n\tgetAll() {\n\t\treturn Array.from(this.allTrackedProcessors());\n\t}\n\t*allTrackedProcessors() {\n\t\tfor (const tracked of this.processorsByDrive.values()) yield* tracked;\n\t}\n\tasync detectAndRegisterNewDrives(operations) {\n\t\tfor (const op of operations) {\n\t\t\tif (!this.isDriveCreation(op)) continue;\n\t\t\tconst driveId = op.context.documentId;\n\t\t\tif (this.knownDrives.has(driveId)) continue;\n\t\t\tthis.knownDrives.set(driveId, op.context.documentType);\n\t\t\tconst driveHeader = extractDriveHeader(op);\n\t\t\tif (!driveHeader) continue;\n\t\t\tfor (const [identifier, factory] of this.factoryRegistry) await this.createProcessorsForDrive(driveId, identifier, factory, driveHeader);\n\t\t}\n\t}\n\tisDriveCreation(op) {\n\t\treturn op.operation.action.type === \"CREATE_DOCUMENT\" && this.driveContainerTypes.has(op.context.documentType);\n\t}\n\tasync detectAndCleanupDeletedDrives(operations) {\n\t\tfor (const op of operations) {\n\t\t\tif (!isDriveDeletion(op)) continue;\n\t\t\tconst driveId = extractDeletedDocumentId(op);\n\t\t\tif (!driveId || !this.knownDrives.has(driveId)) continue;\n\t\t\tif (!this.isDeletedDocumentADrive(driveId)) continue;\n\t\t\tawait this.cleanupDriveProcessors(driveId);\n\t\t\tthis.knownDrives.delete(driveId);\n\t\t}\n\t}\n\tasync discoverExistingDrives() {\n\t\tconst drives = await this.db.selectFrom(\"DocumentSnapshot\").select([\"documentId\", \"documentType\"]).where(\"documentType\", \"in\", [...this.driveContainerTypes]).where(\"isDeleted\", \"=\", false).execute();\n\t\tfor (const drive of drives) this.knownDrives.set(drive.documentId, drive.documentType);\n\t}\n\tisDeletedDocumentADrive(documentId) {\n\t\treturn this.knownDrives.has(documentId);\n\t}\n\tasync createProcessorsForDrive(driveId, identifier, factory, driveHeader) {\n\t\tlet records;\n\t\ttry {\n\t\t\trecords = await factory(driveHeader);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Factory '@FactoryId' failed for drive '@DriveId': @Error\", identifier, driveId, error);\n\t\t\treturn;\n\t\t}\n\t\tif (records.length === 0) return;\n\t\tconst trackedList = [];\n\t\tfor (let i = 0; i < records.length; i++) {\n\t\t\tconst record = records[i];\n\t\t\tconst processorId = `${identifier}:${driveId}:${i}`;\n\t\t\tconst cached = this.cursorCache.get(processorId);\n\t\t\tlet lastOrdinal;\n\t\t\tlet status;\n\t\t\tlet lastError;\n\t\t\tlet lastErrorTimestamp;\n\t\t\tif (cached) {\n\t\t\t\tlastOrdinal = cached.lastOrdinal;\n\t\t\t\tstatus = cached.status;\n\t\t\t\tlastError = cached.lastError ?? void 0;\n\t\t\t\tlastErrorTimestamp = cached.lastErrorTimestamp ?? void 0;\n\t\t\t} else {\n\t\t\t\tlastOrdinal = (record.startFrom ?? \"beginning\") === \"current\" ? this.lastOrdinal : 0;\n\t\t\t\tstatus = \"active\";\n\t\t\t\tlastError = void 0;\n\t\t\t\tlastErrorTimestamp = void 0;\n\t\t\t}\n\t\t\tconst tracked = {\n\t\t\t\tprocessorId,\n\t\t\t\tfactoryId: identifier,\n\t\t\t\tdriveId,\n\t\t\t\tprocessorIndex: i,\n\t\t\t\trecord,\n\t\t\t\tlastOrdinal,\n\t\t\t\tstatus,\n\t\t\t\tlastError,\n\t\t\t\tlastErrorTimestamp,\n\t\t\t\tretry: () => this.retryProcessor(tracked)\n\t\t\t};\n\t\t\ttrackedList.push(tracked);\n\t\t\tawait this.saveProcessorCursor(tracked);\n\t\t}\n\t\tawait this.db.deleteFrom(\"ProcessorCursor\").where(\"factoryId\", \"=\", identifier).where(\"driveId\", \"=\", driveId).where(\"processorIndex\", \">=\", records.length).execute();\n\t\tfor (const [id, row] of this.cursorCache) if (row.factoryId === identifier && row.driveId === driveId && row.processorIndex >= records.length) this.cursorCache.delete(id);\n\t\tconst factoryProcessors = this.factoryToProcessors.get(identifier);\n\t\tif (factoryProcessors) factoryProcessors.set(driveId, trackedList);\n\t\tconst existingDriveProcessors = this.processorsByDrive.get(driveId) ?? [];\n\t\tthis.processorsByDrive.set(driveId, [...existingDriveProcessors, ...trackedList]);\n\t\tfor (const tracked of trackedList) if (tracked.status === \"active\" && tracked.lastOrdinal < this.lastOrdinal) await this.backfillProcessor(tracked);\n\t}\n\tasync backfillProcessor(tracked) {\n\t\tlet page = await this.operationIndex.getSinceOrdinal(tracked.lastOrdinal);\n\t\twhile (page.results.length > 0) {\n\t\t\tconst matching = page.results.filter((op) => matchesFilter(op, tracked.record.filter));\n\t\t\tif (matching.length > 0) try {\n\t\t\t\tawait tracked.record.processor.onOperations(matching);\n\t\t\t} catch (error) {\n\t\t\t\ttracked.status = \"errored\";\n\t\t\t\ttracked.lastError = error instanceof Error ? error.message : String(error);\n\t\t\t\ttracked.lastErrorTimestamp = /* @__PURE__ */ new Date();\n\t\t\t\tawait this.safeSaveProcessorCursor(tracked);\n\t\t\t\tthis.logger.error(\"Processor '@ProcessorId' failed during backfill at ordinal @Ordinal: @Error\", tracked.processorId, tracked.lastOrdinal, error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttracked.lastOrdinal = Math.max(...page.results.map((op) => op.context.ordinal));\n\t\t\tawait this.safeSaveProcessorCursor(tracked);\n\t\t\tif (!page.next) break;\n\t\t\tpage = await page.next();\n\t\t}\n\t}\n\tasync retryProcessor(tracked) {\n\t\tif (tracked.status !== \"errored\") return;\n\t\ttracked.status = \"active\";\n\t\ttracked.lastError = void 0;\n\t\ttracked.lastErrorTimestamp = void 0;\n\t\tawait this.saveProcessorCursor(tracked);\n\t\tawait this.backfillProcessor(tracked);\n\t}\n\tasync cleanupDriveProcessors(driveId) {\n\t\tconst processors = this.processorsByDrive.get(driveId);\n\t\tif (!processors) return;\n\t\tfor (const tracked of processors) await this.safeDisconnect(tracked.record.processor);\n\t\tthis.processorsByDrive.delete(driveId);\n\t\tfor (const factoryProcessors of this.factoryToProcessors.values()) factoryProcessors.delete(driveId);\n\t\tawait this.deleteProcessorCursors({ driveId });\n\t}\n\tasync safeDisconnect(processor) {\n\t\ttry {\n\t\t\tawait processor.onDisconnect();\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error disconnecting processor: @Error\", error);\n\t\t}\n\t}\n\tasync routeOperationsToProcessors(operations) {\n\t\tconst maxOrdinal = Math.max(...operations.map((op) => op.context.ordinal));\n\t\tconst allTracked = Array.from(this.allTrackedProcessors());\n\t\tawait Promise.all(allTracked.map(async (tracked) => {\n\t\t\tif (tracked.status !== \"active\") return;\n\t\t\tconst matching = operations.filter((op) => op.context.ordinal > tracked.lastOrdinal).filter((op) => matchesFilter(op, tracked.record.filter));\n\t\t\tif (matching.length > 0) try {\n\t\t\t\tawait tracked.record.processor.onOperations(matching);\n\t\t\t} catch (error) {\n\t\t\t\ttracked.status = \"errored\";\n\t\t\t\ttracked.lastError = error instanceof Error ? error.message : String(error);\n\t\t\t\ttracked.lastErrorTimestamp = /* @__PURE__ */ new Date();\n\t\t\t\tawait this.safeSaveProcessorCursor(tracked);\n\t\t\t\tthis.logger.error(\"Processor '@ProcessorId' failed at ordinal @Ordinal: @Error\", tracked.processorId, tracked.lastOrdinal, error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttracked.lastOrdinal = maxOrdinal;\n\t\t\tawait this.safeSaveProcessorCursor(tracked);\n\t\t}));\n\t}\n\tasync loadAllCursors() {\n\t\tconst rows = await this.db.selectFrom(\"ProcessorCursor\").selectAll().execute();\n\t\tfor (const row of rows) this.cursorCache.set(row.processorId, row);\n\t}\n\tasync safeSaveProcessorCursor(tracked) {\n\t\ttry {\n\t\t\tawait this.saveProcessorCursor(tracked);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to persist cursor for '@ProcessorId': @Error\", tracked.processorId, error);\n\t\t}\n\t}\n\tasync saveProcessorCursor(tracked) {\n\t\tawait this.db.insertInto(\"ProcessorCursor\").values({\n\t\t\tprocessorId: tracked.processorId,\n\t\t\tfactoryId: tracked.factoryId,\n\t\t\tdriveId: tracked.driveId,\n\t\t\tprocessorIndex: tracked.processorIndex,\n\t\t\tlastOrdinal: tracked.lastOrdinal,\n\t\t\tstatus: tracked.status,\n\t\t\tlastError: tracked.lastError ?? null,\n\t\t\tlastErrorTimestamp: tracked.lastErrorTimestamp ?? null,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).onConflict((oc) => oc.column(\"processorId\").doUpdateSet({\n\t\t\tlastOrdinal: tracked.lastOrdinal,\n\t\t\tstatus: tracked.status,\n\t\t\tlastError: tracked.lastError ?? null,\n\t\t\tlastErrorTimestamp: tracked.lastErrorTimestamp ?? null,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t})).execute();\n\t\tthis.cursorCache.set(tracked.processorId, {\n\t\t\tprocessorId: tracked.processorId,\n\t\t\tfactoryId: tracked.factoryId,\n\t\t\tdriveId: tracked.driveId,\n\t\t\tprocessorIndex: tracked.processorIndex,\n\t\t\tlastOrdinal: tracked.lastOrdinal,\n\t\t\tstatus: tracked.status,\n\t\t\tlastError: tracked.lastError ?? null,\n\t\t\tlastErrorTimestamp: tracked.lastErrorTimestamp ?? null,\n\t\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t});\n\t}\n\tasync deleteProcessorCursors(filter) {\n\t\tif (\"factoryId\" in filter) {\n\t\t\tawait this.db.deleteFrom(\"ProcessorCursor\").where(\"factoryId\", \"=\", filter.factoryId).execute();\n\t\t\tfor (const [id, row] of this.cursorCache) if (row.factoryId === filter.factoryId) this.cursorCache.delete(id);\n\t\t} else {\n\t\t\tawait this.db.deleteFrom(\"ProcessorCursor\").where(\"driveId\", \"=\", filter.driveId).execute();\n\t\t\tfor (const [id, row] of this.cursorCache) if (row.driveId === filter.driveId) this.cursorCache.delete(id);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/queue/job-execution-handle.ts\n/**\n* Implementation of the IJobExecutionHandle interface\n*/\nvar JobExecutionHandle = class {\n\t_state;\n\t_job;\n\tonStart;\n\tonComplete;\n\tonFail;\n\tonDefer;\n\tgetStateName(state) {\n\t\tswitch (state) {\n\t\t\tcase JobQueueState.PREPROCESSING: return \"PREPROCESSING\";\n\t\t\tcase JobQueueState.PENDING: return \"PENDING\";\n\t\t\tcase JobQueueState.READY: return \"READY\";\n\t\t\tcase JobQueueState.RUNNING: return \"RUNNING\";\n\t\t\tcase JobQueueState.RESOLVED: return \"RESOLVED\";\n\t\t\tdefault: return `UNKNOWN`;\n\t\t}\n\t}\n\tconstructor(job, initialState, callbacks) {\n\t\tthis._job = job;\n\t\tthis._state = initialState;\n\t\tthis.onStart = callbacks?.onStart;\n\t\tthis.onComplete = callbacks?.onComplete;\n\t\tthis.onFail = callbacks?.onFail;\n\t\tthis.onDefer = callbacks?.onDefer;\n\t}\n\tget job() {\n\t\treturn this._job;\n\t}\n\tget state() {\n\t\treturn this._state;\n\t}\n\tstart() {\n\t\tif (this._state !== JobQueueState.READY) throw new Error(`Cannot start job in state ${this.getStateName(this._state)}`);\n\t\tthis._state = JobQueueState.RUNNING;\n\t\tthis.onStart?.();\n\t}\n\tcomplete() {\n\t\tif (this._state !== JobQueueState.RUNNING) throw new Error(`Cannot complete job in state ${this.getStateName(this._state)}`);\n\t\tthis._state = JobQueueState.RESOLVED;\n\t\tthis.onComplete?.();\n\t}\n\tfail(error) {\n\t\tif (this._state !== JobQueueState.RUNNING) throw new Error(`Cannot fail job in state ${this.getStateName(this._state)}`);\n\t\tthis._state = JobQueueState.RESOLVED;\n\t\tthis.onFail?.(error);\n\t}\n\tdefer() {\n\t\tif (this._state !== JobQueueState.RUNNING) throw new Error(`Cannot defer job in state ${this.getStateName(this._state)}`);\n\t\tthis._state = JobQueueState.RESOLVED;\n\t\tthis.onDefer?.();\n\t}\n};\n//#endregion\n//#region src/queue/queue.ts\n/**\n* In-memory implementation of the IQueue interface.\n* Organizes jobs by documentId, scope, and branch to ensure proper ordering.\n* Ensures serial execution per document by tracking executing jobs.\n* Implements dependency management through queue hints.\n*/\nvar InMemoryQueue = class {\n\tqueues = /* @__PURE__ */ new Map();\n\tjobIdToQueueKey = /* @__PURE__ */ new Map();\n\tdocIdToJobId = /* @__PURE__ */ new Map();\n\tjobIdToDocId = /* @__PURE__ */ new Map();\n\tcompletedJobs = /* @__PURE__ */ new Set();\n\tjobIndex = /* @__PURE__ */ new Map();\n\tisBlocked = false;\n\tonDrainedCallback;\n\tisPausedFlag = false;\n\tconstructor(eventBus, resolver) {\n\t\tthis.eventBus = eventBus;\n\t\tthis.resolver = resolver;\n\t}\n\ttoErrorInfo(error) {\n\t\tif (error instanceof Error) return {\n\t\t\tmessage: error.message,\n\t\t\tstack: error.stack || (/* @__PURE__ */ new Error()).stack || \"\"\n\t\t};\n\t\treturn {\n\t\t\tmessage: error,\n\t\t\tstack: (/* @__PURE__ */ new Error()).stack || \"\"\n\t\t};\n\t}\n\t/**\n\t* Creates a unique key for a document/scope/branch combination\n\t*/\n\tcreateQueueKey(documentId, scope, branch) {\n\t\treturn `${documentId}:${scope}:${branch}`;\n\t}\n\t/**\n\t* Gets or creates a queue for the given key\n\t*/\n\tgetQueue(queueKey) {\n\t\tlet queue = this.queues.get(queueKey);\n\t\tif (!queue) {\n\t\t\tqueue = [];\n\t\t\tthis.queues.set(queueKey, queue);\n\t\t}\n\t\treturn queue;\n\t}\n\t/**\n\t* Check if a document has any jobs currently executing\n\t*/\n\tisDocumentExecuting(documentId) {\n\t\tconst executingSet = this.docIdToJobId.get(documentId);\n\t\treturn executingSet ? executingSet.size > 0 : false;\n\t}\n\t/**\n\t* Mark a job as executing for its document\n\t*/\n\tmarkJobExecuting(job) {\n\t\tlet executingSet = this.docIdToJobId.get(job.documentId);\n\t\tif (!executingSet) {\n\t\t\texecutingSet = /* @__PURE__ */ new Set();\n\t\t\tthis.docIdToJobId.set(job.documentId, executingSet);\n\t\t}\n\t\texecutingSet.add(job.id);\n\t\tthis.jobIdToDocId.set(job.id, job.documentId);\n\t}\n\t/**\n\t* Mark a job as no longer executing for its document\n\t*/\n\tmarkJobComplete(jobId, documentId) {\n\t\tconst executingSet = this.docIdToJobId.get(documentId);\n\t\tif (executingSet) {\n\t\t\texecutingSet.delete(jobId);\n\t\t\tif (executingSet.size === 0) this.docIdToJobId.delete(documentId);\n\t\t}\n\t\tthis.jobIdToDocId.delete(jobId);\n\t}\n\t/**\n\t* Check if all dependencies for a job have been completed\n\t*/\n\tareDependenciesMet(job) {\n\t\tif (job.queueHint.length === 0) return true;\n\t\treturn job.queueHint.every((depId) => this.completedJobs.has(depId));\n\t}\n\t/**\n\t* Returns the head of the sub-queue if its dependencies are met, or null.\n\t*\n\t* The dispatcher only ever considers the head — a dep-blocked head holds\n\t* the rest of its sub-queue. This preserves per-(documentId, scope, branch)\n\t* FIFO regardless of how dependencies are authored, and makes the queue's\n\t* documented \"serialized per document\" invariant hold even when callers\n\t* omit queueHint dependencies on jobs that share a sub-queue.\n\t*/\n\tgetNextJobWithMetDependencies(queue) {\n\t\tif (queue.length === 0) return null;\n\t\tconst head = queue[0];\n\t\treturn this.areDependenciesMet(head) ? head : null;\n\t}\n\tgetCreateDocumentType(job) {\n\t\tfor (const action of job.actions) if (action.type === \"CREATE_DOCUMENT\") return action.input.model;\n\t\tfor (const operation of job.operations) if (operation.action.type === \"CREATE_DOCUMENT\") return operation.action.input.model;\n\t}\n\tasync enqueue(job) {\n\t\tif (this.isBlocked) throw new Error(\"Queue is blocked\");\n\t\tconst queueKey = this.createQueueKey(job.documentId, job.scope, job.branch);\n\t\tthis.getQueue(queueKey).push(job);\n\t\tthis.jobIdToQueueKey.set(job.id, queueKey);\n\t\tthis.jobIndex.set(job.id, job);\n\t\tconst documentType = this.getCreateDocumentType(job);\n\t\tif (documentType) try {\n\t\t\tawait this.resolver.ensureModelLoaded(documentType);\n\t\t} catch {\n\t\t\tawait this.failJob(job.id, {\n\t\t\t\tmessage: `Failed to load document model for type: ${documentType}`,\n\t\t\t\tstack: (/* @__PURE__ */ new Error()).stack || \"\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst eventData = {\n\t\t\tdocumentId: job.documentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch,\n\t\t\tjobId: job.id\n\t\t};\n\t\tawait this.eventBus.emit(QueueEventTypes.JOB_AVAILABLE, eventData);\n\t}\n\tdequeue(documentId, scope, branch, signal) {\n\t\tconst queueKey = this.createQueueKey(documentId, scope, branch);\n\t\tconst queue = this.queues.get(queueKey);\n\t\tif (signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\tif (!queue || queue.length === 0) return Promise.resolve(null);\n\t\tconst job = this.getNextJobWithMetDependencies(queue);\n\t\tif (!job) return Promise.resolve(null);\n\t\tconst jobIndex = queue.indexOf(job);\n\t\tqueue.splice(jobIndex, 1);\n\t\tthis.jobIdToQueueKey.delete(job.id);\n\t\tthis.markJobExecuting(job);\n\t\tif (queue.length === 0) this.queues.delete(queueKey);\n\t\tconst handle = new JobExecutionHandle(job, JobQueueState.READY, {\n\t\t\tonStart: () => {},\n\t\t\tonComplete: () => {\n\t\t\t\tthis.completeJob(job.id);\n\t\t\t},\n\t\t\tonFail: (error) => {\n\t\t\t\tthis.failJob(job.id, error);\n\t\t\t},\n\t\t\tonDefer: () => {\n\t\t\t\tthis.deferJob(job.id);\n\t\t\t}\n\t\t});\n\t\treturn Promise.resolve(handle);\n\t}\n\tdequeueNext(signal) {\n\t\tif (signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\tif (this.isPausedFlag) return Promise.resolve(null);\n\t\tfor (const [queueKey, queue] of this.queues.entries()) if (queue.length > 0) {\n\t\t\tconst job = this.getNextJobWithMetDependencies(queue);\n\t\t\tif (!job) continue;\n\t\t\tif (!this.isDocumentExecuting(job.documentId)) {\n\t\t\t\tconst jobIdx = queue.indexOf(job);\n\t\t\t\tqueue.splice(jobIdx, 1);\n\t\t\t\tthis.jobIdToQueueKey.delete(job.id);\n\t\t\t\tthis.markJobExecuting(job);\n\t\t\t\tif (queue.length === 0) this.queues.delete(queueKey);\n\t\t\t\tconst handle = new JobExecutionHandle(job, JobQueueState.READY, {\n\t\t\t\t\tonStart: () => {},\n\t\t\t\t\tonComplete: () => {\n\t\t\t\t\t\tthis.completeJob(job.id);\n\t\t\t\t\t},\n\t\t\t\t\tonFail: (error) => {\n\t\t\t\t\t\tthis.failJob(job.id, error);\n\t\t\t\t\t},\n\t\t\t\t\tonDefer: () => {\n\t\t\t\t\t\tthis.deferJob(job.id);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn Promise.resolve(handle);\n\t\t\t}\n\t\t}\n\t\treturn Promise.resolve(null);\n\t}\n\tdequeueNextMatching(predicate, signal) {\n\t\tif (signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\tif (this.isPausedFlag) return Promise.resolve(null);\n\t\tfor (const [queueKey, queue] of this.queues.entries()) if (queue.length > 0) {\n\t\t\tconst job = this.getNextJobWithMetDependencies(queue);\n\t\t\tif (!job) continue;\n\t\t\tif (this.isDocumentExecuting(job.documentId)) continue;\n\t\t\tif (!predicate({\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch\n\t\t\t})) continue;\n\t\t\tconst jobIdx = queue.indexOf(job);\n\t\t\tqueue.splice(jobIdx, 1);\n\t\t\tthis.jobIdToQueueKey.delete(job.id);\n\t\t\tthis.markJobExecuting(job);\n\t\t\tif (queue.length === 0) this.queues.delete(queueKey);\n\t\t\tconst handle = new JobExecutionHandle(job, JobQueueState.READY, {\n\t\t\t\tonStart: () => {},\n\t\t\t\tonComplete: () => {\n\t\t\t\t\tthis.completeJob(job.id);\n\t\t\t\t},\n\t\t\t\tonFail: (error) => {\n\t\t\t\t\tthis.failJob(job.id, error);\n\t\t\t\t},\n\t\t\t\tonDefer: () => {\n\t\t\t\t\tthis.deferJob(job.id);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn Promise.resolve(handle);\n\t\t}\n\t\treturn Promise.resolve(null);\n\t}\n\tsize(documentId, scope, branch) {\n\t\tconst queueKey = this.createQueueKey(documentId, scope, branch);\n\t\tconst queue = this.queues.get(queueKey);\n\t\treturn Promise.resolve(queue ? queue.length : 0);\n\t}\n\ttotalSize() {\n\t\tlet total = 0;\n\t\tfor (const queue of this.queues.values()) total += queue.length;\n\t\treturn Promise.resolve(total);\n\t}\n\tremove(jobId) {\n\t\tconst queueKey = this.jobIdToQueueKey.get(jobId);\n\t\tif (!queueKey) return Promise.resolve(false);\n\t\tconst queue = this.queues.get(queueKey);\n\t\tif (!queue) {\n\t\t\tthis.jobIdToQueueKey.delete(jobId);\n\t\t\tthis.jobIndex.delete(jobId);\n\t\t\treturn Promise.resolve(false);\n\t\t}\n\t\tconst jobIdx = queue.findIndex((job) => job.id === jobId);\n\t\tif (jobIdx === -1) {\n\t\t\tthis.jobIdToQueueKey.delete(jobId);\n\t\t\tthis.jobIndex.delete(jobId);\n\t\t\treturn Promise.resolve(false);\n\t\t}\n\t\tqueue.splice(jobIdx, 1);\n\t\tthis.jobIdToQueueKey.delete(jobId);\n\t\tthis.jobIndex.delete(jobId);\n\t\tif (queue.length === 0) this.queues.delete(queueKey);\n\t\treturn Promise.resolve(true);\n\t}\n\tclear(documentId, scope, branch) {\n\t\tconst queueKey = this.createQueueKey(documentId, scope, branch);\n\t\tconst queue = this.queues.get(queueKey);\n\t\tif (queue) {\n\t\t\tfor (const job of queue) {\n\t\t\t\tthis.jobIdToQueueKey.delete(job.id);\n\t\t\t\tthis.jobIndex.delete(job.id);\n\t\t\t}\n\t\t\tthis.queues.delete(queueKey);\n\t\t}\n\t\treturn Promise.resolve();\n\t}\n\tclearAll() {\n\t\tthis.jobIdToQueueKey.clear();\n\t\tthis.jobIndex.clear();\n\t\tthis.completedJobs.clear();\n\t\tthis.queues.clear();\n\t\treturn Promise.resolve();\n\t}\n\thasJobs() {\n\t\treturn Promise.resolve(this.queues.size > 0 && Array.from(this.queues.values()).some((q) => q.length > 0));\n\t}\n\tasync completeJob(jobId) {\n\t\tconst documentId = this.jobIdToDocId.get(jobId);\n\t\tif (documentId) this.markJobComplete(jobId, documentId);\n\t\tthis.completedJobs.add(jobId);\n\t\tthis.jobIndex.delete(jobId);\n\t\tawait this.remove(jobId);\n\t\tthis.checkDrained();\n\t}\n\tasync failJob(jobId, error) {\n\t\tconst documentId = this.jobIdToDocId.get(jobId);\n\t\tif (documentId) this.markJobComplete(jobId, documentId);\n\t\tconst job = this.jobIndex.get(jobId);\n\t\tif (job) {\n\t\t\tjob.lastError = error;\n\t\t\tif (error) job.errorHistory.push(error);\n\t\t}\n\t\tthis.jobIndex.delete(jobId);\n\t\tthis.completedJobs.add(jobId);\n\t\tawait this.remove(jobId);\n\t\tthis.eventBus.emit(ReactorEventTypes.JOB_FAILED, {\n\t\t\tjobId,\n\t\t\terror: new Error(error?.message ?? \"Job failed\"),\n\t\t\tjob\n\t\t}).catch(() => {});\n\t\tthis.checkDrained();\n\t}\n\tdeferJob(jobId) {\n\t\tconst documentId = this.jobIdToDocId.get(jobId);\n\t\tif (documentId) this.markJobComplete(jobId, documentId);\n\t\tthis.jobIndex.delete(jobId);\n\t}\n\tasync retryJob(jobId, error) {\n\t\tconst job = this.jobIndex.get(jobId);\n\t\tif (!job) return;\n\t\tjob.lastError = error;\n\t\tconst documentId = this.jobIdToDocId.get(jobId);\n\t\tif (documentId) this.markJobComplete(jobId, documentId);\n\t\tthis.jobIndex.delete(jobId);\n\t\tthis.jobIdToQueueKey.delete(jobId);\n\t\tif (error) job.errorHistory.push(error);\n\t\tconst updatedJob = {\n\t\t\t...job,\n\t\t\tretryCount: (job.retryCount || 0) + 1,\n\t\t\tlastError: error\n\t\t};\n\t\tawait this.enqueue(updatedJob);\n\t}\n\t/**\n\t* Check if the queue is drained and call the callback if it is\n\t*/\n\tcheckDrained() {\n\t\tif (this.isDrained && this.onDrainedCallback) {\n\t\t\tconst callback = this.onDrainedCallback;\n\t\t\tthis.onDrainedCallback = void 0;\n\t\t\tcallback();\n\t\t}\n\t}\n\t/**\n\t* Returns true if and only if all jobs have been resolved.\n\t*/\n\tget isDrained() {\n\t\tconst hasPendingJobs = this.queues.size > 0 && Array.from(this.queues.values()).some((q) => q.length > 0);\n\t\tconst hasExecutingJobs = this.docIdToJobId.size > 0 && Array.from(this.docIdToJobId.values()).some((set) => set.size > 0);\n\t\treturn !hasPendingJobs && !hasExecutingJobs;\n\t}\n\t/**\n\t* Blocks the queue from accepting new jobs.\n\t* @param onDrained - Optional callback to call when the queue is drained\n\t*/\n\tblock(onDrained) {\n\t\tthis.isBlocked = true;\n\t\tthis.onDrainedCallback = onDrained;\n\t\tthis.checkDrained();\n\t}\n\t/**\n\t* Unblocks the queue from accepting new jobs.\n\t*/\n\tunblock() {\n\t\tthis.isBlocked = false;\n\t\tthis.onDrainedCallback = void 0;\n\t}\n\t/**\n\t* Pauses job dequeuing. Jobs can still be enqueued but dequeueNext() will return null.\n\t*/\n\tpause() {\n\t\tthis.isPausedFlag = true;\n\t}\n\t/**\n\t* Resumes job dequeuing and emits JOB_AVAILABLE events for pending jobs to wake up executors.\n\t*/\n\tasync resume() {\n\t\tthis.isPausedFlag = false;\n\t\tfor (const [, queue] of this.queues.entries()) if (queue.length > 0) {\n\t\t\tconst job = queue[0];\n\t\t\tawait this.eventBus.emit(QueueEventTypes.JOB_AVAILABLE, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tjobId: job.id\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Returns whether job dequeuing is paused.\n\t*/\n\tget paused() {\n\t\treturn this.isPausedFlag;\n\t}\n\t/**\n\t* Returns all pending jobs across all queues.\n\t*/\n\tgetPendingJobs() {\n\t\tconst jobs = [];\n\t\tfor (const queue of this.queues.values()) jobs.push(...queue);\n\t\treturn jobs;\n\t}\n\t/**\n\t* Returns a map of document IDs to sets of executing job IDs.\n\t*/\n\tgetExecutingJobIds() {\n\t\treturn new Map(Array.from(this.docIdToJobId.entries()).map(([k, v]) => [k, new Set(v)]));\n\t}\n\t/**\n\t* Returns a job by ID from the job index.\n\t*/\n\tgetJob(jobId) {\n\t\treturn this.jobIndex.get(jobId);\n\t}\n};\n//#endregion\n//#region src/registry/document-model-resolver.ts\n/**\n* Encapsulates the logic for resolving document model modules on demand.\n* Shared between the queue (CREATE_DOCUMENT gate) and the executor manager\n* (post-failure recovery) so that both paths use the same deduplication\n* and failure-caching state.\n*/\nvar DocumentModelResolver = class {\n\tloadingModels = /* @__PURE__ */ new Map();\n\tfailedModelTypes = /* @__PURE__ */ new Set();\n\tbroadcastHook = null;\n\tconstructor(registry, loader) {\n\t\tthis.registry = registry;\n\t\tthis.loader = loader;\n\t}\n\t/**\n\t* Install a post-success hook called after the resolver registers a\n\t* newly loaded model. ReactorBuilder uses this to wire the worker-pool\n\t* `load-model` broadcast without touching the resolver's constructor.\n\t*/\n\tsetBroadcastHook(hook) {\n\t\tthis.broadcastHook = hook;\n\t}\n\tasync ensureModelLoaded(documentType) {\n\t\ttry {\n\t\t\tthis.registry.getModule(documentType);\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tif (!ModuleNotFoundError.isError(error)) throw error;\n\t\t}\n\t\tif (this.failedModelTypes.has(documentType)) throw new Error(`Document model type previously failed to load: ${documentType}`);\n\t\tconst existing = this.loadingModels.get(documentType);\n\t\tif (existing) return existing;\n\t\tconst loadPromise = (async () => {\n\t\t\ttry {\n\t\t\t\tconst module = await this.loader.load(documentType);\n\t\t\t\tconst [result] = this.registry.registerModules(module);\n\t\t\t\tif (result.status === \"error\" && !DuplicateModuleError.isError(result.error)) throw result.error;\n\t\t\t\tawait this.broadcastIfPossible(documentType);\n\t\t\t} catch (error) {\n\t\t\t\tthis.failedModelTypes.add(documentType);\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tthis.loadingModels.delete(documentType);\n\t\t\t}\n\t\t})();\n\t\tthis.loadingModels.set(documentType, loadPromise);\n\t\treturn loadPromise;\n\t}\n\tasync broadcastIfPossible(documentType) {\n\t\tif (!this.broadcastHook || !this.loader.resolveSpec) return;\n\t\tconst entry = await this.loader.resolveSpec(documentType);\n\t\tif (!entry) return;\n\t\tawait this.broadcastHook(entry);\n\t}\n};\n/**\n* No-op resolver used when no document model loader is configured.\n* Checks the registry for the model and returns if found; throws if not.\n* Since there is no loader, missing models cannot be recovered.\n*/\nvar NullDocumentModelResolver = class {\n\tconstructor(registry) {\n\t\tthis.registry = registry;\n\t}\n\tensureModelLoaded(documentType) {\n\t\tif (this.registry) try {\n\t\t\tthis.registry.getModule(documentType);\n\t\t\treturn Promise.resolve();\n\t\t} catch {}\n\t\treturn Promise.reject(new ModuleNotFoundError(documentType));\n\t}\n};\n//#endregion\n//#region src/subs/default-error-handler.ts\n/**\n* Default error handler that re-throws subscription errors.\n* This ensures that errors are not silently swallowed.\n*/\nvar DefaultSubscriptionErrorHandler = class {\n\thandleError(error, context) {\n\t\tconst errorMessage = `Subscription error in ${context.eventType} (${context.subscriptionId})`;\n\t\tif (error instanceof Error) {\n\t\t\tconst enhancedError = /* @__PURE__ */ new Error(`${errorMessage}: ${error.message}`);\n\t\t\tenhancedError.cause = error;\n\t\t\tenhancedError.stack = error.stack;\n\t\t\tthrow enhancedError;\n\t\t} else throw new Error(`${errorMessage}: ${String(error)}`);\n\t}\n};\n//#endregion\n//#region src/subs/react-subscription-manager.ts\nvar ReactorSubscriptionManager = class {\n\tcreatedSubscriptions = /* @__PURE__ */ new Map();\n\tdeletedSubscriptions = /* @__PURE__ */ new Map();\n\tupdatedSubscriptions = /* @__PURE__ */ new Map();\n\trelationshipSubscriptions = /* @__PURE__ */ new Map();\n\tsubscriptionCounter = 0;\n\terrorHandler;\n\tconstructor(errorHandler) {\n\t\tthis.errorHandler = errorHandler;\n\t}\n\tonDocumentCreated(callback, search) {\n\t\tconst id = `created-${++this.subscriptionCounter}`;\n\t\tthis.createdSubscriptions.set(id, {\n\t\t\tid,\n\t\t\tcallback,\n\t\t\tsearch\n\t\t});\n\t\treturn () => {\n\t\t\tthis.createdSubscriptions.delete(id);\n\t\t};\n\t}\n\tonDocumentDeleted(callback, search) {\n\t\tconst id = `deleted-${++this.subscriptionCounter}`;\n\t\tthis.deletedSubscriptions.set(id, {\n\t\t\tid,\n\t\t\tcallback,\n\t\t\tsearch\n\t\t});\n\t\treturn () => {\n\t\t\tthis.deletedSubscriptions.delete(id);\n\t\t};\n\t}\n\tonDocumentStateUpdated(callback, search, view) {\n\t\tconst id = `updated-${++this.subscriptionCounter}`;\n\t\tthis.updatedSubscriptions.set(id, {\n\t\t\tid,\n\t\t\tcallback,\n\t\t\tsearch,\n\t\t\tview\n\t\t});\n\t\treturn () => {\n\t\t\tthis.updatedSubscriptions.delete(id);\n\t\t};\n\t}\n\tonRelationshipChanged(callback, search) {\n\t\tconst id = `relationship-${++this.subscriptionCounter}`;\n\t\tthis.relationshipSubscriptions.set(id, {\n\t\t\tid,\n\t\t\tcallback,\n\t\t\tsearch\n\t\t});\n\t\treturn () => {\n\t\t\tthis.relationshipSubscriptions.delete(id);\n\t\t};\n\t}\n\t/**\n\t* Notify subscribers about created documents\n\t*/\n\tnotifyDocumentsCreated(documentIds, documentTypes, parentIds) {\n\t\tconst result = {\n\t\t\tresults: documentIds,\n\t\t\toptions: {\n\t\t\t\tcursor: \"\",\n\t\t\t\tlimit: documentIds.length\n\t\t\t}\n\t\t};\n\t\tfor (const subscription of this.createdSubscriptions.values()) {\n\t\t\tconst filteredIds = this.filterDocumentIds(documentIds, subscription.search, documentTypes, parentIds);\n\t\t\tif (filteredIds.length > 0) try {\n\t\t\t\tsubscription.callback({\n\t\t\t\t\t...result,\n\t\t\t\t\tresults: filteredIds\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthis.errorHandler.handleError(error, {\n\t\t\t\t\teventType: \"created\",\n\t\t\t\t\tsubscriptionId: subscription.id,\n\t\t\t\t\teventData: filteredIds\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t* Notify subscribers about deleted documents\n\t*/\n\tnotifyDocumentsDeleted(documentIds, documentTypes, parentIds) {\n\t\tfor (const subscription of this.deletedSubscriptions.values()) {\n\t\t\tconst filteredIds = this.filterDocumentIds(documentIds, subscription.search, documentTypes, parentIds);\n\t\t\tif (filteredIds.length > 0) try {\n\t\t\t\tsubscription.callback(filteredIds);\n\t\t\t} catch (error) {\n\t\t\t\tthis.errorHandler.handleError(error, {\n\t\t\t\t\teventType: \"deleted\",\n\t\t\t\t\tsubscriptionId: subscription.id,\n\t\t\t\t\teventData: filteredIds\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t* Notify subscribers about updated documents\n\t*/\n\tnotifyDocumentsUpdated(documents) {\n\t\tconst result = {\n\t\t\tresults: documents,\n\t\t\toptions: {\n\t\t\t\tcursor: \"\",\n\t\t\t\tlimit: documents.length\n\t\t\t}\n\t\t};\n\t\tfor (const subscription of this.updatedSubscriptions.values()) {\n\t\t\tconst filteredDocs = this.filterDocuments(documents, subscription.search);\n\t\t\tif (filteredDocs.length > 0) try {\n\t\t\t\tsubscription.callback({\n\t\t\t\t\t...result,\n\t\t\t\t\tresults: filteredDocs\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthis.errorHandler.handleError(error, {\n\t\t\t\t\teventType: \"updated\",\n\t\t\t\t\tsubscriptionId: subscription.id,\n\t\t\t\t\teventData: filteredDocs\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t* Notify subscribers about relationship changes\n\t*/\n\tnotifyRelationshipChanged(parentId, childId, changeType, childType) {\n\t\tfor (const subscription of this.relationshipSubscriptions.values()) if (this.matchesRelationshipFilter(parentId, childId, childType, subscription.search)) try {\n\t\t\tsubscription.callback(parentId, childId, changeType);\n\t\t} catch (error) {\n\t\t\tthis.errorHandler.handleError(error, {\n\t\t\t\teventType: \"relationshipChanged\",\n\t\t\t\tsubscriptionId: subscription.id,\n\t\t\t\teventData: {\n\t\t\t\t\tparentId,\n\t\t\t\t\tchildId,\n\t\t\t\t\tchangeType\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Clear all subscriptions\n\t*/\n\tclearAll() {\n\t\tthis.createdSubscriptions.clear();\n\t\tthis.deletedSubscriptions.clear();\n\t\tthis.updatedSubscriptions.clear();\n\t\tthis.relationshipSubscriptions.clear();\n\t}\n\tfilterDocumentIds(documentIds, search, documentTypes, parentIds) {\n\t\tif (!search) return documentIds;\n\t\treturn documentIds.filter((id) => {\n\t\t\tif (search.ids && !search.ids.includes(id)) return false;\n\t\t\tif (search.type && documentTypes) {\n\t\t\t\tif (documentTypes.get(id) !== search.type) return false;\n\t\t\t}\n\t\t\tif (search.parentId && parentIds) {\n\t\t\t\tif (parentIds.get(id) !== search.parentId) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t}\n\tfilterDocuments(documents, search) {\n\t\tif (!search) return documents;\n\t\treturn documents.filter((doc) => {\n\t\t\tif (search.ids && !search.ids.includes(doc.header.id)) return false;\n\t\t\tif (search.type && doc.header.documentType !== search.type) return false;\n\t\t\tif (search.slugs && !search.slugs.includes(doc.header.slug)) return false;\n\t\t\treturn true;\n\t\t});\n\t}\n\tmatchesRelationshipFilter(parentId, childId, childType, search) {\n\t\tif (!search) return true;\n\t\tif (search.parentId && parentId !== search.parentId) return false;\n\t\tif (search.ids && !search.ids.includes(childId)) return false;\n\t\tif (search.type && childType && childType !== search.type) return false;\n\t\treturn true;\n\t}\n};\n//#endregion\n//#region src/subs/subscription-notification-read-model.ts\n/**\n* A read model that notifies the subscription manager when operations are processed.\n* This bridges the gap between operation processing and subscription callbacks.\n*\n* Must be processed AFTER other read models have completed and AFTER READ_READY\n* is emitted, so that reactor.get() returns fresh data when callbacks fire.\n*/\nvar SubscriptionNotificationReadModel = class {\n\tname = \"subscription-notification\";\n\tconstructor(subscriptionManager, documentView) {\n\t\tthis.subscriptionManager = subscriptionManager;\n\t\tthis.documentView = documentView;\n\t}\n\tasync indexOperations(operations) {\n\t\tif (operations.length === 0) return;\n\t\tconst created = [];\n\t\tconst deleted = [];\n\t\tconst updatedIds = /* @__PURE__ */ new Set();\n\t\tconst documentTypes = /* @__PURE__ */ new Map();\n\t\tconst parentIds = /* @__PURE__ */ new Map();\n\t\tfor (const item of operations) {\n\t\t\tconst { operation, context } = item;\n\t\t\tconst actionType = operation.action.type;\n\t\t\tdocumentTypes.set(context.documentId, context.documentType);\n\t\t\tif (actionType === \"CREATE_DOCUMENT\") created.push(context.documentId);\n\t\t\telse if (actionType === \"DELETE_DOCUMENT\") {\n\t\t\t\tconst deletedId = operation.action.input.documentId ?? context.documentId;\n\t\t\t\tdeleted.push(deletedId);\n\t\t\t} else if (actionType === \"ADD_RELATIONSHIP\") {\n\t\t\t\tconst input = operation.action.input;\n\t\t\t\tthis.subscriptionManager.notifyRelationshipChanged(input.sourceId, input.targetId, RelationshipChangeType.Added, input.childType);\n\t\t\t} else if (actionType === \"REMOVE_RELATIONSHIP\") {\n\t\t\t\tconst input = operation.action.input;\n\t\t\t\tthis.subscriptionManager.notifyRelationshipChanged(input.sourceId, input.targetId, RelationshipChangeType.Removed, input.childType);\n\t\t\t} else if (!created.includes(context.documentId)) updatedIds.add(context.documentId);\n\t\t}\n\t\tif (created.length > 0) this.subscriptionManager.notifyDocumentsCreated(created, documentTypes, parentIds);\n\t\tif (deleted.length > 0) this.subscriptionManager.notifyDocumentsDeleted(deleted, documentTypes, parentIds);\n\t\tif (updatedIds.size > 0 && this.documentView) {\n\t\t\tconst documents = await Promise.all(Array.from(updatedIds).map((id) => this.documentView.get(id)));\n\t\t\tthis.subscriptionManager.notifyDocumentsUpdated(documents);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/sync/types.ts\nlet ChannelScheme = /* @__PURE__ */ function(ChannelScheme) {\n\tChannelScheme[\"CONNECT\"] = \"connect\";\n\tChannelScheme[\"SWITCHBOARD\"] = \"switchboard\";\n\treturn ChannelScheme;\n}({});\n/**\n* Controls how a remote drives its polling schedule.\n* - `Auto` (default): the channel runs the configured interval timer in the background.\n* - `Manual`: the channel registers and connects but never ticks on its own.\n* Callers must invoke ISyncManager.triggerPull(name) to fetch.\n*/\nlet PollBehavior = /* @__PURE__ */ function(PollBehavior) {\n\tPollBehavior[\"Auto\"] = \"auto\";\n\tPollBehavior[\"Manual\"] = \"manual\";\n\treturn PollBehavior;\n}({});\nlet SyncOperationStatus = /* @__PURE__ */ function(SyncOperationStatus) {\n\tSyncOperationStatus[SyncOperationStatus[\"Unknown\"] = -1] = \"Unknown\";\n\tSyncOperationStatus[SyncOperationStatus[\"TransportPending\"] = 0] = \"TransportPending\";\n\tSyncOperationStatus[SyncOperationStatus[\"ExecutionPending\"] = 1] = \"ExecutionPending\";\n\tSyncOperationStatus[SyncOperationStatus[\"Applied\"] = 2] = \"Applied\";\n\tSyncOperationStatus[SyncOperationStatus[\"Error\"] = 3] = \"Error\";\n\treturn SyncOperationStatus;\n}({});\nlet ChannelErrorSource = /* @__PURE__ */ function(ChannelErrorSource) {\n\tChannelErrorSource[\"None\"] = \"none\";\n\tChannelErrorSource[\"Channel\"] = \"channel\";\n\tChannelErrorSource[\"Inbox\"] = \"inbox\";\n\tChannelErrorSource[\"Outbox\"] = \"outbox\";\n\treturn ChannelErrorSource;\n}({});\n/**\n* Event types for sync lifecycle events.\n* These events track the sync progress of a job's operations to remotes.\n* Uses a separate namespace (20000 range) from ReactorEventTypes (10000 range).\n*/\nconst SyncEventTypes = {\n\tSYNC_PENDING: 20001,\n\tSYNC_SUCCEEDED: 20002,\n\tSYNC_FAILED: 20003,\n\tDEAD_LETTER_ADDED: 20004,\n\tCONNECTION_STATE_CHANGED: 20005\n};\n//#endregion\n//#region src/sync/mailbox.ts\nvar MailboxAggregateError = class extends Error {\n\terrors;\n\tconstructor(errors) {\n\t\tconst messages = errors.map((e) => e.message).join(\"; \");\n\t\tsuper(`Mailbox callback failed with ${errors.length} error(s): ${messages}`);\n\t\tthis.name = \"MailboxAggregateError\";\n\t\tthis.errors = errors;\n\t}\n};\nvar Mailbox = class {\n\titemsMap = /* @__PURE__ */ new Map();\n\taddedCallbacks = [];\n\tremovedCallbacks = [];\n\tpaused = false;\n\taddedBuffer = [];\n\tremovedBuffer = [];\n\t_ack = 0;\n\t_latestOrdinal = 0;\n\tinit(ackOrdinal) {\n\t\tthis._ack = this._latestOrdinal = ackOrdinal;\n\t}\n\tadvanceOrdinal(ordinal) {\n\t\tthis._latestOrdinal = Math.max(this._latestOrdinal, ordinal);\n\t}\n\tget items() {\n\t\treturn Array.from(this.itemsMap.values());\n\t}\n\tget ackOrdinal() {\n\t\treturn this._ack;\n\t}\n\tget latestOrdinal() {\n\t\treturn this._latestOrdinal;\n\t}\n\tget(id) {\n\t\treturn this.itemsMap.get(id);\n\t}\n\tadd(...items) {\n\t\tfor (const item of items) {\n\t\t\tthis.itemsMap.set(item.id, item);\n\t\t\tfor (const op of item.operations) this._latestOrdinal = Math.max(this._latestOrdinal, op.context.ordinal);\n\t\t\titem.on((syncOp, _, next) => {\n\t\t\t\tif (next === SyncOperationStatus.Applied) for (const op of syncOp.operations) this._ack = Math.max(this._ack, op.context.ordinal);\n\t\t\t});\n\t\t}\n\t\tif (this.paused) {\n\t\t\tthis.addedBuffer.push(...items);\n\t\t\treturn;\n\t\t}\n\t\tconst callbacks = [...this.addedCallbacks];\n\t\tconst errors = [];\n\t\tfor (const callback of callbacks) try {\n\t\t\tcallback(items);\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\tif (errors.length > 0) throw new MailboxAggregateError(errors);\n\t}\n\tremove(...items) {\n\t\tfor (const item of items) this.itemsMap.delete(item.id);\n\t\tif (this.paused) {\n\t\t\tthis.removedBuffer.push(...items);\n\t\t\treturn;\n\t\t}\n\t\tconst callbacks = [...this.removedCallbacks];\n\t\tconst errors = [];\n\t\tfor (const callback of callbacks) try {\n\t\t\tcallback(items);\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\tif (errors.length > 0) throw new MailboxAggregateError(errors);\n\t}\n\tonAdded(callback) {\n\t\tthis.addedCallbacks.push(callback);\n\t}\n\tonRemoved(callback) {\n\t\tthis.removedCallbacks.push(callback);\n\t}\n\tpause() {\n\t\tthis.paused = true;\n\t}\n\tresume() {\n\t\tthis.paused = false;\n\t\tthis.flush();\n\t}\n\tflush() {\n\t\tif (this.addedBuffer.length > 0) {\n\t\t\tconst items = this.addedBuffer.splice(0);\n\t\t\tconst callbacks = [...this.addedCallbacks];\n\t\t\tconst errors = [];\n\t\t\tfor (const callback of callbacks) try {\n\t\t\t\tcallback(items);\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t\t}\n\t\t\tif (errors.length > 0) throw new MailboxAggregateError(errors);\n\t\t}\n\t\tif (this.removedBuffer.length > 0) {\n\t\t\tconst items = this.removedBuffer.splice(0);\n\t\t\tconst callbacks = [...this.removedCallbacks];\n\t\t\tconst errors = [];\n\t\t\tfor (const callback of callbacks) try {\n\t\t\t\tcallback(items);\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t\t}\n\t\t\tif (errors.length > 0) throw new MailboxAggregateError(errors);\n\t\t}\n\t}\n\tisPaused() {\n\t\treturn this.paused;\n\t}\n};\n//#endregion\n//#region src/sync/buffered-mailbox.ts\nvar BufferedMailbox = class {\n\titemsMap = /* @__PURE__ */ new Map();\n\taddedCallbacks = [];\n\tremovedCallbacks = [];\n\taddedBuffer = [];\n\tremovedBuffer = [];\n\taddedTimer = null;\n\tremovedTimer = null;\n\tmilliseconds;\n\tmaxQueued;\n\tpaused = false;\n\t_ack = 0;\n\t_latestOrdinal = 0;\n\tconstructor(milliseconds, maxQueued) {\n\t\tthis.milliseconds = milliseconds;\n\t\tthis.maxQueued = maxQueued;\n\t}\n\tinit(ackOrdinal) {\n\t\tthis._ack = this._latestOrdinal = ackOrdinal;\n\t}\n\tadvanceOrdinal(ordinal) {\n\t\tthis._latestOrdinal = Math.max(this._latestOrdinal, ordinal);\n\t}\n\tget items() {\n\t\treturn Array.from(this.itemsMap.values());\n\t}\n\tget ackOrdinal() {\n\t\treturn this._ack;\n\t}\n\tget latestOrdinal() {\n\t\treturn this._latestOrdinal;\n\t}\n\tget(id) {\n\t\treturn this.itemsMap.get(id);\n\t}\n\tadd(...items) {\n\t\tfor (const item of items) {\n\t\t\tthis.itemsMap.set(item.id, item);\n\t\t\tfor (const op of item.operations) this._latestOrdinal = Math.max(this._latestOrdinal, op.context.ordinal);\n\t\t\titem.on((syncOp, _, next) => {\n\t\t\t\tif (next === SyncOperationStatus.Applied) for (const op of syncOp.operations) this._ack = Math.max(this._ack, op.context.ordinal);\n\t\t\t});\n\t\t}\n\t\tthis.addedBuffer.push(...items);\n\t\tif (this.paused) return;\n\t\tif (this.addedBuffer.length >= this.maxQueued) this.flushAdded();\n\t\telse this.scheduleAddedFlush();\n\t}\n\tremove(...items) {\n\t\tfor (const item of items) this.itemsMap.delete(item.id);\n\t\tthis.removedBuffer.push(...items);\n\t\tif (this.paused) return;\n\t\tif (this.removedBuffer.length >= this.maxQueued) this.flushRemoved();\n\t\telse this.scheduleRemovedFlush();\n\t}\n\tonAdded(callback) {\n\t\tthis.addedCallbacks.push(callback);\n\t}\n\tonRemoved(callback) {\n\t\tthis.removedCallbacks.push(callback);\n\t}\n\tpause() {\n\t\tthis.paused = true;\n\t\tif (this.addedTimer !== null) {\n\t\t\tclearTimeout(this.addedTimer);\n\t\t\tthis.addedTimer = null;\n\t\t}\n\t\tif (this.removedTimer !== null) {\n\t\t\tclearTimeout(this.removedTimer);\n\t\t\tthis.removedTimer = null;\n\t\t}\n\t}\n\tresume() {\n\t\tthis.paused = false;\n\t\tif (this.addedBuffer.length > 0) this.scheduleAddedFlush();\n\t\tif (this.removedBuffer.length > 0) this.scheduleRemovedFlush();\n\t}\n\tisPaused() {\n\t\treturn this.paused;\n\t}\n\tflush() {\n\t\tthis.flushAdded();\n\t\tthis.flushRemoved();\n\t}\n\tscheduleAddedFlush() {\n\t\tif (this.addedTimer !== null) clearTimeout(this.addedTimer);\n\t\tthis.addedTimer = setTimeout(() => {\n\t\t\tthis.flushAdded();\n\t\t}, this.milliseconds);\n\t}\n\tscheduleRemovedFlush() {\n\t\tif (this.removedTimer !== null) clearTimeout(this.removedTimer);\n\t\tthis.removedTimer = setTimeout(() => {\n\t\t\tthis.flushRemoved();\n\t\t}, this.milliseconds);\n\t}\n\tflushAdded() {\n\t\tif (this.addedTimer !== null) {\n\t\t\tclearTimeout(this.addedTimer);\n\t\t\tthis.addedTimer = null;\n\t\t}\n\t\tconst items = this.addedBuffer;\n\t\tthis.addedBuffer = [];\n\t\tif (items.length > 0) this.invokeCallbacks(this.addedCallbacks, items);\n\t}\n\tflushRemoved() {\n\t\tif (this.removedTimer !== null) {\n\t\t\tclearTimeout(this.removedTimer);\n\t\t\tthis.removedTimer = null;\n\t\t}\n\t\tconst items = this.removedBuffer;\n\t\tthis.removedBuffer = [];\n\t\tif (items.length > 0) this.invokeCallbacks(this.removedCallbacks, items);\n\t}\n\tinvokeCallbacks(callbacks, items) {\n\t\tconst callbacksCopy = [...callbacks];\n\t\tconst errors = [];\n\t\tfor (const callback of callbacksCopy) try {\n\t\t\tcallback(items);\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\tif (errors.length > 0) throw new MailboxAggregateError(errors);\n\t}\n};\n//#endregion\n//#region src/sync/errors.ts\nvar GraphQLRequestError = class extends Error {\n\tstatusCode;\n\tcategory;\n\tconstructor(message, category, statusCode) {\n\t\tsuper(message);\n\t\tthis.name = \"GraphQLRequestError\";\n\t\tthis.category = category;\n\t\tthis.statusCode = statusCode;\n\t}\n};\nvar PollingChannelError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"PollingChannelError\";\n\t}\n};\nvar ChannelError = class extends Error {\n\tsource;\n\terror;\n\tconstructor(source, error) {\n\t\tsuper(`ChannelError[${source}]: ${error.message}`);\n\t\tthis.name = \"ChannelError\";\n\t\tthis.source = source;\n\t\tthis.error = error;\n\t}\n};\n//#endregion\n//#region src/sync/sync-operation.ts\nvar SyncOperationAggregateError = class extends Error {\n\terrors;\n\tconstructor(errors) {\n\t\tconst messages = errors.map((e) => e.message).join(\"; \");\n\t\tsuper(`SyncOperation callback failed with ${errors.length} error(s): ${messages}`);\n\t\tthis.name = \"SyncOperationAggregateError\";\n\t\tthis.errors = errors;\n\t}\n};\nvar SyncOperation = class {\n\tid;\n\tjobId;\n\tjobDependencies;\n\tremoteName;\n\tdocumentId;\n\tscopes;\n\tbranch;\n\toperations;\n\tstatus;\n\terror;\n\tdeliveredCount = 0;\n\temittedCount = 0;\n\tcallbacks = [];\n\tconstructor(id, jobId, jobDependencies, remoteName, documentId, scopes, branch, operations) {\n\t\tthis.id = id;\n\t\tthis.jobId = jobId;\n\t\tthis.jobDependencies = jobDependencies;\n\t\tthis.remoteName = remoteName;\n\t\tthis.documentId = documentId;\n\t\tthis.scopes = scopes;\n\t\tthis.branch = branch;\n\t\tthis.operations = operations;\n\t\tthis.status = SyncOperationStatus.Unknown;\n\t}\n\ton(callback) {\n\t\tthis.callbacks.push(callback);\n\t}\n\tstarted() {\n\t\tthis.transition(SyncOperationStatus.TransportPending);\n\t}\n\ttransported() {\n\t\tthis.transition(SyncOperationStatus.ExecutionPending);\n\t}\n\texecuted() {\n\t\tthis.transition(SyncOperationStatus.Applied);\n\t}\n\tfailed(error) {\n\t\tthis.error = error;\n\t\tthis.transition(SyncOperationStatus.Error);\n\t}\n\ttransition(next) {\n\t\tconst prev = this.status;\n\t\tif (next <= prev) return;\n\t\tthis.status = next;\n\t\tconst errors = [];\n\t\tfor (const callback of this.callbacks) try {\n\t\t\tcallback(this, prev, next);\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\tif (errors.length > 0) throw new SyncOperationAggregateError(errors);\n\t}\n};\n//#endregion\n//#region src/sync/utils.ts\n/**\n* Trims a mailbox using the jobIds from a batch.\n*/\nfunction trimMailboxFromBatch(mailbox, batch) {\n\tconst toRemove = [];\n\tfor (const syncOp of batch.entries) for (const item of mailbox.items) if (syncOp.event.jobId === item.jobId) {\n\t\ttoRemove.push(item);\n\t\tbreak;\n\t}\n\tif (toRemove.length > 0) {\n\t\tfor (const syncOp of toRemove) syncOp.executed();\n\t\tmailbox.remove(...toRemove);\n\t}\n}\n/**\n* Trims a mailbox using the ack ordinal.\n*/\nfunction trimMailboxFromAckOrdinal(mailbox, ackOrdinal) {\n\tconst toRemove = [];\n\tfor (const syncOp of mailbox.items) {\n\t\tlet maxOrdinal = 0;\n\t\tfor (const op of syncOp.operations) maxOrdinal = Math.max(maxOrdinal, op.context.ordinal);\n\t\tif (maxOrdinal <= ackOrdinal) toRemove.push(syncOp);\n\t}\n\tif (toRemove.length > 0) {\n\t\tfor (const syncOp of toRemove) syncOp.executed();\n\t\tmailbox.remove(...toRemove);\n\t}\n}\n/**\n* Filters operations based on a remote's filter criteria.\n*\n* @param operations - The operations to filter\n* @param filter - The filter criteria to apply\n* @returns The filtered operations that match the criteria\n*/\nfunction filterOperations(operations, filter) {\n\treturn operations.filter((op) => {\n\t\tif (filter.branch && op.context.branch !== filter.branch) return false;\n\t\tif (filter.documentId.length > 0 && !filter.documentId.includes(op.context.documentId)) return false;\n\t\tif (filter.scope.length > 0 && !filter.scope.includes(op.context.scope)) return false;\n\t\treturn true;\n\t});\n}\n/**\n* Creates an idle channel health status.\n*\n* @returns A new idle channel health object\n*/\nfunction createIdleHealth() {\n\treturn {\n\t\tstate: \"idle\",\n\t\tfailureCount: 0\n\t};\n}\n/**\n* Batches consecutive operations by documentId and scope, preserving ordering.\n*\n* For operations [a1_doc, a1_global, a2_doc, b1_global], this returns:\n* - Batch 1: [a1_doc] for doc-a, document scope\n* - Batch 2: [a1_global] for doc-a, global scope\n* - Batch 3: [a2_doc] for doc-a, document scope\n* - Batch 4: [b1_global] for doc-b, global scope\n*\n* This ensures operations are grouped for efficient processing while maintaining\n* causality across documents and scopes.\n*/\nfunction batchOperationsByDocument(operations) {\n\tconst batches = [];\n\tlet currentDocId = null;\n\tlet currentScope = null;\n\tlet currentBatch = [];\n\tconst flushBatch = () => {\n\t\tif (currentBatch.length === 0 || currentDocId === null || currentScope === null) return;\n\t\tbatches.push({\n\t\t\tdocumentId: currentDocId,\n\t\t\tbranch: currentBatch[0].context.branch,\n\t\t\tscope: currentScope,\n\t\t\toperations: currentBatch\n\t\t});\n\t\tcurrentBatch = [];\n\t};\n\tfor (const op of operations) {\n\t\tconst docId = op.context.documentId;\n\t\tconst scope = op.context.scope;\n\t\tif (docId !== currentDocId || scope !== currentScope) {\n\t\t\tflushBatch();\n\t\t\tcurrentDocId = docId;\n\t\t\tcurrentScope = scope;\n\t\t}\n\t\tcurrentBatch.push(op);\n\t}\n\tflushBatch();\n\treturn batches;\n}\n/**\n* Splits a sorted page of operations into a safe-to-emit prefix and a\n* deferred tail containing the trailing run that shares the same\n* (documentId, branch, scope, timestampUtcMs) as the last operation.\n*\n* The page is assumed to be sorted by (documentId, scope, ordinal), so a\n* same-(docId, scope, ts) run is contiguous and lives at the end of any\n* page that contains its last member. Holding that tail back lets callers\n* prepend it to the next page so a single producer-side execute() call\n* never gets split across two outbound envelopes.\n*/\nfunction splitTrailingSameTimestampRun(operations) {\n\tif (operations.length === 0) return {\n\t\temit: [],\n\t\tcarry: []\n\t};\n\tconst last = operations[operations.length - 1];\n\tconst lastDocId = last.context.documentId;\n\tconst lastBranch = last.context.branch;\n\tconst lastScope = last.context.scope;\n\tconst lastTs = last.operation.timestampUtcMs;\n\tlet carryStart = operations.length;\n\tfor (let i = operations.length - 1; i >= 0; i--) {\n\t\tconst op = operations[i];\n\t\tif (op.context.documentId === lastDocId && op.context.branch === lastBranch && op.context.scope === lastScope && op.operation.timestampUtcMs === lastTs) carryStart = i;\n\t\telse break;\n\t}\n\treturn {\n\t\temit: operations.slice(0, carryStart),\n\t\tcarry: operations.slice(carryStart)\n\t};\n}\nfunction toOperationWithContext(entry) {\n\treturn {\n\t\toperation: {\n\t\t\tid: entry.id,\n\t\t\tindex: entry.index,\n\t\t\tskip: entry.skip,\n\t\t\thash: entry.hash,\n\t\t\ttimestampUtcMs: entry.timestampUtcMs,\n\t\t\taction: entry.action\n\t\t},\n\t\tcontext: {\n\t\t\tdocumentId: entry.documentId,\n\t\t\tdocumentType: entry.documentType,\n\t\t\tscope: entry.scope,\n\t\t\tbranch: entry.branch,\n\t\t\tordinal: entry.ordinal ?? 0\n\t\t}\n\t};\n}\n/**\n* Merges SyncOperations that share the same (documentId, scope, branch) into\n* a single SyncOperation per group. Within each group, operations are sorted\n* by context.ordinal. The merged SyncOperation keeps the first group member's\n* jobId; all other jobIds are remapped so external dependencies still resolve.\n*/\nfunction consolidateSyncOperations(syncOps) {\n\tif (syncOps.length <= 1) return syncOps;\n\tconst groups = /* @__PURE__ */ new Map();\n\tconst jobIdRemap = /* @__PURE__ */ new Map();\n\tconst insertionOrder = [];\n\tfor (const syncOp of syncOps) {\n\t\tconst key = `${syncOp.documentId}|${syncOp.scopes.slice().sort().join(\",\")}|${syncOp.branch}`;\n\t\tconst existing = groups.get(key);\n\t\tif (existing) {\n\t\t\texisting.ops.push(syncOp);\n\t\t\tif (syncOp.jobId && syncOp.jobId !== existing.canonicalJobId) jobIdRemap.set(syncOp.jobId, existing.canonicalJobId);\n\t\t} else {\n\t\t\tgroups.set(key, {\n\t\t\t\tops: [syncOp],\n\t\t\t\tcanonicalJobId: syncOp.jobId\n\t\t\t});\n\t\t\tinsertionOrder.push(key);\n\t\t}\n\t}\n\tconst result = [];\n\tfor (const key of insertionOrder) {\n\t\tconst group = groups.get(key);\n\t\tconst allOperations = group.ops.flatMap((op) => op.operations).sort((a, b) => a.context.ordinal - b.context.ordinal);\n\t\tconst allDeps = /* @__PURE__ */ new Set();\n\t\tfor (const op of group.ops) for (const dep of op.jobDependencies) allDeps.add(dep);\n\t\tallDeps.delete(group.canonicalJobId);\n\t\tfor (const op of group.ops) allDeps.delete(op.jobId);\n\t\tconst remappedDeps = [];\n\t\tfor (const dep of allDeps) {\n\t\t\tconst mapped = jobIdRemap.get(dep) ?? dep;\n\t\t\tif (!remappedDeps.includes(mapped) && mapped !== group.canonicalJobId) remappedDeps.push(mapped);\n\t\t}\n\t\tconst first = group.ops[0];\n\t\tconst merged = new SyncOperation(first.id, first.jobId, remappedDeps, first.remoteName, first.documentId, first.scopes, first.branch, allOperations);\n\t\tif (first.status > SyncOperationStatus.TransportPending) if (first.status >= SyncOperationStatus.Error) merged.executed();\n\t\telse if (first.status >= SyncOperationStatus.Applied) merged.transported();\n\t\telse merged.started();\n\t\tresult.push(merged);\n\t}\n\treturn result;\n}\n/**\n* Chunks sync operations into batches that respect dependency-connected\n* components. SyncOps linked by jobDependencies are kept in the same chunk.\n* If a connected component exceeds maxSize, it is split by topological order.\n*/\nfunction chunkSyncOperations(items, maxSize) {\n\tif (items.length === 0) return [];\n\tif (items.length <= maxSize) return [items];\n\tconst parent = items.map((_, i) => i);\n\tconst rank = new Array(items.length).fill(0);\n\tfunction find(x) {\n\t\twhile (parent[x] !== x) {\n\t\t\tparent[x] = parent[parent[x]];\n\t\t\tx = parent[x];\n\t\t}\n\t\treturn x;\n\t}\n\tfunction union(a, b) {\n\t\tconst ra = find(a);\n\t\tconst rb = find(b);\n\t\tif (ra === rb) return;\n\t\tif (rank[ra] < rank[rb]) parent[ra] = rb;\n\t\telse if (rank[ra] > rank[rb]) parent[rb] = ra;\n\t\telse {\n\t\t\tparent[rb] = ra;\n\t\t\trank[ra]++;\n\t\t}\n\t}\n\tconst jobIdToIndex = /* @__PURE__ */ new Map();\n\tfor (let i = 0; i < items.length; i++) jobIdToIndex.set(items[i].syncOp.jobId, i);\n\tfor (let i = 0; i < items.length; i++) for (const dep of items[i].syncOp.jobDependencies) {\n\t\tconst depIdx = jobIdToIndex.get(dep);\n\t\tif (depIdx !== void 0) union(i, depIdx);\n\t}\n\tconst componentMap = /* @__PURE__ */ new Map();\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst root = find(i);\n\t\tlet component = componentMap.get(root);\n\t\tif (!component) {\n\t\t\tcomponent = [];\n\t\t\tcomponentMap.set(root, component);\n\t\t}\n\t\tcomponent.push(items[i]);\n\t}\n\tconst components = [...componentMap.values()];\n\tconst chunks = [];\n\tlet currentChunk = [];\n\tfor (const component of components) {\n\t\tif (component.length > maxSize) {\n\t\t\tif (currentChunk.length > 0) {\n\t\t\t\tchunks.push(currentChunk);\n\t\t\t\tcurrentChunk = [];\n\t\t\t}\n\t\t\tfor (const subChunk of splitComponent(component, maxSize)) chunks.push(subChunk);\n\t\t\tcontinue;\n\t\t}\n\t\tif (currentChunk.length + component.length > maxSize) {\n\t\t\tif (currentChunk.length > 0) chunks.push(currentChunk);\n\t\t\tcurrentChunk = [...component];\n\t\t} else currentChunk.push(...component);\n\t}\n\tif (currentChunk.length > 0) chunks.push(currentChunk);\n\treturn chunks;\n}\n/**\n* Splits an oversized connected component into chunks by topological order.\n* Cross-chunk dependency references are handled by the caller's dep filter.\n*/\nfunction splitComponent(items, maxSize) {\n\tconst jobIdToItem = /* @__PURE__ */ new Map();\n\tconst jobIds = /* @__PURE__ */ new Set();\n\tfor (const item of items) {\n\t\tjobIdToItem.set(item.syncOp.jobId, item);\n\t\tjobIds.add(item.syncOp.jobId);\n\t}\n\tconst inDegree = /* @__PURE__ */ new Map();\n\tconst adjacency = /* @__PURE__ */ new Map();\n\tfor (const item of items) {\n\t\tconst key = item.syncOp.jobId;\n\t\tif (!inDegree.has(key)) inDegree.set(key, 0);\n\t\tif (!adjacency.has(key)) adjacency.set(key, []);\n\t\tfor (const dep of item.syncOp.jobDependencies) if (jobIds.has(dep)) {\n\t\t\tinDegree.set(key, (inDegree.get(key) ?? 0) + 1);\n\t\t\tif (!adjacency.has(dep)) adjacency.set(dep, []);\n\t\t\tadjacency.get(dep).push(key);\n\t\t}\n\t}\n\tconst queue = [];\n\tfor (const [key, degree] of inDegree) if (degree === 0) queue.push(key);\n\tconst sorted = [];\n\twhile (queue.length > 0) {\n\t\tconst key = queue.shift();\n\t\tsorted.push(jobIdToItem.get(key));\n\t\tfor (const neighbor of adjacency.get(key) ?? []) {\n\t\t\tconst newDegree = (inDegree.get(neighbor) ?? 1) - 1;\n\t\t\tinDegree.set(neighbor, newDegree);\n\t\t\tif (newDegree === 0) queue.push(neighbor);\n\t\t}\n\t}\n\tif (sorted.length < items.length) {\n\t\tconst sortedIds = new Set(sorted.map((item) => item.syncOp.jobId));\n\t\tfor (const item of items) if (!sortedIds.has(item.syncOp.jobId)) sorted.push(item);\n\t}\n\tconst chunks = [];\n\tfor (let i = 0; i < sorted.length; i += maxSize) chunks.push(sorted.slice(i, i + maxSize));\n\treturn chunks;\n}\n//#endregion\n//#region src/sync/channels/interval-poll-timer.ts\nconst DEFAULT_CONFIG = {\n\tintervalMs: 2e3,\n\tmaxQueueDepth: 100,\n\tbackpressureCheckIntervalMs: 500,\n\tretryBaseDelayMs: 1e3,\n\tretryMaxDelayMs: 3e5,\n\tstartPaused: false\n};\nfunction calculateBackoffDelay(consecutiveFailures, retryBaseDelayMs, retryMaxDelayMs, random) {\n\tconst backoff = Math.min(retryMaxDelayMs, retryBaseDelayMs * Math.pow(2, consecutiveFailures - 1));\n\treturn backoff / 2 + random * (backoff / 2);\n}\n/**\n* Default poll timer using setTimeout.\n* Waits for delegate completion before scheduling next tick.\n* Checks queue depth and defers polling when backpressure is detected.\n*/\nvar IntervalPollTimer = class {\n\tdelegate;\n\ttimer;\n\trunning;\n\tpaused;\n\tconsecutiveFailures;\n\tqueue;\n\tconfig;\n\tconstructor(queue, config = {}) {\n\t\tthis.queue = queue;\n\t\tthis.config = {\n\t\t\t...DEFAULT_CONFIG,\n\t\t\t...config\n\t\t};\n\t\tthis.running = false;\n\t\tthis.paused = this.config.startPaused;\n\t\tthis.consecutiveFailures = 0;\n\t}\n\tsetDelegate(delegate) {\n\t\tthis.delegate = delegate;\n\t}\n\tstart() {\n\t\tthis.running = true;\n\t\tthis.consecutiveFailures = 0;\n\t\tif (!this.paused) this.tick();\n\t}\n\tstop() {\n\t\tthis.running = false;\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = void 0;\n\t\t}\n\t}\n\ttick() {\n\t\tif (!this.delegate || !this.running) return;\n\t\tconst delegate = this.delegate;\n\t\tthis.queue.totalSize().then((size) => {\n\t\t\tif (!this.running) return;\n\t\t\tif (size > this.config.maxQueueDepth) this.scheduleBackpressureRecheck();\n\t\t\telse delegate().then(() => {\n\t\t\t\tthis.consecutiveFailures = 0;\n\t\t\t\tthis.scheduleNext();\n\t\t\t}).catch(() => {\n\t\t\t\tthis.consecutiveFailures++;\n\t\t\t\tthis.scheduleRetry();\n\t\t\t});\n\t\t}).catch(() => {\n\t\t\tthis.scheduleNext();\n\t\t});\n\t}\n\tscheduleNext() {\n\t\tif (!this.running || this.paused) return;\n\t\tthis.timer = setTimeout(() => this.tick(), this.config.intervalMs);\n\t}\n\tscheduleRetry() {\n\t\tif (!this.running || this.paused) return;\n\t\tconst delay = calculateBackoffDelay(this.consecutiveFailures, this.config.retryBaseDelayMs, this.config.retryMaxDelayMs, Math.random());\n\t\tthis.timer = setTimeout(() => this.tick(), delay);\n\t}\n\tscheduleBackpressureRecheck() {\n\t\tif (!this.running || this.paused) return;\n\t\tthis.timer = setTimeout(() => this.tick(), this.config.backpressureCheckIntervalMs);\n\t}\n\tpause() {\n\t\tthis.paused = true;\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = void 0;\n\t\t}\n\t}\n\tresume() {\n\t\tthis.paused = false;\n\t\tif (this.running) this.scheduleNext();\n\t}\n\ttriggerNow() {\n\t\tif (this.running && this.delegate) this.tick();\n\t}\n\tisPaused() {\n\t\treturn this.paused;\n\t}\n\tisRunning() {\n\t\treturn this.running;\n\t}\n\tgetIntervalMs() {\n\t\treturn this.config.intervalMs;\n\t}\n\tsetIntervalMs(ms) {\n\t\tthis.config.intervalMs = ms;\n\t}\n};\n//#endregion\n//#region src/sync/channels/utils.ts\nlet syncOpCounter = 0;\n/**\n* Serializes an action for GraphQL transport, converting signature tuples to strings.\n*\n* Only the fields declared by the GraphQL `ActionInput` type are forwarded. This\n* guards against stale runtime-only fields (e.g. a legacy `attachments` array on\n* operations persisted before the attachment-system removal) leaking into the\n* mutation variables, where the tightened schema would reject them.\n*/\nfunction serializeAction(action) {\n\tconst base = {\n\t\tid: action.id,\n\t\ttype: action.type,\n\t\ttimestampUtcMs: action.timestampUtcMs,\n\t\tinput: action.input,\n\t\tscope: action.scope\n\t};\n\tconst signer = action.context?.signer;\n\tif (!signer?.signatures) return action.context ? {\n\t\t...base,\n\t\tcontext: action.context\n\t} : base;\n\treturn {\n\t\t...base,\n\t\tcontext: {\n\t\t\t...action.context,\n\t\t\tsigner: {\n\t\t\t\t...signer,\n\t\t\t\tsignatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(\", \") : sig)\n\t\t\t}\n\t\t}\n\t};\n}\n/**\n* Serializes a SyncEnvelope for GraphQL transport.\n*\n* Signatures are serialized as comma-separated strings since GraphQL schema\n* defines them as [String!]!. The resultingState context field is stripped\n* since it is not defined in OperationContextInput.\n*/\nfunction serializeEnvelope(envelope) {\n\treturn {\n\t\ttype: envelope.type.toUpperCase(),\n\t\tchannelMeta: envelope.channelMeta,\n\t\toperations: envelope.operations?.map((opWithContext) => ({\n\t\t\toperation: {\n\t\t\t\tindex: opWithContext.operation.index,\n\t\t\t\ttimestampUtcMs: opWithContext.operation.timestampUtcMs,\n\t\t\t\thash: opWithContext.operation.hash,\n\t\t\t\tskip: opWithContext.operation.skip,\n\t\t\t\terror: opWithContext.operation.error,\n\t\t\t\tid: opWithContext.operation.id,\n\t\t\t\taction: serializeAction(opWithContext.operation.action)\n\t\t\t},\n\t\t\tcontext: {\n\t\t\t\tdocumentId: opWithContext.context.documentId,\n\t\t\t\tdocumentType: opWithContext.context.documentType,\n\t\t\t\tscope: opWithContext.context.scope,\n\t\t\t\tbranch: opWithContext.context.branch,\n\t\t\t\tordinal: opWithContext.context.ordinal\n\t\t\t}\n\t\t})),\n\t\tcursor: envelope.cursor,\n\t\tkey: envelope.key,\n\t\tdependsOn: envelope.dependsOn\n\t};\n}\n/**\n* Deserializes a signature from a comma-separated string back to a tuple.\n*\n* GraphQL serializes Signature tuples as comma-separated strings for transport.\n* This function converts them back to the expected [string, string, string, string, string] format.\n*/\nfunction deserializeSignature(sig) {\n\tif (Array.isArray(sig)) return sig;\n\treturn sig.split(\", \");\n}\n/**\n* Deserializes signatures in an operation's signer context from strings back to tuples.\n*\n* When operations are transported via GraphQL, signatures are serialized as comma-separated\n* strings. This function restores them to the Signature tuple format required for verification.\n*/\nfunction deserializeOperationSignatures(opWithContext) {\n\tconst signer = opWithContext.operation.action.context?.signer;\n\tif (!signer?.signatures || signer.signatures.length === 0) return opWithContext;\n\tconst deserializedSignatures = signer.signatures.map(deserializeSignature);\n\tconst deserializedOperation = {\n\t\t...opWithContext.operation,\n\t\taction: {\n\t\t\t...opWithContext.operation.action,\n\t\t\tcontext: {\n\t\t\t\t...opWithContext.operation.action.context,\n\t\t\t\tsigner: {\n\t\t\t\t\t...signer,\n\t\t\t\t\tsignatures: deserializedSignatures\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\treturn {\n\t\t...opWithContext,\n\t\toperation: deserializedOperation\n\t};\n}\n/**\n* Converts a SyncEnvelope containing operations into multiple SyncOperations.\n*\n* This function batches operations by documentId, preserving cross-document ordering.\n* For operations [a1, a2, a3, b1, b2, a4], it returns:\n* - SyncOperation 1: [a1, a2, a3] for doc-a\n* - SyncOperation 2: [b1, b2] for doc-b\n* - SyncOperation 3: [a4] for doc-a\n*\n* This ensures operations are grouped for efficient processing while maintaining\n* causality across documents.\n*/\nfunction envelopesToSyncOperations(envelope, remoteName) {\n\tif (!envelope.operations || envelope.operations.length === 0) return [];\n\treturn batchOperationsByDocument(envelope.operations.map(deserializeOperationSignatures)).map((batch) => {\n\t\treturn new SyncOperation(`syncop-${envelope.channelMeta.id}-${Date.now()}-${syncOpCounter++}`, envelope.key ?? \"\", (envelope.dependsOn ?? []).filter(Boolean), remoteName, batch.documentId, [batch.scope], batch.branch, batch.operations);\n\t});\n}\nconst getLatestAppliedOrdinal = (syncOps) => {\n\tlet maxOrdinal = 0;\n\tfor (const syncOp of syncOps) if (syncOp.status === SyncOperationStatus.Applied) for (const op of syncOp.operations) maxOrdinal = Math.max(maxOrdinal, op.context.ordinal);\n\treturn maxOrdinal;\n};\n//#endregion\n//#region src/sync/channels/gql-req-channel.ts\n/**\n* GraphQL-based synchronization channel for network communication between reactors.\n*/\nvar GqlRequestChannel = class {\n\tinbox;\n\toutbox;\n\tdeadLetter;\n\tconfig;\n\tbufferedOutbox;\n\tchannelId;\n\tremoteName;\n\tcursorStorage;\n\toperationIndex;\n\tpollTimer;\n\tabortController = new AbortController();\n\tisShutdown;\n\tfailureCount;\n\tlastSuccessUtcMs;\n\tlastFailureUtcMs;\n\tlastPersistedInboxOrdinal = 0;\n\tlastPersistedOutboxOrdinal = 0;\n\tpushFailureCount = 0;\n\tpushRetryTimer = null;\n\tpushBlocked = false;\n\tisPushing = false;\n\tpendingDrain = false;\n\treceivingPages = false;\n\tconnectionState = \"connecting\";\n\tconnectionStateCallbacks = /* @__PURE__ */ new Set();\n\tconstructor(logger, channelId, remoteName, cursorStorage, config, operationIndex, pollTimer) {\n\t\tthis.logger = logger;\n\t\tthis.channelId = channelId;\n\t\tthis.remoteName = remoteName;\n\t\tthis.cursorStorage = cursorStorage;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.pollTimer = pollTimer;\n\t\tthis.config = {\n\t\t\turl: config.url,\n\t\t\tjwtHandler: config.jwtHandler,\n\t\t\tfetchFn: config.fetchFn,\n\t\t\tcollectionId: config.collectionId,\n\t\t\tfilter: config.filter,\n\t\t\tretryBaseDelayMs: config.retryBaseDelayMs,\n\t\t\tretryMaxDelayMs: config.retryMaxDelayMs\n\t\t};\n\t\tthis.isShutdown = false;\n\t\tthis.failureCount = 0;\n\t\tthis.inbox = new Mailbox();\n\t\tthis.bufferedOutbox = new BufferedMailbox(500, 25);\n\t\tthis.outbox = this.bufferedOutbox;\n\t\tthis.deadLetter = new Mailbox();\n\t\tthis.deadLetter.onAdded((syncOps) => {\n\t\t\tfor (const syncOp of syncOps) this.logger.warn(\"Dead letter added for document @DocumentId on channel @ChannelId\", syncOp.documentId, this.channelId);\n\t\t});\n\t\tthis.outbox.onAdded((syncOps) => {\n\t\t\tif (this.isShutdown) return;\n\t\t\tif (this.isPushing) {\n\t\t\t\tthis.pendingDrain = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.pushBlocked) return;\n\t\t\tif (this.receivingPages) {\n\t\t\t\tthis.pendingDrain = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.attemptPush(syncOps);\n\t\t});\n\t\tthis.outbox.onRemoved((syncOps) => {\n\t\t\tconst maxOrdinal = getLatestAppliedOrdinal(syncOps);\n\t\t\tif (maxOrdinal > this.lastPersistedOutboxOrdinal) {\n\t\t\t\tthis.lastPersistedOutboxOrdinal = maxOrdinal;\n\t\t\t\tthis.cursorStorage.upsert({\n\t\t\t\t\tremoteName: this.remoteName,\n\t\t\t\t\tcursorType: \"outbox\",\n\t\t\t\t\tcursorOrdinal: maxOrdinal,\n\t\t\t\t\tlastSyncedAtUtcMs: Date.now()\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tthis.logger.error(\"Failed to update outbox cursor for @ChannelId! This means that future application runs may resend duplicate operations. This is recoverable (with deduplication protection), but not-optimal: @Error\", this.channelId, error);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tthis.inbox.onRemoved((syncOps) => {\n\t\t\tconst maxOrdinal = getLatestAppliedOrdinal(syncOps);\n\t\t\tif (maxOrdinal > this.lastPersistedInboxOrdinal) {\n\t\t\t\tthis.lastPersistedInboxOrdinal = maxOrdinal;\n\t\t\t\tthis.cursorStorage.upsert({\n\t\t\t\t\tremoteName: this.remoteName,\n\t\t\t\t\tcursorType: \"inbox\",\n\t\t\t\t\tcursorOrdinal: maxOrdinal,\n\t\t\t\t\tlastSyncedAtUtcMs: Date.now()\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tthis.logger.error(\"Failed to update inbox cursor for @ChannelId! This is unlikely to cause a problem, but not-optimal: @Error\", this.channelId, error);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Shuts down the channel and prevents further operations.\n\t*/\n\tshutdown() {\n\t\tthis.abortController.abort();\n\t\tthis.bufferedOutbox.flush();\n\t\tthis.isShutdown = true;\n\t\tthis.pollTimer.stop();\n\t\tif (this.pushRetryTimer) {\n\t\t\tclearTimeout(this.pushRetryTimer);\n\t\t\tthis.pushRetryTimer = null;\n\t\t}\n\t\tthis.transitionConnectionState(\"disconnected\");\n\t\treturn Promise.resolve();\n\t}\n\tgetConnectionState() {\n\t\treturn {\n\t\t\tstate: this.connectionState,\n\t\t\tfailureCount: this.failureCount,\n\t\t\tlastSuccessUtcMs: this.lastSuccessUtcMs ?? 0,\n\t\t\tlastFailureUtcMs: this.lastFailureUtcMs ?? 0,\n\t\t\tpushBlocked: this.pushBlocked,\n\t\t\tpushFailureCount: this.pushFailureCount,\n\t\t\treceivingPages: this.receivingPages\n\t\t};\n\t}\n\tonConnectionStateChange(callback) {\n\t\tthis.connectionStateCallbacks.add(callback);\n\t\treturn () => {\n\t\t\tthis.connectionStateCallbacks.delete(callback);\n\t\t};\n\t}\n\ttriggerPull() {\n\t\tif (this.isShutdown) return;\n\t\tthis.pollTimer.triggerNow();\n\t}\n\t/**\n\t* Initializes the channel by registering it on the remote server and starting polling.\n\t*/\n\tasync init() {\n\t\tconst { ackOrdinal } = await this.touchRemoteChannel();\n\t\tconst cursors = await this.cursorStorage.list(this.remoteName);\n\t\tconst inboxOrdinal = cursors.find((c) => c.cursorType === \"inbox\")?.cursorOrdinal ?? 0;\n\t\tconst outboxOrdinal = cursors.find((c) => c.cursorType === \"outbox\")?.cursorOrdinal ?? 0;\n\t\tthis.inbox.init(inboxOrdinal);\n\t\tthis.outbox.init(outboxOrdinal);\n\t\tthis.lastPersistedInboxOrdinal = inboxOrdinal;\n\t\tthis.lastPersistedOutboxOrdinal = outboxOrdinal;\n\t\tif (ackOrdinal > 0) trimMailboxFromAckOrdinal(this.outbox, ackOrdinal);\n\t\tthis.pollTimer.setDelegate(() => this.poll());\n\t\tthis.pollTimer.start();\n\t\tthis.transitionConnectionState(\"connected\");\n\t}\n\ttransitionConnectionState(next) {\n\t\tif (this.connectionState === next) return;\n\t\tthis.connectionState = next;\n\t\tconst snapshot = this.getConnectionState();\n\t\tfor (const callback of this.connectionStateCallbacks) try {\n\t\t\tcallback(snapshot);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Connection state change callback error: @Error\", error);\n\t\t}\n\t}\n\t/**\n\t* Polls the remote for new sync envelopes.\n\t*/\n\tasync poll() {\n\t\tif (this.isShutdown) return;\n\t\tlet response;\n\t\ttry {\n\t\t\tresponse = await this.pollSyncEnvelopes(this.inbox.ackOrdinal, this.inbox.latestOrdinal);\n\t\t} catch (error) {\n\t\t\tif (!this.handlePollError(error)) throw error;\n\t\t\treturn;\n\t\t}\n\t\tconst { envelopes, ackOrdinal, deadLetters, hasMore } = response;\n\t\tif (ackOrdinal > 0) trimMailboxFromAckOrdinal(this.outbox, ackOrdinal);\n\t\tconst allSyncOps = [];\n\t\tfor (const envelope of envelopes) if (envelope.type.toLowerCase() === \"operations\" && envelope.operations) {\n\t\t\tconst syncOps = envelopesToSyncOperations(envelope, this.remoteName);\n\t\t\tfor (const syncOp of syncOps) syncOp.transported();\n\t\t\tallSyncOps.push(...syncOps);\n\t\t}\n\t\tconst consolidated = allSyncOps.length > 1 ? consolidateSyncOperations(allSyncOps) : allSyncOps;\n\t\tif (consolidated.length > 0) this.inbox.add(...consolidated);\n\t\tif (deadLetters.length > 0) this.handleRemoteDeadLetters(deadLetters);\n\t\tif (hasMore) this.receivingPages = true;\n\t\telse if (this.receivingPages) {\n\t\t\tthis.receivingPages = false;\n\t\t\tthis.drainOutbox();\n\t\t}\n\t\tthis.lastSuccessUtcMs = Date.now();\n\t\tthis.failureCount = 0;\n\t\tthis.transitionConnectionState(\"connected\");\n\t}\n\t/**\n\t* Handles dead letters reported by the remote server.\n\t* Creates local dead letter SyncOperations so the channel quiesces.\n\t*/\n\thandleRemoteDeadLetters(deadLetters) {\n\t\tfor (const dl of deadLetters) this.logger.error(\"Remote dead letter on @ChannelId: document @DocumentId failed with: @Error\", this.channelId, dl.documentId, dl.error);\n\t\tconst syncOps = [];\n\t\tfor (const dl of deadLetters) {\n\t\t\tconst syncOp = new SyncOperation(crypto.randomUUID(), dl.jobId, [], this.remoteName, dl.documentId, dl.scopes, dl.branch, []);\n\t\t\tsyncOp.failed(new ChannelError(ChannelErrorSource.Outbox, new Error(dl.error)));\n\t\t\tsyncOps.push(syncOp);\n\t\t}\n\t\tthis.deadLetter.add(...syncOps);\n\t}\n\t/**\n\t* Handles polling errors with error classification.\n\t* Returns true if the error was handled (caller should not rethrow).\n\t*/\n\thandlePollError(error) {\n\t\tif (this.isShutdown) return true;\n\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\tif (err.message.includes(\"Channel not found\")) {\n\t\t\tthis.transitionConnectionState(\"reconnecting\");\n\t\t\tthis.recoverFromChannelNotFound();\n\t\t\treturn true;\n\t\t}\n\t\tconst classification = this.classifyError(err);\n\t\tthis.failureCount++;\n\t\tthis.lastFailureUtcMs = Date.now();\n\t\tconst channelError = new ChannelError(ChannelErrorSource.Inbox, err);\n\t\tthis.logger.error(\"GqlChannel poll error (@FailureCount, @Classification): @Error\", this.failureCount, classification, channelError);\n\t\tif (classification === \"unrecoverable\") {\n\t\t\tthis.pollTimer.stop();\n\t\t\tthis.transitionConnectionState(\"error\");\n\t\t\treturn true;\n\t\t}\n\t\tthis.transitionConnectionState(\"error\");\n\t\treturn false;\n\t}\n\t/**\n\t* Recovers from a \"Channel not found\" error by re-registering and restarting polling.\n\t* Self-retries with backoff instead of restarting the poll timer on failure.\n\t*/\n\trecoverFromChannelNotFound() {\n\t\tthis.logger.info(\"GqlChannel @ChannelId not found on remote, re-registering...\", this.channelId);\n\t\tthis.pollTimer.stop();\n\t\tconst attemptRecovery = (attempt) => {\n\t\t\tif (this.isShutdown) return;\n\t\t\tthis.touchRemoteChannel().then(({ ackOrdinal }) => {\n\t\t\t\tthis.logger.info(\"GqlChannel @ChannelId re-registered successfully\", this.channelId);\n\t\t\t\tthis.failureCount = 0;\n\t\t\t\tif (ackOrdinal > 0) trimMailboxFromAckOrdinal(this.outbox, ackOrdinal);\n\t\t\t\tthis.pollTimer.start();\n\t\t\t\tthis.transitionConnectionState(\"connected\");\n\t\t\t}).catch((recoveryError) => {\n\t\t\t\tconst err = recoveryError instanceof Error ? recoveryError : new Error(String(recoveryError));\n\t\t\t\tconst classification = this.classifyError(err);\n\t\t\t\tthis.logger.error(\"GqlChannel @ChannelId recovery attempt @Attempt failed (@Classification): @Error\", this.channelId, attempt, classification, recoveryError);\n\t\t\t\tthis.failureCount++;\n\t\t\t\tthis.lastFailureUtcMs = Date.now();\n\t\t\t\tif (classification === \"unrecoverable\") {\n\t\t\t\t\tthis.transitionConnectionState(\"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.transitionConnectionState(\"reconnecting\");\n\t\t\t\tconst delay = calculateBackoffDelay(attempt, this.config.retryBaseDelayMs, this.config.retryMaxDelayMs, Math.random());\n\t\t\t\tsetTimeout(() => attemptRecovery(attempt + 1), delay);\n\t\t\t});\n\t\t};\n\t\tattemptRecovery(1);\n\t}\n\t/**\n\t* Queries the remote GraphQL endpoint for sync envelopes.\n\t*/\n\tasync pollSyncEnvelopes(ackOrdinal, latestOrdinal) {\n\t\tconst query = `\n query PollSyncEnvelopes($channelId: String!, $outboxAck: Int!, $outboxLatest: Int!) {\n pollSyncEnvelopes(channelId: $channelId, outboxAck: $outboxAck, outboxLatest: $outboxLatest) {\n envelopes {\n type\n channelMeta {\n id\n }\n operations {\n operation {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n context {\n documentId\n documentType\n scope\n branch\n ordinal\n }\n }\n cursor {\n remoteName\n cursorOrdinal\n lastSyncedAtUtcMs\n }\n key\n dependsOn\n }\n ackOrdinal\n deadLetters {\n documentId\n error\n jobId\n branch\n scopes\n operationCount\n }\n hasMore\n }\n }\n `;\n\t\tconst variables = {\n\t\t\tchannelId: this.channelId,\n\t\t\toutboxAck: ackOrdinal,\n\t\t\toutboxLatest: latestOrdinal\n\t\t};\n\t\tconst response = await this.executeGraphQL(query, variables);\n\t\treturn {\n\t\t\tenvelopes: response.pollSyncEnvelopes.envelopes,\n\t\t\tackOrdinal: response.pollSyncEnvelopes.ackOrdinal,\n\t\t\tdeadLetters: response.pollSyncEnvelopes.deadLetters ?? [],\n\t\t\thasMore: response.pollSyncEnvelopes.hasMore\n\t\t};\n\t}\n\t/**\n\t* Registers or updates this channel on the remote server via GraphQL mutation.\n\t* Returns the remote's ack ordinal so the client can trim its outbox.\n\t*/\n\tasync touchRemoteChannel() {\n\t\tlet sinceTimestampUtcMs = \"0\";\n\t\ttry {\n\t\t\tconst result = await this.operationIndex.getLatestTimestampForCollection(this.config.collectionId.key);\n\t\t\tif (result) sinceTimestampUtcMs = result;\n\t\t} catch {}\n\t\tconst mutation = `\n mutation TouchChannel($input: TouchChannelInput!) {\n touchChannel(input: $input) {\n success\n ackOrdinal\n }\n }\n `;\n\t\tconst variables = { input: {\n\t\t\tid: this.channelId,\n\t\t\tname: this.channelId,\n\t\t\tcollectionId: this.config.collectionId.key,\n\t\t\tfilter: {\n\t\t\t\tdocumentId: this.config.filter.documentId,\n\t\t\t\tscope: this.config.filter.scope,\n\t\t\t\tbranch: this.config.filter.branch\n\t\t\t},\n\t\t\tsinceTimestampUtcMs\n\t\t} };\n\t\tconst data = await this.executeGraphQL(mutation, variables);\n\t\tif (!data.touchChannel.success) throw new GraphQLRequestError(\"touchChannel returned success=false\", \"graphql\");\n\t\treturn { ackOrdinal: data.touchChannel.ackOrdinal };\n\t}\n\t/**\n\t* Fire-and-forget push with retry on recoverable errors.\n\t* On success, clears push blocked state. On recoverable error, blocks\n\t* further pushes and schedules a retry. On unrecoverable error, moves\n\t* ops to deadLetter.\n\t*/\n\tattemptPush(syncOps) {\n\t\tthis.isPushing = true;\n\t\tthis.pushSyncOperations(syncOps).then(() => {\n\t\t\tthis.isPushing = false;\n\t\t\tthis.pushBlocked = false;\n\t\t\tthis.pushFailureCount = 0;\n\t\t\tif (this.connectionState === \"reconnecting\" || this.connectionState === \"error\") this.transitionConnectionState(\"connected\");\n\t\t\tthis.drainOutbox();\n\t\t}).catch((error) => {\n\t\t\tthis.isPushing = false;\n\t\t\tthis.pendingDrain = false;\n\t\t\tif (this.isShutdown) return;\n\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\tif (this.classifyError(err) === \"recoverable\") {\n\t\t\t\tthis.pushFailureCount++;\n\t\t\t\tthis.pushBlocked = true;\n\t\t\t\tthis.logger.error(\"GqlChannel push failed (attempt @FailureCount), will retry: @Error\", this.pushFailureCount, err);\n\t\t\t\tthis.transitionConnectionState(\"reconnecting\");\n\t\t\t\tthis.schedulePushRetry();\n\t\t\t} else {\n\t\t\t\tconst channelError = new ChannelError(ChannelErrorSource.Outbox, err);\n\t\t\t\tfor (const syncOp of syncOps) syncOp.failed(channelError);\n\t\t\t\tthis.deadLetter.add(...syncOps);\n\t\t\t\tthis.outbox.remove(...syncOps);\n\t\t\t\tthis.transitionConnectionState(\"error\");\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Schedules a retry of all current outbox items using exponential backoff.\n\t*/\n\tschedulePushRetry() {\n\t\tif (this.pushRetryTimer) return;\n\t\tconst delay = calculateBackoffDelay(this.pushFailureCount, this.config.retryBaseDelayMs, this.config.retryMaxDelayMs, Math.random());\n\t\tthis.pushRetryTimer = setTimeout(() => {\n\t\t\tthis.pushRetryTimer = null;\n\t\t\tif (this.isShutdown) return;\n\t\t\tconst allItems = this.outbox.items;\n\t\t\tif (allItems.length === 0) {\n\t\t\t\tthis.pushBlocked = false;\n\t\t\t\tthis.pushFailureCount = 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.attemptPush([...allItems]);\n\t\t}, delay);\n\t}\n\t/**\n\t* Drains pending outbox items that arrived while a push was in-flight.\n\t* Server-side action.id dedup handles any overlap with the previous push.\n\t*/\n\tdrainOutbox() {\n\t\tif (!this.pendingDrain) return;\n\t\tthis.pendingDrain = false;\n\t\tif (this.isShutdown) return;\n\t\tconst items = this.outbox.items;\n\t\tif (items.length === 0) return;\n\t\tthis.attemptPush([...items]);\n\t}\n\t/**\n\t* Classifies an error as recoverable or unrecoverable based on its type.\n\t* Recoverable errors are transient and worth retrying (network, 5xx, parse).\n\t* Unrecoverable errors will not self-heal (auth, client errors, GraphQL rejections).\n\t*/\n\tclassifyError(error) {\n\t\tif (!(error instanceof GraphQLRequestError)) return \"recoverable\";\n\t\tswitch (error.category) {\n\t\t\tcase \"network\": return \"recoverable\";\n\t\t\tcase \"http\":\n\t\t\t\tif (error.statusCode !== void 0 && error.statusCode >= 500) return \"recoverable\";\n\t\t\t\treturn \"unrecoverable\";\n\t\t\tcase \"parse\": return \"recoverable\";\n\t\t\tcase \"graphql\": return \"unrecoverable\";\n\t\t\tcase \"missing-data\": return \"unrecoverable\";\n\t\t}\n\t}\n\t/**\n\t* Pushes multiple sync operations to the remote via a single GraphQL mutation.\n\t* Creates one SyncEnvelope per SyncOperation with key/dependsOn for batch ordering.\n\t*/\n\tasync pushSyncOperations(syncOps) {\n\t\tfor (const syncOp of syncOps) syncOp.started();\n\t\tconst jobIdToKeys = /* @__PURE__ */ new Map();\n\t\tconst envelopes = [];\n\t\tfor (let i = 0; i < syncOps.length; i++) {\n\t\t\tconst syncOp = syncOps[i];\n\t\t\tconst key = String(i);\n\t\t\tif (syncOp.jobId) {\n\t\t\t\tif (!jobIdToKeys.has(syncOp.jobId)) jobIdToKeys.set(syncOp.jobId, []);\n\t\t\t\tjobIdToKeys.get(syncOp.jobId).push(key);\n\t\t\t}\n\t\t\tconst dependsOn = [];\n\t\t\tfor (const dep of syncOp.jobDependencies) {\n\t\t\t\tconst depKeys = jobIdToKeys.get(dep);\n\t\t\t\tif (depKeys) dependsOn.push(...depKeys);\n\t\t\t}\n\t\t\tthis.logger.debug(\"[PUSH]: @Operations\", syncOp.operations.map((op) => `(${op.context.documentId}, ${op.context.branch}, ${op.context.scope}, ${op.operation.index})`));\n\t\t\tenvelopes.push({\n\t\t\t\ttype: \"operations\",\n\t\t\t\tchannelMeta: { id: this.channelId },\n\t\t\t\toperations: syncOp.operations,\n\t\t\t\tkey,\n\t\t\t\tdependsOn\n\t\t\t});\n\t\t}\n\t\tconst mutation = `\n mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {\n pushSyncEnvelopes(envelopes: $envelopes)\n }\n `;\n\t\tconst variables = { envelopes: envelopes.map((e) => serializeEnvelope(e)) };\n\t\tawait this.executeGraphQL(mutation, variables);\n\t}\n\t/**\n\t* Gets the authorization header value using jwtHandler.\n\t*/\n\tasync getAuthorizationHeader() {\n\t\tif (!this.config.jwtHandler) return;\n\t\ttry {\n\t\t\tconst token = await this.config.jwtHandler(this.config.url);\n\t\t\tif (token) return `Bearer ${token}`;\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"JWT handler failed: @Error\", error);\n\t\t}\n\t}\n\t/**\n\t* Executes a GraphQL query or mutation against the remote endpoint.\n\t*/\n\tasync executeGraphQL(query, variables) {\n\t\tconst headers = { \"Content-Type\": \"application/json\" };\n\t\tconst authHeader = await this.getAuthorizationHeader();\n\t\tif (authHeader) headers[\"Authorization\"] = authHeader;\n\t\tconst operationName = query.match(/(?:query|mutation)\\s+(\\w+)/)?.[1] ?? \"unknown\";\n\t\tthis.logger.verbose(\"GQL request @channelId @operation @url vars=@variables\", this.channelId, operationName, this.config.url, JSON.stringify(variables));\n\t\tconst fetchFn = this.config.fetchFn ?? fetch;\n\t\tlet response;\n\t\ttry {\n\t\t\tresponse = await fetchFn(this.config.url, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tquery,\n\t\t\t\t\tvariables\n\t\t\t\t}),\n\t\t\t\tsignal: this.abortController.signal\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new GraphQLRequestError(`GraphQL request failed: ${error instanceof Error ? error.message : String(error)}`, \"network\");\n\t\t}\n\t\tif (!response.ok) throw new GraphQLRequestError(`GraphQL request failed: ${response.status} ${response.statusText}`, \"http\", response.status);\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await response.json();\n\t\t} catch (error) {\n\t\t\tthrow new GraphQLRequestError(`Failed to parse GraphQL response: ${error instanceof Error ? error.message : String(error)}`, \"parse\");\n\t\t}\n\t\tthis.logger.verbose(\"GQL response @channelId @operation status=@status data=@data errors=@errors\", this.channelId, operationName, response.status, JSON.stringify(result.data), result.errors ? JSON.stringify(result.errors) : \"none\");\n\t\tif (result.errors) throw new GraphQLRequestError(`GraphQL errors: ${JSON.stringify(result.errors, null, 2)}`, \"graphql\");\n\t\tif (!result.data) throw new GraphQLRequestError(\"GraphQL response missing data field\", \"missing-data\");\n\t\treturn result.data;\n\t}\n\tget poller() {\n\t\treturn this.pollTimer;\n\t}\n};\n//#endregion\n//#region src/sync/channels/gql-request-channel-factory.ts\n/**\n* Factory for creating GqlRequestChannel instances.\n*\n* Extracts GraphQL-specific configuration from ChannelConfig.parameters and\n* instantiates GqlRequestChannel instances for network-based synchronization.\n*\n* The optional jwtHandler enables dynamic JWT token generation per-request,\n* which is useful for short-lived tokens with audience-specific claims.\n*/\nvar GqlRequestChannelFactory = class {\n\tlogger;\n\tjwtHandler;\n\tqueue;\n\tconstructor(logger, jwtHandler, queue) {\n\t\tthis.logger = logger;\n\t\tthis.jwtHandler = jwtHandler;\n\t\tthis.queue = queue;\n\t}\n\t/**\n\t* Creates a new GqlRequestChannel instance with the given configuration.\n\t* See GqlChannelConfig for the expected parameters.\n\t*\n\t* @param config - Channel configuration including type and parameters\n\t* @param cursorStorage - Storage for persisting synchronization cursors\n\t* @param operationIndex - Operation index for querying timestamps\n\t* @returns A new GqlRequestChannel instance\n\t*/\n\tinstance(remoteId, remoteName, config, cursorStorage, collectionId, filter, operationIndex, options) {\n\t\tconst url = config.parameters.url;\n\t\tif (typeof url !== \"string\" || !url) throw new Error(\"GqlRequestChannelFactory requires \\\"url\\\" parameter in config.parameters\");\n\t\tconst gqlConfig = {\n\t\t\turl,\n\t\t\tcollectionId,\n\t\t\tfilter,\n\t\t\tjwtHandler: this.jwtHandler,\n\t\t\tretryBaseDelayMs: 1e3,\n\t\t\tretryMaxDelayMs: 3e5\n\t\t};\n\t\tlet pollIntervalMs = 2e3;\n\t\tif (config.parameters.pollIntervalMs !== void 0) {\n\t\t\tif (typeof config.parameters.pollIntervalMs !== \"number\") throw new Error(\"\\\"pollIntervalMs\\\" parameter must be a number\");\n\t\t\tpollIntervalMs = config.parameters.pollIntervalMs;\n\t\t}\n\t\tlet retryBaseDelayMs;\n\t\tif (config.parameters.retryBaseDelayMs !== void 0) {\n\t\t\tif (typeof config.parameters.retryBaseDelayMs !== \"number\") throw new Error(\"\\\"retryBaseDelayMs\\\" parameter must be a number\");\n\t\t\tretryBaseDelayMs = config.parameters.retryBaseDelayMs;\n\t\t}\n\t\tlet retryMaxDelayMs;\n\t\tif (config.parameters.retryMaxDelayMs !== void 0) {\n\t\t\tif (typeof config.parameters.retryMaxDelayMs !== \"number\") throw new Error(\"\\\"retryMaxDelayMs\\\" parameter must be a number\");\n\t\t\tretryMaxDelayMs = config.parameters.retryMaxDelayMs;\n\t\t}\n\t\tif (config.parameters.fetchFn !== void 0) {\n\t\t\tif (typeof config.parameters.fetchFn !== \"function\") throw new Error(\"\\\"fetchFn\\\" parameter must be a function\");\n\t\t\tgqlConfig.fetchFn = config.parameters.fetchFn;\n\t\t}\n\t\tif (retryBaseDelayMs !== void 0) gqlConfig.retryBaseDelayMs = retryBaseDelayMs;\n\t\tif (retryMaxDelayMs !== void 0) gqlConfig.retryMaxDelayMs = retryMaxDelayMs;\n\t\tlet maxQueueDepth;\n\t\tif (config.parameters.maxQueueDepth !== void 0) {\n\t\t\tif (typeof config.parameters.maxQueueDepth !== \"number\") throw new Error(\"\\\"maxQueueDepth\\\" parameter must be a number\");\n\t\t\tmaxQueueDepth = config.parameters.maxQueueDepth;\n\t\t}\n\t\tlet backpressureCheckIntervalMs;\n\t\tif (config.parameters.backpressureCheckIntervalMs !== void 0) {\n\t\t\tif (typeof config.parameters.backpressureCheckIntervalMs !== \"number\") throw new Error(\"\\\"backpressureCheckIntervalMs\\\" parameter must be a number\");\n\t\t\tbackpressureCheckIntervalMs = config.parameters.backpressureCheckIntervalMs;\n\t\t}\n\t\tconst pollTimer = new IntervalPollTimer(this.queue, {\n\t\t\tintervalMs: pollIntervalMs,\n\t\t\t...retryBaseDelayMs !== void 0 && { retryBaseDelayMs },\n\t\t\t...retryMaxDelayMs !== void 0 && { retryMaxDelayMs },\n\t\t\t...maxQueueDepth !== void 0 && { maxQueueDepth },\n\t\t\t...backpressureCheckIntervalMs !== void 0 && { backpressureCheckIntervalMs },\n\t\t\tstartPaused: options?.pollBehavior === PollBehavior.Manual\n\t\t});\n\t\treturn new GqlRequestChannel(this.logger, remoteId, remoteName, cursorStorage, gqlConfig, operationIndex, pollTimer);\n\t}\n};\n//#endregion\n//#region src/sync/channels/gql-res-channel.ts\n/**\n* This class is used server-side to accumulate inbox + outbox operations.\n*\n* In general, the resolvers are responsible for updating mailboxes.\n*/\nvar GqlResponseChannel = class {\n\tinbox;\n\toutbox;\n\tdeadLetter;\n\tchannelId;\n\tremoteName;\n\tcursorStorage;\n\tisShutdown;\n\tlastPersistedInboxOrdinal = 0;\n\tlastPersistedOutboxOrdinal = 0;\n\tconnectionState = \"connecting\";\n\tconnectionStateCallbacks = /* @__PURE__ */ new Set();\n\tconstructor(logger, channelId, remoteName, cursorStorage) {\n\t\tthis.logger = logger;\n\t\tthis.channelId = channelId;\n\t\tthis.remoteName = remoteName;\n\t\tthis.cursorStorage = cursorStorage;\n\t\tthis.isShutdown = false;\n\t\tthis.inbox = new Mailbox();\n\t\tthis.outbox = new Mailbox();\n\t\tthis.deadLetter = new Mailbox();\n\t\tthis.outbox.onRemoved((syncOps) => {\n\t\t\tconst maxOrdinal = getLatestAppliedOrdinal(syncOps);\n\t\t\tif (maxOrdinal > this.lastPersistedOutboxOrdinal) {\n\t\t\t\tthis.lastPersistedOutboxOrdinal = maxOrdinal;\n\t\t\t\tthis.cursorStorage.upsert({\n\t\t\t\t\tremoteName: this.remoteName,\n\t\t\t\t\tcursorType: \"outbox\",\n\t\t\t\t\tcursorOrdinal: maxOrdinal,\n\t\t\t\t\tlastSyncedAtUtcMs: Date.now()\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tthis.logger.error(\"Failed to update outbox cursor for @ChannelId! This means that future application runs may resend duplicate operations. This is recoverable (with deduplication protection), but not-optimal: @Error\", this.channelId, error);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tthis.inbox.onRemoved((syncOps) => {\n\t\t\tconst maxOrdinal = getLatestAppliedOrdinal(syncOps);\n\t\t\tif (maxOrdinal > this.lastPersistedInboxOrdinal) {\n\t\t\t\tthis.lastPersistedInboxOrdinal = maxOrdinal;\n\t\t\t\tthis.cursorStorage.upsert({\n\t\t\t\t\tremoteName: this.remoteName,\n\t\t\t\t\tcursorType: \"inbox\",\n\t\t\t\t\tcursorOrdinal: maxOrdinal,\n\t\t\t\t\tlastSyncedAtUtcMs: Date.now()\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tthis.logger.error(\"Failed to update inbox cursor for @ChannelId! This is unlikely to cause a problem, but not-optimal: @Error\", this.channelId, error);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\tshutdown() {\n\t\tthis.isShutdown = true;\n\t\tthis.transitionConnectionState(\"disconnected\");\n\t\treturn Promise.resolve();\n\t}\n\tgetConnectionState() {\n\t\treturn {\n\t\t\tstate: this.connectionState,\n\t\t\tfailureCount: 0,\n\t\t\tlastSuccessUtcMs: 0,\n\t\t\tlastFailureUtcMs: 0,\n\t\t\tpushBlocked: false,\n\t\t\tpushFailureCount: 0,\n\t\t\treceivingPages: false\n\t\t};\n\t}\n\tonConnectionStateChange(callback) {\n\t\tthis.connectionStateCallbacks.add(callback);\n\t\treturn () => {\n\t\t\tthis.connectionStateCallbacks.delete(callback);\n\t\t};\n\t}\n\t/** Response channels are push-driven; resolvers populate mailboxes directly. */\n\ttriggerPull() {}\n\ttransitionConnectionState(next) {\n\t\tif (this.connectionState === next) return;\n\t\tthis.connectionState = next;\n\t\tconst snapshot = this.getConnectionState();\n\t\tfor (const callback of this.connectionStateCallbacks) try {\n\t\t\tcallback(snapshot);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Connection state change callback error: @Error\", error);\n\t\t}\n\t}\n\tasync init() {\n\t\tconst cursors = await this.cursorStorage.list(this.remoteName);\n\t\tconst inboxOrdinal = cursors.find((c) => c.cursorType === \"inbox\")?.cursorOrdinal ?? 0;\n\t\tconst outboxOrdinal = cursors.find((c) => c.cursorType === \"outbox\")?.cursorOrdinal ?? 0;\n\t\tthis.inbox.init(inboxOrdinal);\n\t\tthis.outbox.init(outboxOrdinal);\n\t\tthis.lastPersistedInboxOrdinal = inboxOrdinal;\n\t\tthis.lastPersistedOutboxOrdinal = outboxOrdinal;\n\t\tthis.transitionConnectionState(\"connected\");\n\t}\n};\n//#endregion\n//#region src/sync/channels/gql-response-channel-factory.ts\n/**\n* Factory for creating GqlResponseChannel instances.\n*/\nvar GqlResponseChannelFactory = class {\n\tlogger;\n\tconstructor(logger) {\n\t\tthis.logger = logger;\n\t}\n\tinstance(remoteId, remoteName, config, cursorStorage) {\n\t\treturn new GqlResponseChannel(this.logger, remoteId, remoteName, cursorStorage);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/sync-cursor-storage.ts\nfunction rowToRemoteCursor(row) {\n\treturn {\n\t\tremoteName: row.remote_name,\n\t\tcursorType: row.cursor_type,\n\t\tcursorOrdinal: Number(row.cursor_ordinal),\n\t\tlastSyncedAtUtcMs: row.last_synced_at_utc_ms ? new Date(row.last_synced_at_utc_ms).getTime() : void 0\n\t};\n}\nfunction remoteCursorToRow(cursor) {\n\treturn {\n\t\tremote_name: cursor.remoteName,\n\t\tcursor_type: cursor.cursorType,\n\t\tcursor_ordinal: BigInt(cursor.cursorOrdinal),\n\t\tlast_synced_at_utc_ms: cursor.lastSyncedAtUtcMs ? new Date(cursor.lastSyncedAtUtcMs).toISOString() : null\n\t};\n}\nvar KyselySyncCursorStorage = class {\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tasync list(remoteName, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst rows = await this.db.selectFrom(\"sync_cursors\").selectAll().where(\"remote_name\", \"=\", remoteName).execute();\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn rows.map(rowToRemoteCursor);\n\t}\n\tasync get(remoteName, cursorType, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst row = await this.db.selectFrom(\"sync_cursors\").selectAll().where(\"remote_name\", \"=\", remoteName).where(\"cursor_type\", \"=\", cursorType).executeTakeFirst();\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tif (!row) return {\n\t\t\tremoteName,\n\t\t\tcursorType,\n\t\t\tcursorOrdinal: 0\n\t\t};\n\t\treturn rowToRemoteCursor(row);\n\t}\n\tasync upsert(cursor, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tconst insertable = remoteCursorToRow(cursor);\n\t\t\tawait trx.insertInto(\"sync_cursors\").values(insertable).onConflict((oc) => oc.columns([\"remote_name\", \"cursor_type\"]).doUpdateSet({\n\t\t\t\t...insertable,\n\t\t\t\tupdated_at: sql`NOW()`\n\t\t\t})).execute();\n\t\t});\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t}\n\tasync remove(remoteName, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tawait trx.deleteFrom(\"sync_cursors\").where(\"remote_name\", \"=\", remoteName).execute();\n\t\t});\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t}\n};\n//#endregion\n//#region src/storage/kysely/sync-dead-letter-storage.ts\nfunction rowToDeadLetterRecord(row) {\n\treturn {\n\t\tid: row.id,\n\t\tjobId: row.job_id,\n\t\tjobDependencies: row.job_dependencies,\n\t\tremoteName: row.remote_name,\n\t\tdocumentId: row.document_id,\n\t\tscopes: row.scopes,\n\t\tbranch: row.branch,\n\t\toperations: row.operations,\n\t\terrorSource: row.error_source,\n\t\terrorMessage: row.error_message\n\t};\n}\nfunction deadLetterRecordToRow(record) {\n\treturn {\n\t\tid: record.id,\n\t\tjob_id: record.jobId,\n\t\tjob_dependencies: JSON.stringify(record.jobDependencies),\n\t\tremote_name: record.remoteName,\n\t\tdocument_id: record.documentId,\n\t\tscopes: JSON.stringify(record.scopes),\n\t\tbranch: record.branch,\n\t\toperations: JSON.stringify(record.operations),\n\t\terror_source: record.errorSource,\n\t\terror_message: record.errorMessage\n\t};\n}\n/**\n* PGlite/Kysely-backed implementation of {@link ISyncDeadLetterStorage}.\n*/\nvar KyselySyncDeadLetterStorage = class {\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tasync list(remoteName, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst startIndex = paging?.cursor ? parseInt(paging.cursor) : 0;\n\t\tconst limit = paging?.limit || 100;\n\t\tconst rows = await this.db.selectFrom(\"sync_dead_letters\").selectAll().where(\"remote_name\", \"=\", remoteName).orderBy(\"ordinal\", \"desc\").offset(startIndex).limit(limit + 1).execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, limit);\n\t\t}\n\t\tconst nextCursor = hasMore ? String(startIndex + limit) : void 0;\n\t\tconst cursor = paging?.cursor || \"0\";\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn {\n\t\t\tresults: items.map(rowToDeadLetterRecord),\n\t\t\toptions: {\n\t\t\t\tcursor,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor\n\t\t};\n\t}\n\tasync add(deadLetter, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tconst insertable = deadLetterRecordToRow(deadLetter);\n\t\t\tawait trx.insertInto(\"sync_dead_letters\").values(insertable).onConflict((oc) => oc.column(\"id\").doNothing()).execute();\n\t\t});\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t}\n\tasync remove(id, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tawait trx.deleteFrom(\"sync_dead_letters\").where(\"id\", \"=\", id).execute();\n\t\t});\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t}\n\tasync removeByRemote(remoteName, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tawait trx.deleteFrom(\"sync_dead_letters\").where(\"remote_name\", \"=\", remoteName).execute();\n\t\t});\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t}\n\tasync listQuarantinedDocumentIds(signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst rows = await this.db.selectFrom(\"sync_dead_letters\").select(\"document_id\").distinct().execute();\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn rows.map((row) => row.document_id);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/sync-remote-storage.ts\nfunction rowToRemoteRecord(row) {\n\treturn {\n\t\tid: row.channel_id,\n\t\tname: row.name,\n\t\tcollectionId: DriveCollectionId.fromKey(row.collection_id),\n\t\tchannelConfig: {\n\t\t\ttype: row.channel_type,\n\t\t\tparameters: row.channel_parameters ?? {}\n\t\t},\n\t\tfilter: {\n\t\t\tdocumentId: row.filter_document_ids ?? [],\n\t\t\tscope: row.filter_scopes ?? [],\n\t\t\tbranch: row.filter_branch\n\t\t},\n\t\toptions: { sinceTimestampUtcMs: \"0\" },\n\t\tstatus: {\n\t\t\tpush: {\n\t\t\t\tstate: row.push_state,\n\t\t\t\tlastSuccessUtcMs: row.push_last_success_utc_ms ? new Date(row.push_last_success_utc_ms).getTime() : void 0,\n\t\t\t\tlastFailureUtcMs: row.push_last_failure_utc_ms ? new Date(row.push_last_failure_utc_ms).getTime() : void 0,\n\t\t\t\tfailureCount: row.push_failure_count\n\t\t\t},\n\t\t\tpull: {\n\t\t\t\tstate: row.pull_state,\n\t\t\t\tlastSuccessUtcMs: row.pull_last_success_utc_ms ? new Date(row.pull_last_success_utc_ms).getTime() : void 0,\n\t\t\t\tlastFailureUtcMs: row.pull_last_failure_utc_ms ? new Date(row.pull_last_failure_utc_ms).getTime() : void 0,\n\t\t\t\tfailureCount: row.pull_failure_count\n\t\t\t}\n\t\t}\n\t};\n}\nfunction remoteRecordToRow(remote) {\n\treturn {\n\t\tname: remote.name,\n\t\tcollection_id: remote.collectionId.key,\n\t\tchannel_type: remote.channelConfig.type,\n\t\tchannel_id: remote.id,\n\t\tremote_name: remote.name,\n\t\tchannel_parameters: remote.channelConfig.parameters,\n\t\tfilter_document_ids: remote.filter.documentId.length > 0 ? remote.filter.documentId : null,\n\t\tfilter_scopes: remote.filter.scope.length > 0 ? remote.filter.scope : null,\n\t\tfilter_branch: remote.filter.branch,\n\t\tpush_state: remote.status.push.state,\n\t\tpush_last_success_utc_ms: remote.status.push.lastSuccessUtcMs ? new Date(remote.status.push.lastSuccessUtcMs).toISOString() : null,\n\t\tpush_last_failure_utc_ms: remote.status.push.lastFailureUtcMs ? new Date(remote.status.push.lastFailureUtcMs).toISOString() : null,\n\t\tpush_failure_count: remote.status.push.failureCount,\n\t\tpull_state: remote.status.pull.state,\n\t\tpull_last_success_utc_ms: remote.status.pull.lastSuccessUtcMs ? new Date(remote.status.pull.lastSuccessUtcMs).toISOString() : null,\n\t\tpull_last_failure_utc_ms: remote.status.pull.lastFailureUtcMs ? new Date(remote.status.pull.lastFailureUtcMs).toISOString() : null,\n\t\tpull_failure_count: remote.status.pull.failureCount\n\t};\n}\nvar KyselySyncRemoteStorage = class {\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tasync list(signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst rows = await this.db.selectFrom(\"sync_remotes\").selectAll().execute();\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn rows.map(rowToRemoteRecord);\n\t}\n\tasync get(name, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst row = await this.db.selectFrom(\"sync_remotes\").selectAll().where(\"name\", \"=\", name).executeTakeFirst();\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tif (!row) throw new Error(`Remote not found: ${name}`);\n\t\treturn rowToRemoteRecord(row);\n\t}\n\tasync upsert(remote, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tconst insertable = remoteRecordToRow(remote);\n\t\t\tawait trx.insertInto(\"sync_remotes\").values(insertable).onConflict((oc) => oc.column(\"name\").doUpdateSet({\n\t\t\t\t...insertable,\n\t\t\t\tupdated_at: sql`NOW()`\n\t\t\t})).execute();\n\t\t});\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t}\n\tasync remove(name, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tawait trx.deleteFrom(\"sync_remotes\").where(\"name\", \"=\", name).execute();\n\t\t});\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t}\n};\n//#endregion\n//#region src/sync/batch-aggregator.ts\nvar BatchAggregator = class {\n\tlogger;\n\tdriveContainerTypes;\n\tonBatchReady;\n\tqueue = [];\n\tprocessing = false;\n\tpendingBatches = /* @__PURE__ */ new Map();\n\tconstructor(logger, driveContainerTypes, onBatchReady) {\n\t\tthis.logger = logger;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.onBatchReady = onBatchReady;\n\t}\n\tasync enqueueWriteReady(event) {\n\t\tthis.queue.push(event);\n\t\tawait this.processQueue();\n\t}\n\tasync handleJobFailed(event) {\n\t\tconst batchId = event.job?.meta.batchId;\n\t\tif (!batchId) return;\n\t\tconst pending = this.pendingBatches.get(batchId);\n\t\tif (!pending) return;\n\t\tthis.pendingBatches.delete(batchId);\n\t\tif (pending.events.length > 0) await this.onBatchReady(this.prepareBatch(pending.events));\n\t}\n\tclear() {\n\t\tthis.queue = [];\n\t\tthis.pendingBatches.clear();\n\t}\n\tasync processQueue() {\n\t\tif (this.processing) return;\n\t\tthis.processing = true;\n\t\ttry {\n\t\t\twhile (this.queue.length > 0) {\n\t\t\t\tconst event = this.queue.shift();\n\t\t\t\ttry {\n\t\t\t\t\tawait this.handleWriteReady(event);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\tthis.logger.error(\"Failed to process write-ready event (@jobId, @error)\", event.jobId, err.message);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.processing = false;\n\t\t}\n\t}\n\tasync handleWriteReady(event) {\n\t\tconst { batchId, batchJobIds } = event.jobMeta;\n\t\tif (batchJobIds.length <= 1) {\n\t\t\tawait this.onBatchReady(this.prepareBatch([event]));\n\t\t\treturn;\n\t\t}\n\t\tlet pending = this.pendingBatches.get(batchId);\n\t\tif (!pending) {\n\t\t\tpending = {\n\t\t\t\texpectedJobIds: new Set(batchJobIds),\n\t\t\t\tarrivedJobIds: /* @__PURE__ */ new Set(),\n\t\t\t\tevents: []\n\t\t\t};\n\t\t\tthis.pendingBatches.set(batchId, pending);\n\t\t}\n\t\tpending.arrivedJobIds.add(event.jobId);\n\t\tpending.events.push(event);\n\t\tif (pending.arrivedJobIds.size >= pending.expectedJobIds.size) {\n\t\t\tthis.pendingBatches.delete(batchId);\n\t\t\tawait this.onBatchReady(this.prepareBatch(pending.events));\n\t\t}\n\t}\n\tprepareBatch(events) {\n\t\tconst collectionMemberships = this.mergeCollectionMemberships(events);\n\t\tconst isBatch = events.length > 1;\n\t\tconst priorJobIds = [];\n\t\tconst entries = [];\n\t\tfor (const event of events) {\n\t\t\tentries.push({\n\t\t\t\tevent,\n\t\t\t\tjobDependencies: isBatch ? [...priorJobIds] : []\n\t\t\t});\n\t\t\tif (isBatch && event.jobId) priorJobIds.push(event.jobId);\n\t\t}\n\t\treturn {\n\t\t\tcollectionMemberships,\n\t\t\tentries\n\t\t};\n\t}\n\tmergeCollectionMemberships(events) {\n\t\tconst mergedMemberships = {};\n\t\tfor (const event of events) {\n\t\t\tif (event.collectionMemberships) for (const [docId, collections] of Object.entries(event.collectionMemberships)) {\n\t\t\t\tif (!(docId in mergedMemberships)) mergedMemberships[docId] = [];\n\t\t\t\tfor (const c of collections) if (!mergedMemberships[docId].includes(c)) mergedMemberships[docId].push(c);\n\t\t\t}\n\t\t\tfor (const op of event.operations) {\n\t\t\t\tconst action = op.operation.action;\n\t\t\t\tif (action.type !== \"ADD_RELATIONSHIP\") continue;\n\t\t\t\tif (!this.driveContainerTypes.has(op.context.documentType)) continue;\n\t\t\t\tconst input = action.input;\n\t\t\t\tif (!input?.sourceId || !input.targetId) continue;\n\t\t\t\tconst collectionId = DriveCollectionId.forDrive(input.sourceId, op.context.branch).key;\n\t\t\t\tif (!(input.targetId in mergedMemberships)) mergedMemberships[input.targetId] = [];\n\t\t\t\tif (!mergedMemberships[input.targetId].includes(collectionId)) mergedMemberships[input.targetId].push(collectionId);\n\t\t\t}\n\t\t}\n\t\treturn mergedMemberships;\n\t}\n};\n//#endregion\n//#region src/sync/sync-awaiter.ts\n/**\n* Provides a promise-based interface for waiting on sync completion.\n* Subscribes to sync events at construction and tracks completed sync results\n* to provide a fast path for jobs that have already synced.\n*/\nvar SyncAwaiter = class {\n\tcompletedResults = /* @__PURE__ */ new Map();\n\tpendingWaiters = /* @__PURE__ */ new Map();\n\tunsubscribers = [];\n\tisShutdown = false;\n\tconstructor(eventBus) {\n\t\tthis.eventBus = eventBus;\n\t\tthis.subscribeToEvents();\n\t}\n\t/**\n\t* Waits for sync operations for a job to complete.\n\t* Resolves when SYNC_SUCCEEDED is emitted.\n\t* Rejects when SYNC_FAILED is emitted.\n\t*\n\t* @param jobId - The job id to wait for\n\t* @param signal - Optional abort signal\n\t* @returns The sync result\n\t*/\n\twaitForSync(jobId, signal) {\n\t\tif (signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\tif (this.isShutdown) return Promise.reject(/* @__PURE__ */ new Error(\"SyncAwaiter is shutdown\"));\n\t\tconst completedResult = this.completedResults.get(jobId);\n\t\tif (completedResult) return Promise.resolve(completedResult);\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst waiter = {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\tsignal\n\t\t\t};\n\t\t\tconst existingWaiters = this.pendingWaiters.get(jobId) || [];\n\t\t\texistingWaiters.push(waiter);\n\t\t\tthis.pendingWaiters.set(jobId, existingWaiters);\n\t\t\tif (signal) {\n\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\tconst waiters = this.pendingWaiters.get(jobId);\n\t\t\t\t\tif (waiters) {\n\t\t\t\t\t\tconst index = waiters.indexOf(waiter);\n\t\t\t\t\t\tif (index !== -1) {\n\t\t\t\t\t\t\twaiters.splice(index, 1);\n\t\t\t\t\t\t\tif (waiters.length === 0) this.pendingWaiters.delete(jobId);\n\t\t\t\t\t\t\twaiter.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tsignal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Shuts down the sync awaiter. This will synchronously reject all pending waiters.\n\t*/\n\tshutdown() {\n\t\tthis.isShutdown = true;\n\t\tfor (const unsubscribe of this.unsubscribers) unsubscribe();\n\t\tthis.unsubscribers.length = 0;\n\t\tfor (const [, waiters] of this.pendingWaiters) for (const waiter of waiters) waiter.reject(/* @__PURE__ */ new Error(\"SyncAwaiter shutdown\"));\n\t\tthis.pendingWaiters.clear();\n\t}\n\tsubscribeToEvents() {\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(SyncEventTypes.SYNC_SUCCEEDED, (_type, event) => {\n\t\t\tthis.handleSyncSucceeded(event);\n\t\t}));\n\t\tthis.unsubscribers.push(this.eventBus.subscribe(SyncEventTypes.SYNC_FAILED, (_type, event) => {\n\t\t\tthis.handleSyncFailed(event);\n\t\t}));\n\t}\n\thandleSyncSucceeded(event) {\n\t\tconst result = {\n\t\t\tjobId: event.jobId,\n\t\t\tstatus: \"succeeded\",\n\t\t\tsyncOperationCount: event.syncOperationCount,\n\t\t\tsuccessCount: event.syncOperationCount,\n\t\t\tfailureCount: 0,\n\t\t\terrors: []\n\t\t};\n\t\tthis.completedResults.set(event.jobId, result);\n\t\tthis.resolveWaiters(event.jobId, result);\n\t}\n\thandleSyncFailed(event) {\n\t\tconst result = {\n\t\t\tjobId: event.jobId,\n\t\t\tstatus: \"failed\",\n\t\t\tsyncOperationCount: event.successCount + event.failureCount,\n\t\t\tsuccessCount: event.successCount,\n\t\t\tfailureCount: event.failureCount,\n\t\t\terrors: event.errors\n\t\t};\n\t\tthis.completedResults.set(event.jobId, result);\n\t\tthis.resolveWaiters(event.jobId, result);\n\t}\n\tresolveWaiters(jobId, result) {\n\t\tconst waiters = this.pendingWaiters.get(jobId);\n\t\tif (!waiters || waiters.length === 0) return;\n\t\tthis.pendingWaiters.delete(jobId);\n\t\tfor (const waiter of waiters) if (waiter.signal?.aborted) waiter.reject(/* @__PURE__ */ new Error(\"Operation aborted\"));\n\t\telse waiter.resolve(result);\n\t}\n};\n//#endregion\n//#region src/sync/sync-status-tracker.ts\nlet SyncStatus = /* @__PURE__ */ function(SyncStatus) {\n\tSyncStatus[\"Synced\"] = \"SYNCED\";\n\tSyncStatus[\"Outgoing\"] = \"OUTGOING\";\n\tSyncStatus[\"Incoming\"] = \"INCOMING\";\n\tSyncStatus[\"OutgoingAndIncoming\"] = \"OUTGOING_AND_INCOMING\";\n\tSyncStatus[\"Error\"] = \"ERROR\";\n\treturn SyncStatus;\n}({});\nvar SyncStatusTracker = class {\n\tremotes = /* @__PURE__ */ new Map();\n\tseen = /* @__PURE__ */ new Set();\n\tcallbacks = /* @__PURE__ */ new Set();\n\tgetStatus(documentId) {\n\t\tif (!this.seen.has(documentId)) return;\n\t\tlet totalInbox = 0;\n\t\tlet totalOutbox = 0;\n\t\tlet totalErrors = 0;\n\t\tfor (const documents of this.remotes.values()) {\n\t\t\tconst counts = documents.get(documentId);\n\t\t\tif (counts) {\n\t\t\t\ttotalInbox += counts.inboxCount;\n\t\t\t\ttotalOutbox += counts.outboxCount;\n\t\t\t\ttotalErrors += counts.errorCount;\n\t\t\t}\n\t\t}\n\t\treturn deriveStatus(totalInbox, totalOutbox, totalErrors);\n\t}\n\tonChange(callback) {\n\t\tthis.callbacks.add(callback);\n\t\treturn () => {\n\t\t\tthis.callbacks.delete(callback);\n\t\t};\n\t}\n\ttrackRemote(remoteName, channel) {\n\t\tthis.remotes.set(remoteName, /* @__PURE__ */ new Map());\n\t\tchannel.inbox.onAdded((syncOps) => this.handleAdded(remoteName, \"inbox\", syncOps));\n\t\tchannel.inbox.onRemoved((syncOps) => this.handleRemoved(remoteName, \"inbox\", syncOps));\n\t\tchannel.outbox.onAdded((syncOps) => this.handleAdded(remoteName, \"outbox\", syncOps));\n\t\tchannel.outbox.onRemoved((syncOps) => this.handleRemoved(remoteName, \"outbox\", syncOps));\n\t\tchannel.deadLetter.onAdded((syncOps) => this.handleAdded(remoteName, \"deadLetter\", syncOps));\n\t}\n\tuntrackRemote(remoteName) {\n\t\tconst documents = this.remotes.get(remoteName);\n\t\tif (!documents) return;\n\t\tconst affectedDocumentIds = [...documents.keys()];\n\t\tthis.remotes.delete(remoteName);\n\t\tfor (const documentId of affectedDocumentIds) this.notifyChange(documentId);\n\t}\n\tclear() {\n\t\tthis.remotes.clear();\n\t\tthis.seen.clear();\n\t\tthis.callbacks.clear();\n\t}\n\thandleAdded(remoteName, mailboxType, syncOps) {\n\t\tconst changedDocuments = /* @__PURE__ */ new Set();\n\t\tfor (const syncOp of syncOps) {\n\t\t\tif (mailboxType === \"inbox\" && !syncOp.remoteName) continue;\n\t\t\tconst counts = this.getOrCreateCounts(remoteName, syncOp.documentId);\n\t\t\tthis.seen.add(syncOp.documentId);\n\t\t\tif (mailboxType === \"inbox\") counts.inboxCount++;\n\t\t\telse if (mailboxType === \"outbox\") counts.outboxCount++;\n\t\t\telse counts.errorCount++;\n\t\t\tchangedDocuments.add(syncOp.documentId);\n\t\t}\n\t\tfor (const documentId of changedDocuments) this.notifyChange(documentId);\n\t}\n\thandleRemoved(remoteName, mailboxType, syncOps) {\n\t\tconst changedDocuments = /* @__PURE__ */ new Set();\n\t\tfor (const syncOp of syncOps) {\n\t\t\tconst counts = this.getOrCreateCounts(remoteName, syncOp.documentId);\n\t\t\tif (mailboxType === \"inbox\") counts.inboxCount = Math.max(0, counts.inboxCount - 1);\n\t\t\telse if (mailboxType === \"outbox\") counts.outboxCount = Math.max(0, counts.outboxCount - 1);\n\t\t\tchangedDocuments.add(syncOp.documentId);\n\t\t}\n\t\tfor (const documentId of changedDocuments) this.notifyChange(documentId);\n\t}\n\tgetOrCreateCounts(remoteName, documentId) {\n\t\tlet documents = this.remotes.get(remoteName);\n\t\tif (!documents) {\n\t\t\tdocuments = /* @__PURE__ */ new Map();\n\t\t\tthis.remotes.set(remoteName, documents);\n\t\t}\n\t\tlet counts = documents.get(documentId);\n\t\tif (!counts) {\n\t\t\tcounts = {\n\t\t\t\tinboxCount: 0,\n\t\t\t\toutboxCount: 0,\n\t\t\t\terrorCount: 0\n\t\t\t};\n\t\t\tdocuments.set(documentId, counts);\n\t\t}\n\t\treturn counts;\n\t}\n\tnotifyChange(documentId) {\n\t\tconst status = this.getStatus(documentId);\n\t\tif (status === void 0) return;\n\t\tfor (const callback of [...this.callbacks]) callback(documentId, status);\n\t}\n};\nfunction deriveStatus(inboxCount, outboxCount, errorCount) {\n\tif (errorCount > 0) return SyncStatus.Error;\n\tif (inboxCount > 0 && outboxCount > 0) return SyncStatus.OutgoingAndIncoming;\n\tif (inboxCount > 0) return SyncStatus.Incoming;\n\tif (outboxCount > 0) return SyncStatus.Outgoing;\n\treturn SyncStatus.Synced;\n}\n//#endregion\n//#region src/sync/sync-manager.ts\nvar OutboxMode = /* @__PURE__ */ function(OutboxMode) {\n\tOutboxMode[\"Backfill\"] = \"backfill\";\n\tOutboxMode[\"BatchTriggered\"] = \"batch-triggered\";\n\treturn OutboxMode;\n}(OutboxMode || {});\nconst defaultSyncManagerConfig = {\n\tmaxDeadLettersPerRemote: 100,\n\tmaxInboxBatchSize: 32\n};\nconst PLAN_KEY_TO_JOB_UUID_CAP = 1e4;\nvar SyncManager = class {\n\tlogger;\n\tremoteStorage;\n\tcursorStorage;\n\tdeadLetterStorage;\n\tchannelFactory;\n\toperationIndex;\n\treactor;\n\teventBus;\n\tremotes;\n\tawaiter;\n\tsyncAwaiter;\n\tabortController = new AbortController();\n\tisShutdown;\n\teventUnsubscribe;\n\tfailedEventUnsubscribe;\n\tbatchAggregator;\n\tsyncStatusTracker;\n\tconfig;\n\tconnectionStateUnsubscribes = /* @__PURE__ */ new Map();\n\tquarantinedDocumentIds = /* @__PURE__ */ new Set();\n\tbackfillAbortControllers = /* @__PURE__ */ new Map();\n\tplanKeyToJobUuid = /* @__PURE__ */ new Map();\n\tlastEnqueuedJobIdByKey = /* @__PURE__ */ new Map();\n\tinboxChunkChain = Promise.resolve();\n\tconstructor(logger, remoteStorage, cursorStorage, deadLetterStorage, channelFactory, operationIndex, reactor, eventBus, driveContainerTypes, config = {}) {\n\t\tthis.logger = logger;\n\t\tthis.remoteStorage = remoteStorage;\n\t\tthis.cursorStorage = cursorStorage;\n\t\tthis.deadLetterStorage = deadLetterStorage;\n\t\tthis.channelFactory = channelFactory;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.reactor = reactor;\n\t\tthis.eventBus = eventBus;\n\t\tthis.config = {\n\t\t\t...defaultSyncManagerConfig,\n\t\t\t...config\n\t\t};\n\t\tthis.remotes = /* @__PURE__ */ new Map();\n\t\tthis.awaiter = new JobAwaiter(eventBus, (jobId, signal) => reactor.getJobStatus(jobId, signal));\n\t\tthis.syncAwaiter = new SyncAwaiter(eventBus);\n\t\tthis.isShutdown = false;\n\t\tthis.batchAggregator = new BatchAggregator(logger, driveContainerTypes, (batch) => this.processCompleteBatch(batch));\n\t\tthis.syncStatusTracker = new SyncStatusTracker();\n\t}\n\tasync startup() {\n\t\tif (this.isShutdown) throw new Error(\"SyncManager is already shutdown and cannot be started\");\n\t\ttry {\n\t\t\tconst quarantinedIds = await this.deadLetterStorage.listQuarantinedDocumentIds();\n\t\t\tfor (const id of quarantinedIds) this.quarantinedDocumentIds.add(id);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to load quarantined document IDs (@error)\", error instanceof Error ? error.message : String(error));\n\t\t}\n\t\tconst remoteRecords = await this.remoteStorage.list();\n\t\tfor (const record of remoteRecords) {\n\t\t\tconst channel = this.channelFactory.instance(record.id, record.name, record.channelConfig, this.cursorStorage, record.collectionId, record.filter, this.operationIndex, record.options);\n\t\t\tconst remote = {\n\t\t\t\tid: record.id,\n\t\t\t\tname: record.name,\n\t\t\t\tcollectionId: record.collectionId,\n\t\t\t\tfilter: record.filter,\n\t\t\t\toptions: record.options,\n\t\t\t\tchannel\n\t\t\t};\n\t\t\tthis.remotes.set(record.name, remote);\n\t\t\tawait this.loadDeadLetters(remote);\n\t\t\tthis.wireChannelCallbacks(remote);\n\t\t\ttry {\n\t\t\t\tawait channel.init();\n\t\t\t} catch (error) {\n\t\t\t\tthis.logger.error(\"Error initializing channel for remote (@name, @error)\", record.name, error instanceof Error ? error.message : String(error));\n\t\t\t\tthis.remotes.delete(record.name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst outboxAckOrdinal = remote.channel.outbox.ackOrdinal;\n\t\t\tif (outboxAckOrdinal > 0) {\n\t\t\t\tconst backfillController = new AbortController();\n\t\t\t\tthis.backfillAbortControllers.set(record.name, backfillController);\n\t\t\t\tthis.updateOutbox(remote, outboxAckOrdinal, OutboxMode.Backfill, backfillController.signal).catch((error) => {\n\t\t\t\t\tif (backfillController.signal.aborted) return;\n\t\t\t\t\tthis.logger.error(\"Backfill failed for remote @RemoteName: @Error\", remote.name, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t}).finally(() => {\n\t\t\t\t\tthis.backfillAbortControllers.delete(record.name);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.eventUnsubscribe = this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY, async (_type, event) => this.batchAggregator.enqueueWriteReady(event));\n\t\tthis.failedEventUnsubscribe = this.eventBus.subscribe(ReactorEventTypes.JOB_FAILED, async (_type, event) => this.batchAggregator.handleJobFailed(event));\n\t}\n\tshutdown() {\n\t\tthis.isShutdown = true;\n\t\tthis.abortController.abort();\n\t\tfor (const controller of this.backfillAbortControllers.values()) controller.abort();\n\t\tthis.backfillAbortControllers.clear();\n\t\tthis.planKeyToJobUuid.clear();\n\t\tthis.lastEnqueuedJobIdByKey.clear();\n\t\tthis.batchAggregator.clear();\n\t\tif (this.eventUnsubscribe) {\n\t\t\tthis.eventUnsubscribe();\n\t\t\tthis.eventUnsubscribe = void 0;\n\t\t}\n\t\tif (this.failedEventUnsubscribe) {\n\t\t\tthis.failedEventUnsubscribe();\n\t\t\tthis.failedEventUnsubscribe = void 0;\n\t\t}\n\t\tthis.awaiter.shutdown();\n\t\tthis.syncAwaiter.shutdown();\n\t\tthis.syncStatusTracker.clear();\n\t\tfor (const unsub of this.connectionStateUnsubscribes.values()) unsub();\n\t\tthis.connectionStateUnsubscribes.clear();\n\t\tconst promises = [];\n\t\tfor (const remote of this.remotes.values()) promises.push(remote.channel.shutdown());\n\t\tthis.remotes.clear();\n\t\treturn {\n\t\t\tisShutdown: true,\n\t\t\tcompleted: Promise.all(promises).then(() => void 0)\n\t\t};\n\t}\n\tgetByName(name) {\n\t\tconst remote = this.remotes.get(name);\n\t\tif (!remote) throw new Error(`Remote with name '${name}' does not exist`);\n\t\treturn remote;\n\t}\n\tgetById(id) {\n\t\tfor (const remote of this.remotes.values()) if (remote.id === id) return remote;\n\t\tthrow new Error(`Remote with id '${id}' does not exist`);\n\t}\n\tasync add(name, collectionId, channelConfig, filter = {\n\t\tdocumentId: [],\n\t\tscope: [],\n\t\tbranch: \"\"\n\t}, options = { sinceTimestampUtcMs: \"0\" }, id) {\n\t\tif (this.isShutdown) throw new Error(\"SyncManager is shutdown and cannot add remotes\");\n\t\tif (this.remotes.has(name)) throw new Error(`Remote with name '${name}' already exists`);\n\t\tthis.logger.debug(\"Adding remote (@name, @collectionId, @channelConfig, @filter, @options, @id)\", name, collectionId.key, channelConfig, filter, options, id);\n\t\tconst remoteId = id ?? crypto.randomUUID();\n\t\tconst remoteRecord = {\n\t\t\tid: remoteId,\n\t\t\tname,\n\t\t\tcollectionId,\n\t\t\tchannelConfig,\n\t\t\tfilter,\n\t\t\toptions,\n\t\t\tstatus: {\n\t\t\t\tpush: createIdleHealth(),\n\t\t\t\tpull: createIdleHealth()\n\t\t\t}\n\t\t};\n\t\tawait this.remoteStorage.upsert(remoteRecord);\n\t\tconst channel = this.channelFactory.instance(remoteId, name, channelConfig, this.cursorStorage, collectionId, filter, this.operationIndex, options);\n\t\tconst remote = {\n\t\t\tid: remoteId,\n\t\t\tname,\n\t\t\tcollectionId,\n\t\t\tfilter,\n\t\t\toptions,\n\t\t\tchannel\n\t\t};\n\t\tthis.remotes.set(name, remote);\n\t\tawait this.loadDeadLetters(remote);\n\t\tthis.wireChannelCallbacks(remote);\n\t\ttry {\n\t\t\tawait channel.init();\n\t\t} catch (error) {\n\t\t\tthis.remotes.delete(name);\n\t\t\tawait this.remoteStorage.remove(name);\n\t\t\tthrow error;\n\t\t}\n\t\tconst backfillController = new AbortController();\n\t\tthis.backfillAbortControllers.set(name, backfillController);\n\t\tthis.updateOutbox(remote, 0, OutboxMode.Backfill, backfillController.signal).catch((error) => {\n\t\t\tif (backfillController.signal.aborted) return;\n\t\t\tthis.logger.error(\"Backfill failed for remote @RemoteName: @Error\", remote.name, error instanceof Error ? error : new Error(String(error)));\n\t\t}).finally(() => {\n\t\t\tthis.backfillAbortControllers.delete(name);\n\t\t});\n\t\treturn remote;\n\t}\n\ttriggerPull(name) {\n\t\tconst remote = this.remotes.get(name);\n\t\tif (!remote) throw new Error(`Remote with name '${name}' does not exist`);\n\t\tremote.channel.triggerPull();\n\t}\n\tasync remove(name) {\n\t\tconst remote = this.remotes.get(name);\n\t\tif (!remote) throw new Error(`Remote with name '${name}' does not exist`);\n\t\tconst backfillController = this.backfillAbortControllers.get(name);\n\t\tif (backfillController) {\n\t\t\tbackfillController.abort();\n\t\t\tthis.backfillAbortControllers.delete(name);\n\t\t}\n\t\tawait remote.channel.shutdown();\n\t\tawait this.remoteStorage.remove(name);\n\t\tawait this.cursorStorage.remove(name);\n\t\tthis.syncStatusTracker.untrackRemote(name);\n\t\tconst unsub = this.connectionStateUnsubscribes.get(name);\n\t\tif (unsub) {\n\t\t\tunsub();\n\t\t\tthis.connectionStateUnsubscribes.delete(name);\n\t\t}\n\t\tthis.remotes.delete(name);\n\t}\n\tlist() {\n\t\treturn Array.from(this.remotes.values());\n\t}\n\twaitForSync(jobId, signal) {\n\t\treturn this.syncAwaiter.waitForSync(jobId, signal);\n\t}\n\tgetSyncStatus(documentId) {\n\t\treturn this.syncStatusTracker.getStatus(documentId);\n\t}\n\tonSyncStatusChange(callback) {\n\t\treturn this.syncStatusTracker.onChange(callback);\n\t}\n\trecordPlanKeyMapping(planKey, jobId) {\n\t\tif (!this.planKeyToJobUuid.has(planKey) && this.planKeyToJobUuid.size >= PLAN_KEY_TO_JOB_UUID_CAP) {\n\t\t\tconst oldest = this.planKeyToJobUuid.keys().next().value;\n\t\t\tif (oldest !== void 0) this.planKeyToJobUuid.delete(oldest);\n\t\t}\n\t\tthis.planKeyToJobUuid.set(planKey, jobId);\n\t}\n\twireChannelCallbacks(remote) {\n\t\tremote.channel.inbox.onAdded((syncOps) => this.handleInboxAdded(remote, syncOps));\n\t\tthis.syncStatusTracker.trackRemote(remote.name, remote.channel);\n\t\tconst unsubscribe = remote.channel.onConnectionStateChange((snapshot) => {\n\t\t\tthis.eventBus.emit(SyncEventTypes.CONNECTION_STATE_CHANGED, {\n\t\t\t\tremoteName: remote.name,\n\t\t\t\tremoteId: remote.id,\n\t\t\t\tprevious: snapshot.state,\n\t\t\t\tcurrent: snapshot.state,\n\t\t\t\tsnapshot\n\t\t\t}).catch(() => {});\n\t\t});\n\t\tthis.connectionStateUnsubscribes.set(remote.name, unsubscribe);\n\t\tremote.channel.deadLetter.onAdded((syncOps) => {\n\t\t\tfor (const syncOp of syncOps) {\n\t\t\t\tthis.logger.error(\"Dead letter (@remote, @documentId, @jobId, @error, @dependencies)\", remote.name, syncOp.documentId, syncOp.jobId, syncOp.error?.message ?? \"unknown\", syncOp.jobDependencies);\n\t\t\t\tthis.quarantinedDocumentIds.add(syncOp.documentId);\n\t\t\t\tconst record = {\n\t\t\t\t\tid: syncOp.id,\n\t\t\t\t\tjobId: syncOp.jobId,\n\t\t\t\t\tjobDependencies: syncOp.jobDependencies,\n\t\t\t\t\tremoteName: syncOp.remoteName,\n\t\t\t\t\tdocumentId: syncOp.documentId,\n\t\t\t\t\tscopes: syncOp.scopes,\n\t\t\t\t\tbranch: syncOp.branch,\n\t\t\t\t\toperations: syncOp.operations,\n\t\t\t\t\terrorSource: syncOp.error?.source ?? ChannelErrorSource.None,\n\t\t\t\t\terrorMessage: syncOp.error?.error.message ?? \"unknown\"\n\t\t\t\t};\n\t\t\t\tthis.deadLetterStorage.add(record).catch((err) => {\n\t\t\t\t\tthis.logger.error(\"Failed to persist dead letter (@id, @error)\", record.id, err instanceof Error ? err.message : String(err));\n\t\t\t\t});\n\t\t\t\tthis.eventBus.emit(SyncEventTypes.DEAD_LETTER_ADDED, {\n\t\t\t\t\tid: record.id,\n\t\t\t\t\tjobId: record.jobId,\n\t\t\t\t\tremoteName: record.remoteName,\n\t\t\t\t\tdocumentId: record.documentId,\n\t\t\t\t\terrorSource: record.errorSource\n\t\t\t\t}).catch(() => {});\n\t\t\t}\n\t\t\tconst items = remote.channel.deadLetter.items;\n\t\t\tif (items.length > this.config.maxDeadLettersPerRemote) {\n\t\t\t\tconst excessCount = items.length - this.config.maxDeadLettersPerRemote;\n\t\t\t\tconst toEvict = items.slice(0, excessCount);\n\t\t\t\tremote.channel.deadLetter.remove(...toEvict);\n\t\t\t}\n\t\t});\n\t}\n\tasync loadDeadLetters(remote) {\n\t\tlet records;\n\t\ttry {\n\t\t\trecords = (await this.deadLetterStorage.list(remote.name, {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: this.config.maxDeadLettersPerRemote\n\t\t\t})).results;\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to load dead letters for remote (@name, @error)\", remote.name, error instanceof Error ? error.message : String(error));\n\t\t\treturn;\n\t\t}\n\t\tif (records.length === 0) return;\n\t\trecords.reverse();\n\t\tconst syncOps = [];\n\t\tfor (const record of records) {\n\t\t\tconst syncOp = new SyncOperation(record.id, record.jobId, record.jobDependencies, record.remoteName, record.documentId, record.scopes, record.branch, record.operations);\n\t\t\tsyncOp.failed(new ChannelError(record.errorSource, new Error(record.errorMessage)));\n\t\t\tsyncOps.push(syncOp);\n\t\t}\n\t\tremote.channel.deadLetter.add(...syncOps);\n\t\tthis.logger.debug(\"Loaded @count persisted dead letters for remote @name\", records.length, remote.name);\n\t}\n\tgetRemotesForCollection(collectionId) {\n\t\treturn Array.from(this.remotes.values()).filter((remote) => remote.collectionId.key === collectionId);\n\t}\n\tasync processCompleteBatch(batch) {\n\t\tif (this.isShutdown) return;\n\t\tconst collectionIds = [...new Set(Object.values(batch.collectionMemberships).flatMap((collections) => collections))];\n\t\tconst affectedRemotes = [];\n\t\tfor (const collectionId of collectionIds) {\n\t\t\tconst remotes = this.getRemotesForCollection(collectionId);\n\t\t\tfor (const remote of remotes) if (!affectedRemotes.includes(remote)) affectedRemotes.push(remote);\n\t\t}\n\t\tfor (const remote of affectedRemotes) trimMailboxFromBatch(remote.channel.inbox, batch);\n\t\tfor (const remote of affectedRemotes) await this.updateOutbox(remote, remote.channel.outbox.latestOrdinal, OutboxMode.BatchTriggered);\n\t}\n\thandleInboxAdded(remote, syncOps) {\n\t\tif (this.isShutdown) return;\n\t\tconst eligible = syncOps.filter((op) => !this.quarantinedDocumentIds.has(op.documentId));\n\t\tif (eligible.length === 0) return;\n\t\tconst keyed = [];\n\t\tconst nonKeyed = [];\n\t\tfor (const syncOp of eligible) if (syncOp.jobId) keyed.push(syncOp);\n\t\telse nonKeyed.push(syncOp);\n\t\tfor (const syncOp of nonKeyed) this.applyInboxJob(remote, syncOp);\n\t\tif (keyed.length > 0) {\n\t\t\tconst chunks = chunkSyncOperations(keyed.map((syncOp) => ({\n\t\t\t\tremote,\n\t\t\t\tsyncOp\n\t\t\t})), this.config.maxInboxBatchSize);\n\t\t\tthis.processInboxChunks(chunks);\n\t\t}\n\t}\n\tprocessInboxChunks(chunks) {\n\t\tconst next = this.inboxChunkChain.then(async () => {\n\t\t\tfor (const chunk of chunks) {\n\t\t\t\tif (this.isShutdown) return;\n\t\t\t\tawait this.applyInboxBatch(chunk);\n\t\t\t}\n\t\t});\n\t\tthis.inboxChunkChain = next.catch((err) => {\n\t\t\tthis.logger.error(\"Inbox chunk processing failed (@error)\", err instanceof Error ? err.message : String(err));\n\t\t});\n\t\treturn next;\n\t}\n\tasync applyInboxJob(remote, syncOp) {\n\t\tconst operations = syncOp.operations.map((op) => op.operation);\n\t\tlet jobInfo;\n\t\ttry {\n\t\t\tjobInfo = await this.reactor.load(syncOp.documentId, syncOp.branch, operations, this.abortController.signal, { sourceRemote: remote.name });\n\t\t} catch (error) {\n\t\t\tif (this.isShutdown) return;\n\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\tthis.logger.error(\"Failed to load operations from inbox (@remote, @documentId, @error)\", remote.name, syncOp.documentId, err.message);\n\t\t\tconst channelError = new ChannelError(ChannelErrorSource.Inbox, err);\n\t\t\tsyncOp.failed(channelError);\n\t\t\tremote.channel.deadLetter.add(syncOp);\n\t\t\tremote.channel.inbox.remove(syncOp);\n\t\t\treturn;\n\t\t}\n\t\tlet completedJobInfo;\n\t\ttry {\n\t\t\tcompletedJobInfo = await this.awaiter.waitForJob(jobInfo.id, this.abortController.signal);\n\t\t} catch (error) {\n\t\t\tif (this.isShutdown) return;\n\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\tthis.logger.error(\"Failed to wait for job completion (@remote, @documentId, @jobId, @error)\", remote.name, syncOp.documentId, jobInfo.id, err.message);\n\t\t\tconst channelError = new ChannelError(ChannelErrorSource.Inbox, err);\n\t\t\tsyncOp.failed(channelError);\n\t\t\tremote.channel.deadLetter.add(syncOp);\n\t\t\tremote.channel.inbox.remove(syncOp);\n\t\t\treturn;\n\t\t}\n\t\tif (this.isShutdown) return;\n\t\tif (completedJobInfo.status === JobStatus.FAILED) {\n\t\t\tconst errorMessage = completedJobInfo.error?.message || \"Unknown error\";\n\t\t\tthis.logger.error(\"Failed to apply operations from inbox (@remote, @documentId, @jobId, @error)\", remote.name, syncOp.documentId, completedJobInfo.id, errorMessage);\n\t\t\tconst error = new ChannelError(ChannelErrorSource.Inbox, /* @__PURE__ */ new Error(`Failed to apply operations: ${errorMessage}`));\n\t\t\tsyncOp.failed(error);\n\t\t\tremote.channel.deadLetter.add(syncOp);\n\t\t} else syncOp.executed();\n\t\tremote.channel.inbox.remove(syncOp);\n\t}\n\tasync applyInboxBatch(items) {\n\t\tconst sourceRemote = items[0].remote.name;\n\t\tconst chunkKeys = new Set(items.map(({ syncOp }) => syncOp.jobId));\n\t\tconst jobs = items.map(({ syncOp }) => {\n\t\t\tconst dependsOn = [];\n\t\t\tconst externalDeps = [];\n\t\t\tfor (const dep of syncOp.jobDependencies) {\n\t\t\t\tif (!dep) continue;\n\t\t\t\tif (chunkKeys.has(dep)) dependsOn.push(dep);\n\t\t\t\telse {\n\t\t\t\t\tconst uuid = this.planKeyToJobUuid.get(dep);\n\t\t\t\t\tif (uuid !== void 0) externalDeps.push(uuid);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst fifoKey = `${syncOp.documentId}:${syncOp.scopes[0]}:${syncOp.branch}`;\n\t\t\tconst prevUuid = this.lastEnqueuedJobIdByKey.get(fifoKey);\n\t\t\tif (prevUuid !== void 0) externalDeps.push(prevUuid);\n\t\t\treturn {\n\t\t\t\tkey: syncOp.jobId,\n\t\t\t\tdocumentId: syncOp.documentId,\n\t\t\t\tscope: syncOp.scopes[0],\n\t\t\t\tbranch: syncOp.branch,\n\t\t\t\toperations: syncOp.operations.map((op) => op.operation),\n\t\t\t\tdependsOn,\n\t\t\t\texternalDeps\n\t\t\t};\n\t\t});\n\t\tconst request = { jobs };\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.reactor.loadBatch(request, this.abortController.signal, { sourceRemote });\n\t\t} catch (error) {\n\t\t\tif (this.isShutdown) return;\n\t\t\tfor (const { remote, syncOp } of items) {\n\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tsyncOp.failed(new ChannelError(ChannelErrorSource.Inbox, err));\n\t\t\t\tremote.channel.deadLetter.add(syncOp);\n\t\t\t\tremote.channel.inbox.remove(syncOp);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.isShutdown) return;\n\t\tfor (const plan of jobs) {\n\t\t\tif (!(plan.key in result.jobs)) continue;\n\t\t\tconst info = result.jobs[plan.key];\n\t\t\tthis.recordPlanKeyMapping(plan.key, info.id);\n\t\t\tconst fifoKey = `${plan.documentId}:${plan.scope}:${plan.branch}`;\n\t\t\tthis.lastEnqueuedJobIdByKey.set(fifoKey, info.id);\n\t\t}\n\t\tfor (const { remote, syncOp } of items) {\n\t\t\tif (!(syncOp.jobId in result.jobs)) {\n\t\t\t\tthis.logger.error(\"Job key missing from batch load result (@remote, @documentId, @jobId)\", remote.name, syncOp.documentId, syncOp.jobId);\n\t\t\t\tconst error = new ChannelError(ChannelErrorSource.Inbox, /* @__PURE__ */ new Error(`Job key '${syncOp.jobId}' missing from batch load result`));\n\t\t\t\tsyncOp.failed(error);\n\t\t\t\tremote.channel.deadLetter.add(syncOp);\n\t\t\t\tremote.channel.inbox.remove(syncOp);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst jobInfo = result.jobs[syncOp.jobId];\n\t\t\tlet completedJobInfo;\n\t\t\ttry {\n\t\t\t\tcompletedJobInfo = await this.awaiter.waitForJob(jobInfo.id, this.abortController.signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (this.isShutdown) continue;\n\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tsyncOp.failed(new ChannelError(ChannelErrorSource.Inbox, err));\n\t\t\t\tremote.channel.deadLetter.add(syncOp);\n\t\t\t\tremote.channel.inbox.remove(syncOp);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (this.isShutdown) return;\n\t\t\tif (completedJobInfo.status === JobStatus.FAILED) {\n\t\t\t\tconst errorMessage = completedJobInfo.error?.message || \"Unknown error\";\n\t\t\t\tconst channelError = new ChannelError(ChannelErrorSource.Inbox, /* @__PURE__ */ new Error(`Failed to apply operations: ${errorMessage}`));\n\t\t\t\tsyncOp.failed(channelError);\n\t\t\t\tremote.channel.deadLetter.add(syncOp);\n\t\t\t} else syncOp.executed();\n\t\t\tremote.channel.inbox.remove(syncOp);\n\t\t}\n\t}\n\tasync updateOutbox(remote, ackOrdinal, mode = OutboxMode.Backfill, signal) {\n\t\tconst composedSignal = signal ? AbortSignal.any([signal, this.abortController.signal]) : this.abortController.signal;\n\t\tlet maxOrdinal = ackOrdinal;\n\t\tconst lastJobByDoc = /* @__PURE__ */ new Map();\n\t\tlet prevChainJobId;\n\t\tconst sinceTimestamp = remote.options.sinceTimestampUtcMs;\n\t\tconst emitBatches = (operations) => {\n\t\t\tif (operations.length === 0) return;\n\t\t\tconst batches = batchOperationsByDocument(operations);\n\t\t\tconst syncOps = [];\n\t\t\tfor (const batch of batches) {\n\t\t\t\tconst jobId = crypto.randomUUID();\n\t\t\t\tconst prevJobId = lastJobByDoc.get(batch.documentId);\n\t\t\t\tconst deps = [];\n\t\t\t\tif (prevJobId) deps.push(prevJobId);\n\t\t\t\tif (mode === OutboxMode.BatchTriggered && prevChainJobId && prevChainJobId !== prevJobId) deps.push(prevChainJobId);\n\t\t\t\tconst syncOp = new SyncOperation(crypto.randomUUID(), jobId, deps, remote.name, batch.documentId, [batch.scope], batch.branch, batch.operations);\n\t\t\t\tsyncOps.push(syncOp);\n\t\t\t\tlastJobByDoc.set(batch.documentId, jobId);\n\t\t\t\tif (mode === OutboxMode.BatchTriggered) prevChainJobId = jobId;\n\t\t\t}\n\t\t\tremote.channel.outbox.add(...syncOps);\n\t\t};\n\t\tlet page = await this.operationIndex.find(remote.collectionId.key, ackOrdinal, { excludeSourceRemote: remote.name }, void 0, composedSignal);\n\t\tlet carry = [];\n\t\tlet hasMore;\n\t\tdo {\n\t\t\tif (composedSignal.aborted) return;\n\t\t\tfor (const entry of page.results) maxOrdinal = Math.max(maxOrdinal, entry.ordinal ?? 0);\n\t\t\tlet operations = page.results.map((entry) => toOperationWithContext(entry));\n\t\t\tif (carry.length > 0) {\n\t\t\t\toperations = [...carry, ...operations];\n\t\t\t\tcarry = [];\n\t\t\t}\n\t\t\tif (sinceTimestamp && sinceTimestamp !== \"0\") operations = operations.filter((op) => op.operation.timestampUtcMs >= sinceTimestamp);\n\t\t\toperations = filterOperations(operations, remote.filter);\n\t\t\toperations = operations.filter((op) => !this.quarantinedDocumentIds.has(op.context.documentId));\n\t\t\thasMore = !!page.next;\n\t\t\tif (operations.length > 0) {\n\t\t\t\toperations.sort((a, b) => {\n\t\t\t\t\tif (a.context.documentId !== b.context.documentId) return a.context.documentId < b.context.documentId ? -1 : 1;\n\t\t\t\t\tif (a.context.scope !== b.context.scope) return a.context.scope < b.context.scope ? -1 : 1;\n\t\t\t\t\treturn a.context.ordinal - b.context.ordinal;\n\t\t\t\t});\n\t\t\t\tif (hasMore) {\n\t\t\t\t\tconst split = splitTrailingSameTimestampRun(operations);\n\t\t\t\t\tcarry = split.carry;\n\t\t\t\t\temitBatches(split.emit);\n\t\t\t\t} else emitBatches(operations);\n\t\t\t}\n\t\t\tif (hasMore) page = await page.next();\n\t\t} while (hasMore);\n\t\tif (carry.length > 0) emitBatches(carry);\n\t\tremote.channel.outbox.advanceOrdinal(maxOrdinal);\n\t}\n};\n//#endregion\n//#region src/sync/sync-builder.ts\nvar SyncBuilder = class {\n\tchannelFactory;\n\tremoteStorage;\n\tcursorStorage;\n\tdeadLetterStorage;\n\tconfig = {};\n\twithChannelFactory(factory) {\n\t\tthis.channelFactory = factory;\n\t\treturn this;\n\t}\n\twithRemoteStorage(storage) {\n\t\tthis.remoteStorage = storage;\n\t\treturn this;\n\t}\n\twithCursorStorage(storage) {\n\t\tthis.cursorStorage = storage;\n\t\treturn this;\n\t}\n\twithDeadLetterStorage(storage) {\n\t\tthis.deadLetterStorage = storage;\n\t\treturn this;\n\t}\n\twithMaxDeadLettersPerRemote(limit) {\n\t\tthis.config.maxDeadLettersPerRemote = limit;\n\t\treturn this;\n\t}\n\twithMaxInboxBatchSize(limit) {\n\t\tthis.config.maxInboxBatchSize = limit;\n\t\treturn this;\n\t}\n\tbuild(reactor, logger, operationIndex, eventBus, db, driveContainerTypes) {\n\t\treturn this.buildModule(reactor, logger, operationIndex, eventBus, db, driveContainerTypes).syncManager;\n\t}\n\tbuildModule(reactor, logger, operationIndex, eventBus, db, driveContainerTypes) {\n\t\tif (!this.channelFactory) throw new Error(\"Channel factory is required\");\n\t\tconst remoteStorage = this.remoteStorage ?? new KyselySyncRemoteStorage(db);\n\t\tconst cursorStorage = this.cursorStorage ?? new KyselySyncCursorStorage(db);\n\t\tconst deadLetterStorage = this.deadLetterStorage ?? new KyselySyncDeadLetterStorage(db);\n\t\tconst syncManager = new SyncManager(logger, remoteStorage, cursorStorage, deadLetterStorage, this.channelFactory, operationIndex, reactor, eventBus, driveContainerTypes, this.config);\n\t\treturn {\n\t\t\tremoteStorage,\n\t\t\tcursorStorage,\n\t\t\tdeadLetterStorage,\n\t\t\tchannelFactory: this.channelFactory,\n\t\t\tsyncManager\n\t\t};\n\t}\n};\n//#endregion\n//#region src/core/create-default-database.ts\nasync function createDefaultDatabase() {\n\tconst { Kysely } = await import(\"kysely\");\n\tconst { PGlite } = await import(\"@electric-sql/pglite\");\n\tconst { PGliteDialect } = await import(\"kysely-pglite-dialect\");\n\treturn new Kysely({ dialect: new PGliteDialect(new PGlite()) });\n}\n//#endregion\n//#region src/shared/factories.ts\n/**\n* Factory method to create a ShutdownStatus that can be updated\n*\n* @param initialState - Initial shutdown state (default: false)\n* @returns A tuple of [ShutdownStatus, setShutdown function, setCompleted function]\n*/\nfunction createMutableShutdownStatus(initialState = false) {\n\tlet shutdownState = initialState;\n\tlet completedPromise = Promise.resolve();\n\tconst status = {\n\t\tget isShutdown() {\n\t\t\treturn shutdownState;\n\t\t},\n\t\tget completed() {\n\t\t\treturn completedPromise;\n\t\t}\n\t};\n\tconst setShutdown = (value) => {\n\t\tshutdownState = value;\n\t};\n\tconst setCompleted = (promise) => {\n\t\tcompletedPromise = promise;\n\t};\n\treturn [\n\t\tstatus,\n\t\tsetShutdown,\n\t\tsetCompleted\n\t];\n}\n//#endregion\n//#region src/core/types.ts\nvar AbortError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message || \"Aborted\");\n\t\tthis.name = \"AbortError\";\n\t}\n};\n//#endregion\n//#region src/core/reactor.ts\n/**\n* This class implements the IReactor interface and serves as the main entry point\n* for the new Reactor architecture.\n*/\nvar Reactor = class {\n\tlogger;\n\tdocumentModelRegistry;\n\tshutdownStatus;\n\tsetShutdown;\n\tsetCompleted;\n\tqueue;\n\tjobTracker;\n\treadModelCoordinator;\n\tfeatures;\n\tdocumentView;\n\tdocumentIndexer;\n\toperationStore;\n\teventBus;\n\texecutorManager;\n\tconstructor(logger, documentModelRegistry, queue, jobTracker, readModelCoordinator, features, documentView, documentIndexer, operationStore, eventBus, executorManager) {\n\t\tthis.logger = logger;\n\t\tthis.documentModelRegistry = documentModelRegistry;\n\t\tthis.queue = queue;\n\t\tthis.jobTracker = jobTracker;\n\t\tthis.readModelCoordinator = readModelCoordinator;\n\t\tthis.features = features;\n\t\tthis.documentView = documentView;\n\t\tthis.documentIndexer = documentIndexer;\n\t\tthis.operationStore = operationStore;\n\t\tthis.eventBus = eventBus;\n\t\tthis.executorManager = executorManager;\n\t\tconst [status, setShutdown, setCompleted] = createMutableShutdownStatus(false);\n\t\tthis.shutdownStatus = status;\n\t\tthis.setShutdown = setShutdown;\n\t\tthis.setCompleted = setCompleted;\n\t\tthis.eventBus.subscribe(ReactorEventTypes.JOB_FAILED, (_type, event) => {\n\t\t\tthis.logger.error(\"Job @JobId failed with @Message: @Job\", event.jobId, event.error.message, event.job);\n\t\t});\n\t\tthis.readModelCoordinator.start();\n\t}\n\tkill() {\n\t\tthis.logger.verbose(\"kill()\");\n\t\tif (this.shutdownStatus.isShutdown) return this.shutdownStatus;\n\t\tthis.setShutdown(true);\n\t\tconst shutdownAsync = async () => {\n\t\t\tawait this.executorManager.stop(true);\n\t\t\tthis.readModelCoordinator.stop();\n\t\t\tthis.jobTracker.shutdown();\n\t\t};\n\t\tthis.setCompleted(shutdownAsync());\n\t\treturn this.shutdownStatus;\n\t}\n\tgetDocumentModels(namespace, paging, signal) {\n\t\tthis.logger.verbose(\"getDocumentModels(@namespace, @paging)\", namespace, paging);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tconst filteredModels = this.documentModelRegistry.getAllModules().filter((module) => !namespace || module.documentModel.global.id.startsWith(namespace));\n\t\tconst startIndex = paging ? parseInt(paging.cursor) || 0 : 0;\n\t\tconst limit = paging?.limit || filteredModels.length;\n\t\tconst pagedModels = filteredModels.slice(startIndex, startIndex + limit);\n\t\tconst hasMore = startIndex + limit < filteredModels.length;\n\t\tconst nextCursor = hasMore ? String(startIndex + limit) : void 0;\n\t\treturn Promise.resolve({\n\t\t\tresults: pagedModels,\n\t\t\toptions: paging || {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: filteredModels.length\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.getDocumentModels(namespace, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t});\n\t}\n\tasync get(id, view, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"get(@id, @view)\", id, view);\n\t\treturn await this.documentView.get(id, view, consistencyToken, signal);\n\t}\n\tasync getBySlug(slug, view, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"getBySlug(@slug, @view)\", slug, view);\n\t\tconst documentId = await this.documentView.resolveSlug(slug, view, consistencyToken, signal);\n\t\tif (!documentId) throw new Error(`Document not found with slug: ${slug}`);\n\t\treturn await this.get(documentId, view, consistencyToken, signal);\n\t}\n\tasync getByIdOrSlug(identifier, view, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"getByIdOrSlug(@identifier, @view)\", identifier, view);\n\t\treturn await this.documentView.getByIdOrSlug(identifier, view, consistencyToken, signal);\n\t}\n\tasync getOutgoingRelationships(sourceId, relationshipType, consistencyToken, signal) {\n\t\tconst relationships = await this.documentIndexer.getOutgoing(sourceId, [relationshipType], void 0, consistencyToken, signal);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\treturn relationships.results.map((rel) => rel.targetId);\n\t}\n\tasync getIncomingRelationships(targetId, relationshipType, consistencyToken, signal) {\n\t\tconst relationships = await this.documentIndexer.getIncoming(targetId, [relationshipType], void 0, consistencyToken, signal);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\treturn relationships.results.map((rel) => rel.sourceId);\n\t}\n\tasync getOperations(documentId, view, filter, paging, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"getOperations(@documentId, @view, @filter, @paging)\", documentId, view, filter, paging);\n\t\tconst branch = view?.branch || \"main\";\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tconst allScopes = Object.keys(revisions.revision);\n\t\tconst result = {};\n\t\tfor (const scope of allScopes) {\n\t\t\tif (!matchesScope(view, scope)) continue;\n\t\t\tthrowIfAborted(signal, () => new AbortError());\n\t\t\tconst scopeResult = await this.operationStore.getSince(documentId, scope, branch, -1, filter, paging, signal);\n\t\t\tresult[scope] = {\n\t\t\t\tresults: scopeResult.results,\n\t\t\t\toptions: scopeResult.options,\n\t\t\t\tnextCursor: scopeResult.nextCursor,\n\t\t\t\tnext: scopeResult.next ? async () => {\n\t\t\t\t\treturn (await this.getOperations(documentId, view, filter, {\n\t\t\t\t\t\tcursor: scopeResult.nextCursor,\n\t\t\t\t\t\tlimit: scopeResult.options.limit\n\t\t\t\t\t}, consistencyToken, signal))[scope];\n\t\t\t\t} : void 0\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t}\n\tasync find(search, view, paging, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"find(@search, @view, @paging)\", search, view, paging);\n\t\tlet results;\n\t\tif (search.ids) {\n\t\t\tif (search.slugs && search.slugs.length > 0) throw new Error(\"Cannot use both ids and slugs in the same search\");\n\t\t\tresults = await this.findByIds(search.ids, view, paging, consistencyToken, signal);\n\t\t\tif (search.type) results = filterByType(results, search.type);\n\t\t} else if (search.slugs) {\n\t\t\tresults = await this.findBySlugs(search.slugs, view, paging, consistencyToken, signal);\n\t\t\tif (search.type) results = filterByType(results, search.type);\n\t\t} else if (search.parentId) {\n\t\t\tresults = await this.findByParentId(search.parentId, view, paging, consistencyToken, signal);\n\t\t\tif (search.type) results = filterByType(results, search.type);\n\t\t} else if (search.type) results = await this.findByType(search.type, view, paging, consistencyToken, signal);\n\t\telse throw new Error(\"No search criteria provided\");\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\treturn results;\n\t}\n\tasync create(document, signer, signal, meta) {\n\t\tthis.logger.verbose(\"create(@id, @type, @slug)\", document.header.id, document.header.documentType, document.header.slug);\n\t\tconst createdAtUtcIso = (/* @__PURE__ */ new Date()).toISOString();\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tlet actions = [createDocumentAction({\n\t\t\tmodel: document.header.documentType,\n\t\t\tversion: 0,\n\t\t\tdocumentId: document.header.id,\n\t\t\tsigning: {\n\t\t\t\tsignature: document.header.id,\n\t\t\t\tpublicKey: document.header.sig.publicKey,\n\t\t\t\tnonce: document.header.sig.nonce,\n\t\t\t\tcreatedAtUtcIso: document.header.createdAtUtcIso,\n\t\t\t\tdocumentType: document.header.documentType\n\t\t\t},\n\t\t\tslug: document.header.slug,\n\t\t\tname: document.header.name,\n\t\t\tbranch: document.header.branch,\n\t\t\tmeta: document.header.meta,\n\t\t\tprotocolVersions: document.header.protocolVersions ?? { \"base-reducer\": 2 }\n\t\t}), upgradeDocumentAction({\n\t\t\tdocumentId: document.header.id,\n\t\t\tmodel: document.header.documentType,\n\t\t\tfromVersion: 0,\n\t\t\ttoVersion: document.state.document.version,\n\t\t\tinitialState: document.state\n\t\t})];\n\t\tif (signer) actions = await signActions(actions, signer, signal);\n\t\tconst jobId = v4();\n\t\tconst jobMeta = buildSingleJobMeta(jobId, meta);\n\t\tconst job = {\n\t\t\tid: jobId,\n\t\t\tkind: \"mutation\",\n\t\t\tdocumentId: document.header.id,\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\",\n\t\t\tactions,\n\t\t\toperations: [],\n\t\t\tcreatedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tqueueHint: [],\n\t\t\tmaxRetries: 3,\n\t\t\terrorHistory: [],\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tconst jobInfo = {\n\t\t\tid: jobId,\n\t\t\tdocumentId: job.documentId,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tcreatedAtUtcIso,\n\t\t\tconsistencyToken: {\n\t\t\t\tversion: 1,\n\t\t\t\tcreatedAtUtcIso,\n\t\t\t\tcoordinates: []\n\t\t\t},\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tthis.jobTracker.registerJob(jobInfo);\n\t\tthis.emitJobPending(jobInfo.id, jobMeta);\n\t\tawait this.queue.enqueue(job);\n\t\treturn jobInfo;\n\t}\n\tasync deleteDocument(id, signer, signal, meta) {\n\t\tthis.logger.verbose(\"deleteDocument(@id)\", id);\n\t\tconst createdAtUtcIso = (/* @__PURE__ */ new Date()).toISOString();\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tlet action = deleteDocumentAction(id);\n\t\tif (signer) action = await signAction(action, signer, signal);\n\t\tconst jobId = v4();\n\t\tconst jobMeta = buildSingleJobMeta(jobId, meta);\n\t\tconst job = {\n\t\t\tid: jobId,\n\t\t\tkind: \"mutation\",\n\t\t\tdocumentId: id,\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\",\n\t\t\tactions: [action],\n\t\t\toperations: [],\n\t\t\tcreatedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tqueueHint: [],\n\t\t\tmaxRetries: 3,\n\t\t\terrorHistory: [],\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tconst jobInfo = {\n\t\t\tid: jobId,\n\t\t\tdocumentId: job.documentId,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tcreatedAtUtcIso,\n\t\t\tconsistencyToken: {\n\t\t\t\tversion: 1,\n\t\t\t\tcreatedAtUtcIso,\n\t\t\t\tcoordinates: []\n\t\t\t},\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tthis.jobTracker.registerJob(jobInfo);\n\t\tthis.emitJobPending(jobInfo.id, jobMeta);\n\t\tawait this.queue.enqueue(job);\n\t\treturn jobInfo;\n\t}\n\tasync execute(docId, branch, actions, signal, meta) {\n\t\tthis.logger.verbose(\"execute(@docId, @branch, @actions)\", docId, branch, actions);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tconst createdAtUtcIso = (/* @__PURE__ */ new Date()).toISOString();\n\t\tconst scope = getSharedActionScope(actions);\n\t\tconst jobId = v4();\n\t\tconst jobMeta = buildSingleJobMeta(jobId, meta);\n\t\tconst job = {\n\t\t\tid: jobId,\n\t\t\tkind: \"mutation\",\n\t\t\tdocumentId: docId,\n\t\t\tscope,\n\t\t\tbranch,\n\t\t\tactions,\n\t\t\toperations: [],\n\t\t\tcreatedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tqueueHint: [],\n\t\t\tmaxRetries: 3,\n\t\t\terrorHistory: [],\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tconst jobInfo = {\n\t\t\tid: jobId,\n\t\t\tdocumentId: job.documentId,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tcreatedAtUtcIso,\n\t\t\tconsistencyToken: {\n\t\t\t\tversion: 1,\n\t\t\t\tcreatedAtUtcIso,\n\t\t\t\tcoordinates: []\n\t\t\t},\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tthis.jobTracker.registerJob(jobInfo);\n\t\tthis.emitJobPending(jobInfo.id, jobMeta);\n\t\tawait this.queue.enqueue(job);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\treturn jobInfo;\n\t}\n\tasync load(docId, branch, operations, signal, meta) {\n\t\tthis.logger.verbose(\"load(@docId, @branch, @count, @operations)\", docId, branch, operations.length, operations);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tif (operations.length === 0) throw new Error(\"load requires at least one operation\");\n\t\tconst scope = getSharedOperationScope(operations);\n\t\tconst createdAtUtcIso = (/* @__PURE__ */ new Date()).toISOString();\n\t\tconst jobId = v4();\n\t\tconst jobMeta = buildSingleJobMeta(jobId, meta);\n\t\tconst job = {\n\t\t\tid: jobId,\n\t\t\tkind: \"load\",\n\t\t\tdocumentId: docId,\n\t\t\tscope,\n\t\t\tbranch,\n\t\t\tactions: [],\n\t\t\toperations,\n\t\t\tcreatedAt: createdAtUtcIso,\n\t\t\tqueueHint: [],\n\t\t\tmaxRetries: 3,\n\t\t\terrorHistory: [],\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tconst jobInfo = {\n\t\t\tid: jobId,\n\t\t\tdocumentId: job.documentId,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tcreatedAtUtcIso,\n\t\t\tconsistencyToken: {\n\t\t\t\tversion: 1,\n\t\t\t\tcreatedAtUtcIso,\n\t\t\t\tcoordinates: []\n\t\t\t},\n\t\t\tmeta: jobMeta\n\t\t};\n\t\tthis.jobTracker.registerJob(jobInfo);\n\t\tthis.emitJobPending(jobInfo.id, jobMeta);\n\t\tawait this.queue.enqueue(job);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\treturn jobInfo;\n\t}\n\tasync executeBatch(request, signal, meta) {\n\t\tthis.logger.verbose(\"executeBatch(@count jobs)\", request.jobs.length);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tvalidateBatchRequest(request.jobs);\n\t\tfor (const jobPlan of request.jobs) validateActionScopes(jobPlan);\n\t\tconst createdAtUtcIso = (/* @__PURE__ */ new Date()).toISOString();\n\t\tconst planKeyToJobId = /* @__PURE__ */ new Map();\n\t\tfor (const jobPlan of request.jobs) planKeyToJobId.set(jobPlan.key, v4());\n\t\tconst batchId = v4();\n\t\tconst batchJobIds = [...planKeyToJobId.values()];\n\t\tconst batchMeta = {\n\t\t\t...meta,\n\t\t\tbatchId,\n\t\t\tbatchJobIds\n\t\t};\n\t\tconst jobInfos = /* @__PURE__ */ new Map();\n\t\tfor (const jobPlan of request.jobs) {\n\t\t\tconst jobInfo = {\n\t\t\t\tid: planKeyToJobId.get(jobPlan.key),\n\t\t\t\tdocumentId: jobPlan.documentId,\n\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\tcreatedAtUtcIso,\n\t\t\t\tconsistencyToken: {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcreatedAtUtcIso,\n\t\t\t\t\tcoordinates: []\n\t\t\t\t},\n\t\t\t\tmeta: batchMeta\n\t\t\t};\n\t\t\tthis.jobTracker.registerJob(jobInfo);\n\t\t\tthis.emitJobPending(jobInfo.id, batchMeta);\n\t\t\tjobInfos.set(jobPlan.key, jobInfo);\n\t\t}\n\t\tconst sortedKeys = topologicalSort(request.jobs);\n\t\tconst enqueuedKeys = [];\n\t\ttry {\n\t\t\tfor (const key of sortedKeys) {\n\t\t\t\tthrowIfAborted(signal, () => new AbortError());\n\t\t\t\tconst jobPlan = request.jobs.find((j) => j.key === key);\n\t\t\t\tconst jobId = planKeyToJobId.get(key);\n\t\t\t\tconst queueHint = jobPlan.dependsOn.map((depKey) => planKeyToJobId.get(depKey));\n\t\t\t\tconst job = {\n\t\t\t\t\tid: jobId,\n\t\t\t\t\tkind: \"mutation\",\n\t\t\t\t\tdocumentId: jobPlan.documentId,\n\t\t\t\t\tscope: jobPlan.scope,\n\t\t\t\t\tbranch: jobPlan.branch,\n\t\t\t\t\tactions: jobPlan.actions,\n\t\t\t\t\toperations: [],\n\t\t\t\t\tcreatedAt: createdAtUtcIso,\n\t\t\t\t\tqueueHint,\n\t\t\t\t\tmaxRetries: 3,\n\t\t\t\t\terrorHistory: [],\n\t\t\t\t\tmeta: batchMeta\n\t\t\t\t};\n\t\t\t\tawait this.queue.enqueue(job);\n\t\t\t\tenqueuedKeys.push(key);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfor (const key of enqueuedKeys) {\n\t\t\t\tconst jobId = planKeyToJobId.get(key);\n\t\t\t\ttry {\n\t\t\t\t\tawait this.queue.remove(jobId);\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tfor (const jobInfo of jobInfos.values()) this.jobTracker.markFailed(jobInfo.id, toErrorInfo$1(\"Batch enqueue failed\"));\n\t\t\tthrow error;\n\t\t}\n\t\treturn { jobs: Object.fromEntries(jobInfos) };\n\t}\n\tasync loadBatch(request, signal, meta) {\n\t\tthis.logger.verbose(\"loadBatch(@count jobs)\", request.jobs.length);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tvalidateBatchLoadRequest(request.jobs);\n\t\tfor (const jobPlan of request.jobs) validateOperationScopes(jobPlan);\n\t\tconst createdAtUtcIso = (/* @__PURE__ */ new Date()).toISOString();\n\t\tconst planKeyToJobId = /* @__PURE__ */ new Map();\n\t\tfor (const jobPlan of request.jobs) planKeyToJobId.set(jobPlan.key, v4());\n\t\tconst batchId = v4();\n\t\tconst batchJobIds = [...planKeyToJobId.values()];\n\t\tconst batchMeta = {\n\t\t\t...meta,\n\t\t\tbatchId,\n\t\t\tbatchJobIds\n\t\t};\n\t\tconst jobInfos = /* @__PURE__ */ new Map();\n\t\tfor (const jobPlan of request.jobs) {\n\t\t\tconst jobInfo = {\n\t\t\t\tid: planKeyToJobId.get(jobPlan.key),\n\t\t\t\tdocumentId: jobPlan.documentId,\n\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\tcreatedAtUtcIso,\n\t\t\t\tconsistencyToken: {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcreatedAtUtcIso,\n\t\t\t\t\tcoordinates: []\n\t\t\t\t},\n\t\t\t\tmeta: batchMeta\n\t\t\t};\n\t\t\tthis.jobTracker.registerJob(jobInfo);\n\t\t\tthis.emitJobPending(jobInfo.id, batchMeta);\n\t\t\tjobInfos.set(jobPlan.key, jobInfo);\n\t\t}\n\t\tconst sortedKeys = topologicalSort(request.jobs);\n\t\tconst enqueuedKeys = [];\n\t\ttry {\n\t\t\tfor (const key of sortedKeys) {\n\t\t\t\tthrowIfAborted(signal, () => new AbortError());\n\t\t\t\tconst jobPlan = request.jobs.find((j) => j.key === key);\n\t\t\t\tconst jobId = planKeyToJobId.get(key);\n\t\t\t\tconst queueHint = [...jobPlan.dependsOn.map((depKey) => planKeyToJobId.get(depKey)), ...jobPlan.externalDeps];\n\t\t\t\tconst job = {\n\t\t\t\t\tid: jobId,\n\t\t\t\t\tkind: \"load\",\n\t\t\t\t\tdocumentId: jobPlan.documentId,\n\t\t\t\t\tscope: jobPlan.scope,\n\t\t\t\t\tbranch: jobPlan.branch,\n\t\t\t\t\tactions: [],\n\t\t\t\t\toperations: jobPlan.operations,\n\t\t\t\t\tcreatedAt: createdAtUtcIso,\n\t\t\t\t\tqueueHint,\n\t\t\t\t\tmaxRetries: 3,\n\t\t\t\t\terrorHistory: [],\n\t\t\t\t\tmeta: batchMeta\n\t\t\t\t};\n\t\t\t\tawait this.queue.enqueue(job);\n\t\t\t\tenqueuedKeys.push(key);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfor (const key of enqueuedKeys) {\n\t\t\t\tconst jobId = planKeyToJobId.get(key);\n\t\t\t\ttry {\n\t\t\t\t\tawait this.queue.remove(jobId);\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tfor (const jobInfo of jobInfos.values()) this.jobTracker.markFailed(jobInfo.id, toErrorInfo$1(\"Batch enqueue failed\"));\n\t\t\tthrow error;\n\t\t}\n\t\treturn { jobs: Object.fromEntries(jobInfos) };\n\t}\n\tasync addRelationship(sourceId, targetId, relationshipType, branch = \"main\", signer, signal) {\n\t\tthis.logger.verbose(\"addRelationship(@sourceId, @targetId, @relationshipType, @branch)\", sourceId, targetId, relationshipType, branch);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tlet actions = [addRelationshipAction(sourceId, targetId, relationshipType)];\n\t\tif (signer) actions = await signActions(actions, signer, signal);\n\t\treturn await this.execute(sourceId, branch, actions, signal);\n\t}\n\tasync removeRelationship(sourceId, targetId, relationshipType, branch = \"main\", signer, signal) {\n\t\tthis.logger.verbose(\"removeRelationship(@sourceId, @targetId, @relationshipType, @branch)\", sourceId, targetId, relationshipType, branch);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tlet actions = [removeRelationshipAction(sourceId, targetId, relationshipType)];\n\t\tif (signer) actions = await signActions(actions, signer, signal);\n\t\treturn await this.execute(sourceId, branch, actions, signal);\n\t}\n\tgetJobStatus(jobId, signal) {\n\t\tthis.logger.verbose(\"getJobStatus(@jobId)\", jobId);\n\t\tthrowIfAborted(signal, () => new AbortError());\n\t\tconst jobInfo = this.jobTracker.getJobStatus(jobId);\n\t\tif (!jobInfo) {\n\t\t\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\treturn Promise.resolve({\n\t\t\t\tid: jobId,\n\t\t\t\tdocumentId: \"\",\n\t\t\t\tstatus: JobStatus.FAILED,\n\t\t\t\tcreatedAtUtcIso: now,\n\t\t\t\tcompletedAtUtcIso: now,\n\t\t\t\terror: toErrorInfo$1(\"Job not found\"),\n\t\t\t\tconsistencyToken: {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcreatedAtUtcIso: now,\n\t\t\t\t\tcoordinates: []\n\t\t\t\t},\n\t\t\t\tmeta: {\n\t\t\t\t\tbatchId: jobId,\n\t\t\t\t\tbatchJobIds: [jobId]\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn Promise.resolve(jobInfo);\n\t}\n\tasync findByIds(ids, view, paging, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"findByIds(@count ids)\", ids.length);\n\t\tconst startIndex = paging?.cursor ? parseInt(paging.cursor) || 0 : 0;\n\t\tconst limit = paging?.limit || ids.length;\n\t\tconst pagedIds = ids.slice(startIndex, startIndex + limit);\n\t\tconst results = await this.documentView.getMany(pagedIds, view, consistencyToken, signal);\n\t\tconst nextCursor = startIndex + limit < ids.length ? String(startIndex + limit) : void 0;\n\t\treturn {\n\t\t\tresults,\n\t\t\toptions: paging || {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: ids.length\n\t\t\t},\n\t\t\tnextCursor\n\t\t};\n\t}\n\tasync findBySlugs(slugs, view, paging, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"findBySlugs(@count slugs)\", slugs.length);\n\t\tconst ids = await this.documentView.resolveSlugs(slugs, view, consistencyToken, signal);\n\t\treturn await this.findByIds(ids, view, paging, consistencyToken, signal);\n\t}\n\tasync findByParentId(parentId, view, paging, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"findByParentId(@parentId)\", parentId);\n\t\tconst ids = (await this.documentIndexer.getOutgoing(parentId, [\"child\"], paging, consistencyToken, signal)).results.map((rel) => rel.targetId);\n\t\treturn await this.findByIds(ids, view, paging, void 0, signal);\n\t}\n\tasync findByType(type, view, paging, consistencyToken, signal) {\n\t\tthis.logger.verbose(\"findByType(@type)\", type);\n\t\treturn await this.documentView.findByType(type, view, paging, consistencyToken, signal);\n\t}\n\temitJobPending(jobId, meta) {\n\t\tconst event = {\n\t\t\tjobId,\n\t\t\tjobMeta: meta\n\t\t};\n\t\tthis.eventBus.emit(ReactorEventTypes.JOB_PENDING, event).catch(() => {});\n\t}\n};\n//#endregion\n//#region src/core/reactor-builder.ts\nvar ReactorBuilder = class {\n\tlogger;\n\tdocumentModels = [];\n\tupgradeManifests = [];\n\tfeatures = { legacyStorageEnabled: false };\n\treadModels = [];\n\treadModelFactories = [];\n\texecutorManager;\n\texecutorConfig = {};\n\twriteCacheConfig;\n\tmigrationStrategy = \"auto\";\n\tsyncBuilder;\n\teventBus;\n\treadModelCoordinator;\n\tsignatureVerifier;\n\tkyselyInstance;\n\tsignalHandlersEnabled = false;\n\tqueueInstance;\n\tchannelScheme;\n\tjwtHandler;\n\tdocumentModelLoader;\n\tshutdownHooks = [];\n\tdriveContainerTypes = DEFAULT_DRIVE_CONTAINER_TYPES;\n\tdocumentModelSpecs = [];\n\tworkerPoolConfig;\n\tresolvedModelManifest;\n\tworkerDbConfig;\n\tworkerSignatureVerifierSpec;\n\tworkerFactory;\n\tprojectionShardConfig;\n\tprojectionWorkerFactory;\n\tinstrumentedPools = [];\n\twithLogger(logger) {\n\t\tthis.logger = logger;\n\t\treturn this;\n\t}\n\twithDocumentModels(models) {\n\t\tthis.documentModels = models;\n\t\treturn this;\n\t}\n\twithUpgradeManifests(manifests) {\n\t\tthis.upgradeManifests = manifests;\n\t\treturn this;\n\t}\n\twithFeatures(features) {\n\t\tthis.features = {\n\t\t\t...this.features,\n\t\t\t...features\n\t\t};\n\t\treturn this;\n\t}\n\twithReadModel(readModel) {\n\t\tthis.readModels.push(readModel);\n\t\treturn this;\n\t}\n\t/**\n\t* Register a factory that builds a pre-ready read model after the reactor's\n\t* internal `operationIndex`, `writeCache`, and processor-manager consistency\n\t* tracker are constructed. Use this for read models (e.g. `BaseReadModel`\n\t* subclasses) that need those dependencies and therefore cannot be built\n\t* before calling `buildModule()`.\n\t*/\n\twithReadModelFactory(factory) {\n\t\tthis.readModelFactories.push(factory);\n\t\treturn this;\n\t}\n\twithReadModelCoordinator(readModelCoordinator) {\n\t\tthis.readModelCoordinator = readModelCoordinator;\n\t\treturn this;\n\t}\n\twithExecutor(executor) {\n\t\tthis.executorManager = executor;\n\t\treturn this;\n\t}\n\twithExecutorConfig(config) {\n\t\tthis.executorConfig = {\n\t\t\t...this.executorConfig,\n\t\t\t...config\n\t\t};\n\t\treturn this;\n\t}\n\twithWriteCacheConfig(config) {\n\t\tthis.writeCacheConfig = config;\n\t\treturn this;\n\t}\n\twithDriveContainerTypes(types) {\n\t\tthis.driveContainerTypes = new Set(types);\n\t\treturn this;\n\t}\n\twithMigrationStrategy(strategy) {\n\t\tthis.migrationStrategy = strategy;\n\t\treturn this;\n\t}\n\twithSync(syncBuilder) {\n\t\tthis.syncBuilder = syncBuilder;\n\t\treturn this;\n\t}\n\twithEventBus(eventBus) {\n\t\tthis.eventBus = eventBus;\n\t\treturn this;\n\t}\n\twithSignatureVerifier(verifier) {\n\t\tthis.signatureVerifier = verifier;\n\t\treturn this;\n\t}\n\twithKysely(kysely) {\n\t\tthis.kyselyInstance = kysely;\n\t\treturn this;\n\t}\n\t/**\n\t* Register an externally-constructed pg.Pool's {@link PoolInstrumentation}\n\t* so it surfaces through {@link ReactorModule.pools}. Use this when the\n\t* caller built the pool itself (e.g. the in-process bench host wiring) so\n\t* pool acquire-wait and pool-stat metrics still emit. The builder also\n\t* registers any pool it constructs internally via {@link createPostgresDatabase}.\n\t*/\n\twithInstrumentedPool(instrumentation) {\n\t\tthis.instrumentedPools.push(instrumentation);\n\t\treturn this;\n\t}\n\twithQueue(queue) {\n\t\tthis.queueInstance = queue;\n\t\treturn this;\n\t}\n\twithChannelScheme(scheme) {\n\t\tthis.channelScheme = scheme;\n\t\treturn this;\n\t}\n\twithJwtHandler(handler) {\n\t\tthis.jwtHandler = handler;\n\t\treturn this;\n\t}\n\twithDocumentModelLoader(loader) {\n\t\tthis.documentModelLoader = loader;\n\t\treturn this;\n\t}\n\twithSignalHandlers() {\n\t\tthis.signalHandlersEnabled = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Register an async cleanup hook to run during graceful shutdown. Hooks fire\n\t* after `reactor.kill()` resolves and before `database.destroy()`, so callers\n\t* that depend on the reactor (e.g. an HTTP API layered on top) can drain\n\t* cleanly before the underlying kysely instance is torn down. Hook errors are\n\t* logged and otherwise ignored — one bad hook cannot strand the rest of the\n\t* shutdown chain.\n\t*/\n\twithShutdownHook(hook) {\n\t\tthis.shutdownHooks.push(hook);\n\t\treturn this;\n\t}\n\twithDocumentModelSpecs(specs) {\n\t\tthis.documentModelSpecs = specs;\n\t\treturn this;\n\t}\n\t/**\n\t* Stores the worker-pool configuration. When `config.enabled === true` the\n\t* builder constructs a {@link WorkerPoolJobExecutorManager} in place of the\n\t* in-process {@link SimpleJobExecutorManager}.\n\t*/\n\twithWorkerPool(config) {\n\t\tthis.workerPoolConfig = config;\n\t\treturn this;\n\t}\n\t/**\n\t* Postgres connection info forwarded to each worker so it can open its own\n\t* pool. Required when `workerPool.enabled === true` unless a custom\n\t* `withWorkerFactory` or `withExecutor` is provided.\n\t*/\n\twithWorkerDbConfig(db) {\n\t\tthis.workerDbConfig = db;\n\t\treturn this;\n\t}\n\t/**\n\t* Factory spec the worker imports to instantiate its signature verifier.\n\t* Required when `workerPool.enabled === true` unless a custom\n\t* `withWorkerFactory` or `withExecutor` is provided.\n\t*/\n\twithWorkerSignatureVerifierSpec(spec) {\n\t\tthis.workerSignatureVerifierSpec = spec;\n\t\treturn this;\n\t}\n\t/**\n\t* Inject a custom {@link WorkerFactory}. When set, the builder skips\n\t* default thread-transport wiring and hands the factory directly to the\n\t* pool manager. Use this in tests or to plug in a different transport\n\t* (e.g. a child-process adapter).\n\t*/\n\twithWorkerFactory(factory) {\n\t\tthis.workerFactory = factory;\n\t\treturn this;\n\t}\n\t/**\n\t* Configure N sharded projection workers. When set, the builder replaces\n\t* the default in-process {@link ReadModelCoordinator} with a\n\t* {@link ProjectionShardManager}. The same `DbConfig` registered via\n\t* {@link withWorkerDbConfig} is reused for the projection workers'\n\t* connection info; only the `poolSize` is overridden by\n\t* {@link ProjectionShardBuilderConfig.poolSize}.\n\t*\n\t* Requires {@link withWorkerDbConfig} (the projection workers need\n\t* connection info to open their own pools). The same model manifest\n\t* resolved from {@link withDocumentModelSpecs} is forwarded.\n\t*/\n\twithProjectionShards(config) {\n\t\tthis.projectionShardConfig = config;\n\t\treturn this;\n\t}\n\t/**\n\t* Inject a custom {@link ProjectionWorkerFactory}. When set, the builder\n\t* skips default thread-transport wiring for the projection shards and\n\t* hands the factory directly to {@link ProjectionShardManager}.\n\t*/\n\twithProjectionWorkerFactory(factory) {\n\t\tthis.projectionWorkerFactory = factory;\n\t\treturn this;\n\t}\n\tgetResolvedModelManifest() {\n\t\treturn this.resolvedModelManifest;\n\t}\n\tasync build() {\n\t\treturn (await this.buildModule()).reactor;\n\t}\n\tasync buildModule() {\n\t\tif (!this.logger) this.logger = new ConsoleLogger([\"reactor\"]);\n\t\tif (this.workerPoolConfig?.enabled) {\n\t\t\tif (this.documentModels.length > 0) throw new Error(\"workerPool.enabled requires withDocumentModelSpecs; remove withDocumentModels() in worker-pool mode.\");\n\t\t\tif (this.documentModelSpecs.length === 0) throw new Error(\"workerPool.enabled requires at least one spec registered via withDocumentModelSpecs.\");\n\t\t\tconst needsDefaultFactory = !this.executorManager && !this.workerFactory;\n\t\t\tif (needsDefaultFactory && !this.workerDbConfig) throw new Error(\"workerPool.enabled requires withWorkerDbConfig (or a custom withWorkerFactory / withExecutor).\");\n\t\t\tif (needsDefaultFactory && !this.workerSignatureVerifierSpec) throw new Error(\"workerPool.enabled requires withWorkerSignatureVerifierSpec (or a custom withWorkerFactory / withExecutor).\");\n\t\t}\n\t\tif (this.documentModelSpecs.length > 0) this.resolvedModelManifest = this.documentModelSpecs.map((input) => {\n\t\t\tif (\"filePath\" in input) return {\n\t\t\t\tdocumentType: \"<unresolved>\",\n\t\t\t\tversion: \"<unresolved>\",\n\t\t\t\tspec: { module: {\n\t\t\t\t\tfilePath: input.filePath,\n\t\t\t\t\texportName: \"documentModel\"\n\t\t\t\t} }\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tdocumentType: \"<unresolved>\",\n\t\t\t\tversion: input.version,\n\t\t\t\tspec: { module: {\n\t\t\t\t\tpackageName: input.packageName,\n\t\t\t\t\texportName: \"documentModel\"\n\t\t\t\t} }\n\t\t\t};\n\t\t});\n\t\tconst documentModelRegistry = new DocumentModelRegistry();\n\t\tif (this.upgradeManifests.length > 0) {\n\t\t\tconst results = documentModelRegistry.registerUpgradeManifests(...this.upgradeManifests);\n\t\t\tfor (const result of results) if (result.status === \"error\") this.logger.error(\"Failed to register upgrade manifest: @error\", result.error.message);\n\t\t}\n\t\tif (this.documentModels.length > 0) {\n\t\t\tconst results = documentModelRegistry.registerModules(...this.documentModels);\n\t\t\tfor (const result of results) if (result.status === \"error\") this.logger.error(\"Failed to register document model: @error\", result.error.message);\n\t\t}\n\t\tconst baseDatabase = this.kyselyInstance ?? (this.workerPoolConfig?.enabled && this.workerDbConfig ? await this.createPostgresDatabase(this.workerDbConfig) : await createDefaultDatabase());\n\t\tif (this.migrationStrategy === \"auto\") {\n\t\t\tconst result = await runMigrations(baseDatabase, REACTOR_SCHEMA);\n\t\t\tif (!result.success && result.error) throw new Error(`Database migration failed: ${result.error.message}`);\n\t\t}\n\t\tconst database = baseDatabase.withSchema(REACTOR_SCHEMA);\n\t\tconst operationStore = new KyselyOperationStore(database);\n\t\tconst keyframeStore = new KyselyKeyframeStore(database);\n\t\tconst eventBus = this.eventBus || new EventBus();\n\t\tconst resolver = this.documentModelLoader ? new DocumentModelResolver(documentModelRegistry, this.documentModelLoader) : new NullDocumentModelResolver(documentModelRegistry);\n\t\tconst queue = this.queueInstance ?? new InMemoryQueue(eventBus, resolver);\n\t\tconst jobTracker = new InMemoryJobTracker(eventBus);\n\t\tconst writeCache = new KyselyWriteCache(keyframeStore, operationStore, documentModelRegistry, {\n\t\t\tmaxDocuments: this.writeCacheConfig?.maxDocuments ?? 100,\n\t\t\tringBufferSize: this.writeCacheConfig?.ringBufferSize ?? 10,\n\t\t\tkeyframeInterval: this.writeCacheConfig?.keyframeInterval ?? 10\n\t\t});\n\t\tawait writeCache.startup();\n\t\tconst operationIndex = new KyselyOperationIndex(database);\n\t\tconst documentMetaCache = new DocumentMetaCache(operationStore, { maxDocuments: 1e3 });\n\t\tawait documentMetaCache.startup();\n\t\tconst collectionMembershipCache = new CollectionMembershipCache(operationIndex);\n\t\tconst executionScope = new KyselyExecutionScope(database, operationStore, operationIndex, keyframeStore, writeCache, documentMetaCache, collectionMembershipCache);\n\t\tlet executorManager = this.executorManager;\n\t\tlet executorStartCount = this.executorConfig.maxConcurrency ?? 1;\n\t\tif (!executorManager) if (this.workerPoolConfig?.enabled) {\n\t\t\tconst poolManager = new WorkerPoolJobExecutorManager(this.workerFactory ?? await this.createDefaultWorkerFactory(this.workerPoolConfig), eventBus, queue, jobTracker, this.logger, resolver, collectionMembershipCache, this.executorConfig.jobTimeoutMs);\n\t\t\texecutorManager = poolManager;\n\t\t\texecutorStartCount = this.workerPoolConfig.numWorkers;\n\t\t\tif (resolver instanceof DocumentModelResolver) resolver.setBroadcastHook((entry) => poolManager.loadModel(entry));\n\t\t} else executorManager = new SimpleJobExecutorManager(() => new SimpleJobExecutor(this.logger, documentModelRegistry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, this.driveContainerTypes, this.executorConfig, this.signatureVerifier, executionScope), eventBus, queue, jobTracker, this.logger, resolver, this.executorConfig.jobTimeoutMs);\n\t\tawait executorManager.start(executorStartCount);\n\t\tconst readModelInstances = Array.from(new Set([...this.readModels]));\n\t\tconst documentViewConsistencyTracker = new ConsistencyTracker();\n\t\tconst documentView = new KyselyDocumentView(database, operationStore, operationIndex, writeCache, documentViewConsistencyTracker);\n\t\ttry {\n\t\t\tawait documentView.init();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error initializing document view\", error);\n\t\t}\n\t\treadModelInstances.push(documentView);\n\t\tconst documentIndexerConsistencyTracker = new ConsistencyTracker();\n\t\tconst documentIndexer = new KyselyDocumentIndexer(database, operationIndex, writeCache, documentIndexerConsistencyTracker);\n\t\ttry {\n\t\t\tawait documentIndexer.init();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error initializing document indexer\", error);\n\t\t}\n\t\treadModelInstances.push(documentIndexer);\n\t\tconst subscriptionManager = new ReactorSubscriptionManager(new DefaultSubscriptionErrorHandler());\n\t\tconst subscriptionNotificationReadModel = new SubscriptionNotificationReadModel(subscriptionManager, documentView);\n\t\tconst processorManagerConsistencyTracker = new ConsistencyTracker();\n\t\tconst processorManager = new ProcessorManager(database, operationIndex, writeCache, processorManagerConsistencyTracker, this.logger, this.driveContainerTypes);\n\t\ttry {\n\t\t\tawait processorManager.init();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error initializing processor manager\", error);\n\t\t}\n\t\tfor (const factory of this.readModelFactories) {\n\t\t\tconst readModel = await factory({\n\t\t\t\toperationIndex,\n\t\t\t\twriteCache,\n\t\t\t\tprocessorManagerConsistencyTracker\n\t\t\t});\n\t\t\treadModelInstances.push(readModel);\n\t\t}\n\t\tconst readModelCoordinator = this.readModelCoordinator ? this.readModelCoordinator : this.projectionShardConfig ? await this.createProjectionShardManager(this.projectionShardConfig, eventBus) : new ReadModelCoordinator(eventBus, readModelInstances, [subscriptionNotificationReadModel, processorManager]);\n\t\tconst reactor = new Reactor(this.logger, documentModelRegistry, queue, jobTracker, readModelCoordinator, this.features, documentView, documentIndexer, operationStore, eventBus, executorManager);\n\t\tlet syncModule = void 0;\n\t\tif (this.channelScheme) {\n\t\t\tconst factory = this.channelScheme === ChannelScheme.CONNECT ? new GqlRequestChannelFactory(this.logger, this.jwtHandler, queue) : new GqlResponseChannelFactory(this.logger);\n\t\t\tsyncModule = new SyncBuilder().withChannelFactory(factory).buildModule(reactor, this.logger, operationIndex, eventBus, database, this.driveContainerTypes);\n\t\t\tawait syncModule.syncManager.startup();\n\t\t} else if (this.syncBuilder) {\n\t\t\tsyncModule = this.syncBuilder.buildModule(reactor, this.logger, operationIndex, eventBus, database, this.driveContainerTypes);\n\t\t\tawait syncModule.syncManager.startup();\n\t\t}\n\t\tconst module = {\n\t\t\teventBus,\n\t\t\tdocumentModelRegistry,\n\t\t\tqueue,\n\t\t\tjobTracker,\n\t\t\texecutorManager,\n\t\t\tdatabase,\n\t\t\toperationStore,\n\t\t\tkeyframeStore,\n\t\t\twriteCache,\n\t\t\toperationIndex,\n\t\t\tdocumentView,\n\t\t\tdocumentViewConsistencyTracker,\n\t\t\tdocumentIndexer,\n\t\t\tdocumentIndexerConsistencyTracker,\n\t\t\treadModelCoordinator,\n\t\t\tsubscriptionManager,\n\t\t\tprocessorManager,\n\t\t\tprocessorManagerConsistencyTracker,\n\t\t\tsyncModule,\n\t\t\treactor,\n\t\t\tpools: this.instrumentedPools\n\t\t};\n\t\tif (this.signalHandlersEnabled) this.attachSignalHandlers(module);\n\t\treturn module;\n\t}\n\t/**\n\t* Constructs a {@link ProjectionShardManager} bound to the host event\n\t* bus. Builds the default thread-transport factory unless one was\n\t* injected via {@link withProjectionWorkerFactory}. Calls\n\t* `manager.startup()` so all N workers reach READY before the reactor\n\t* is returned to the caller.\n\t*/\n\tasync createProjectionShardManager(config, eventBus) {\n\t\tif (!this.workerDbConfig) throw new Error(\"withProjectionShards requires withWorkerDbConfig; projection workers need connection info to open their own pools.\");\n\t\tconst models = this.resolvedModelManifest ?? [];\n\t\tconst db = {\n\t\t\t...this.workerDbConfig,\n\t\t\tpoolSize: config.poolSize ?? this.workerDbConfig.poolSize,\n\t\t\tapplicationName: \"reactor-projection-shard\"\n\t\t};\n\t\tconst factory = this.projectionWorkerFactory ?? await this.createDefaultProjectionWorkerFactory();\n\t\tconst poolInstrumentations = [];\n\t\tfor (let i = 0; i < config.shardCount; i++) {\n\t\t\tconst forwarder = createForwardingPoolInstrumentation(`projection-shard-${i}`);\n\t\t\tpoolInstrumentations.push(forwarder);\n\t\t\tthis.instrumentedPools.push(forwarder);\n\t\t}\n\t\tconst { ProjectionShardManager } = await import(\"./projection-shard-manager-_c7orNo5.js\");\n\t\tconst manager = new ProjectionShardManager({\n\t\t\tshardCount: config.shardCount,\n\t\t\tdb,\n\t\t\tmodels,\n\t\t\tpreReadyKinds: config.preReadyKinds,\n\t\t\tpostReadyKinds: config.postReadyKinds,\n\t\t\tfactory,\n\t\t\tlogger: this.logger,\n\t\t\thostBus: eventBus,\n\t\t\tinitTimeoutMs: config.initTimeoutMs,\n\t\t\tshutdownGraceMs: config.shutdownGraceMs,\n\t\t\tdrainTimeoutMs: config.drainTimeoutMs,\n\t\t\tchainDepthReportIntervalMs: config.chainDepthReportIntervalMs,\n\t\t\tpoolInstrumentations\n\t\t});\n\t\tawait manager.startup();\n\t\tthis.shutdownHooks.push(() => manager.shutdown());\n\t\treturn manager;\n\t}\n\tasync createDefaultProjectionWorkerFactory() {\n\t\tconst [{ createProjectionThreadTransport }, { projectionWorkerEntryPath }] = await Promise.all([import(\"./transport-CuogVKN_.js\"), import(\"./projection-worker-wI4PwcV2.js\")]);\n\t\treturn () => createProjectionThreadTransport(projectionWorkerEntryPath);\n\t}\n\t/**\n\t* Default {@link WorkerFactory} used when `workerPool.enabled` is set and\n\t* the caller did not inject `withWorkerFactory`. Each worker spawns a real\n\t* `node:worker_threads` Worker pointing at the compiled `worker/entry.js`.\n\t*/\n\tasync createDefaultWorkerFactory(poolConfig) {\n\t\tconst [{ WorkerHandle }, { createThreadTransport }, { workerEntryPath }] = await Promise.all([\n\t\t\timport(\"./worker-handle-B1w03nRA.js\"),\n\t\t\timport(\"./transport-ByGviWdZ.js\"),\n\t\t\timport(\"./worker-XYrQaEmt.js\").then((n) => n.n)\n\t\t]);\n\t\tconst db = this.workerDbConfig;\n\t\tconst signatureVerifier = this.workerSignatureVerifierSpec;\n\t\tconst models = this.resolvedModelManifest ?? [];\n\t\tconst logger = this.logger;\n\t\treturn (index) => {\n\t\t\tconst workerId = `reactor-worker-${index}`;\n\t\t\tconst poolInstrumentation = createForwardingPoolInstrumentation(workerId);\n\t\t\tthis.instrumentedPools.push(poolInstrumentation);\n\t\t\treturn new WorkerHandle({\n\t\t\t\tworkerId,\n\t\t\t\tindex,\n\t\t\t\ttransport: createThreadTransport(workerEntryPath),\n\t\t\t\tinitPayload: {\n\t\t\t\t\tpoolConfig,\n\t\t\t\t\tdb,\n\t\t\t\t\tsignatureVerifier,\n\t\t\t\t\tmodels\n\t\t\t\t},\n\t\t\t\tlogger,\n\t\t\t\tpoolInstrumentation\n\t\t\t});\n\t\t};\n\t}\n\t/**\n\t* Builds the parent Kysely instance against a real Postgres server using\n\t* the same {@link DbConfig} the workers receive at init. Used in the\n\t* worker-pool path so the parent reactor and each worker thread share\n\t* storage; PGlite cannot be shared across threads. The constructed pool\n\t* is wrapped with {@link instrumentPgPool} and the resulting\n\t* {@link PoolInstrumentation} is pushed onto {@link instrumentedPools} so\n\t* the reactor module exposes acquire-wait and pool-stat surfaces.\n\t*/\n\tasync createPostgresDatabase(config) {\n\t\tconst { Kysely, PostgresDialect } = await import(\"kysely\");\n\t\tconst Pool = (await import(\"pg\")).default.Pool;\n\t\tconst pool = new Pool({\n\t\t\thost: config.host,\n\t\t\tport: config.port,\n\t\t\tdatabase: config.database,\n\t\t\tuser: config.user,\n\t\t\tpassword: config.password,\n\t\t\tssl: config.ssl ? { rejectUnauthorized: false } : void 0,\n\t\t\tapplication_name: config.applicationName,\n\t\t\tmax: config.poolSize,\n\t\t\tconnectionTimeoutMillis: config.connectionTimeoutMillis,\n\t\t\tidleTimeoutMillis: config.idleTimeoutMillis\n\t\t});\n\t\tthis.instrumentedPools.push(instrumentPgPool(pool, config.applicationName ?? \"reactor-host\"));\n\t\treturn new Kysely({ dialect: new PostgresDialect({ pool }) });\n\t}\n\tattachSignalHandlers(module) {\n\t\tif (typeof globalThis === \"undefined\" || !(\"process\" in globalThis) || typeof globalThis.process.on !== \"function\") return;\n\t\tconst nodeProcess = globalThis.process;\n\t\tconst realExit = nodeProcess.exit.bind(nodeProcess);\n\t\tlet shutdownInProgress = false;\n\t\tlet pendingExitCode;\n\t\tconst handler = async (signal) => {\n\t\t\tif (shutdownInProgress) {\n\t\t\t\tthis.logger.warn(`Received ${signal} again, continuing graceful shutdown...`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tshutdownInProgress = true;\n\t\t\tnodeProcess.exit = ((code) => {\n\t\t\t\tpendingExitCode ??= code ?? 0;\n\t\t\t});\n\t\t\tthis.logger.info(`Received ${signal}, starting graceful shutdown...`);\n\t\t\tconst status = module.reactor.kill();\n\t\t\ttry {\n\t\t\t\tawait status.completed;\n\t\t\t} catch (error) {\n\t\t\t\tthis.logger.error(\"Shutdown failed waiting for reactor:\", error);\n\t\t\t\tnodeProcess.exit = realExit;\n\t\t\t\trealExit(1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const hook of this.shutdownHooks) try {\n\t\t\t\tawait hook();\n\t\t\t} catch (error) {\n\t\t\t\tthis.logger.error(\"Shutdown hook failed:\", error);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait module.database.destroy();\n\t\t\t} catch (error) {\n\t\t\t\tthis.logger.error(\"Shutdown failed destroying database:\", error);\n\t\t\t\tnodeProcess.exit = realExit;\n\t\t\t\trealExit(1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.logger.info(\"Shutdown complete\");\n\t\t\tnodeProcess.exit = realExit;\n\t\t\trealExit(pendingExitCode ?? 0);\n\t\t};\n\t\tnodeProcess.prependListener(\"SIGINT\", () => void handler(\"SIGINT\"));\n\t\tnodeProcess.prependListener(\"SIGTERM\", () => void handler(\"SIGTERM\"));\n\t}\n};\n//#endregion\n//#region src/signer/passthrough-signer.ts\n/**\n* A no-op signer that returns empty values for all methods.\n* Used when signing is not required.\n*/\nvar PassthroughSigner = class {\n\tpublicKey = {};\n\tsign() {\n\t\treturn Promise.resolve(new Uint8Array(0));\n\t}\n\tverify() {\n\t\treturn Promise.resolve();\n\t}\n\tsignAction() {\n\t\treturn Promise.resolve([\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"\n\t\t]);\n\t}\n};\n//#endregion\n//#region src/core/reactor-client-builder.ts\n/**\n* Builder class for constructing ReactorClient instances with proper configuration\n*/\nvar ReactorClientBuilder = class {\n\tlogger;\n\treactorBuilder;\n\treactor;\n\teventBus;\n\tdocumentIndexer;\n\tdocumentView;\n\tsigner;\n\tsignatureVerifier;\n\tsubscriptionManager;\n\tjobAwaiter;\n\tdocumentModelLoader;\n\t/**\n\t* Sets the logger for the ReactorClient.\n\t* @param logger - The logger to use.\n\t* @returns The ReactorClientBuilder instance.\n\t*/\n\twithLogger(logger) {\n\t\tthis.logger = logger;\n\t\treturn this;\n\t}\n\t/**\n\t* Either this or withReactor must be set.\n\t*/\n\twithReactorBuilder(reactorBuilder) {\n\t\tif (this.reactor) throw new Error(\"Reactor is already set\");\n\t\tthis.reactorBuilder = reactorBuilder;\n\t\treturn this;\n\t}\n\t/**\n\t* Either this or withReactorBuilder must be set.\n\t*/\n\twithReactor(reactor, eventBus, documentIndexer, documentView) {\n\t\tif (this.reactorBuilder) throw new Error(\"ReactorBuilder is already set\");\n\t\tthis.reactor = reactor;\n\t\tthis.eventBus = eventBus;\n\t\tthis.documentIndexer = documentIndexer;\n\t\tthis.documentView = documentView;\n\t\treturn this;\n\t}\n\t/**\n\t* Sets the signer configuration for signing and verifying actions.\n\t*\n\t* @param config - Either an ISigner for signing only, or a SignerConfig for both signing and verification\n\t*/\n\twithSigner(config) {\n\t\tif (\"signer\" in config) {\n\t\t\tthis.signer = config.signer;\n\t\t\tthis.signatureVerifier = config.verifier;\n\t\t} else this.signer = config;\n\t\treturn this;\n\t}\n\twithSubscriptionManager(subscriptionManager) {\n\t\tthis.subscriptionManager = subscriptionManager;\n\t\treturn this;\n\t}\n\twithJobAwaiter(jobAwaiter) {\n\t\tthis.jobAwaiter = jobAwaiter;\n\t\treturn this;\n\t}\n\twithDocumentModelLoader(loader) {\n\t\tthis.documentModelLoader = loader;\n\t\treturn this;\n\t}\n\tasync build() {\n\t\treturn (await this.buildModule()).client;\n\t}\n\tasync buildModule() {\n\t\tif (!this.logger) this.logger = new ConsoleLogger([\"reactor-client\"]);\n\t\tlet reactor;\n\t\tlet eventBus;\n\t\tlet documentIndexer;\n\t\tlet documentView;\n\t\tlet reactorModule;\n\t\tif (this.reactorBuilder) {\n\t\t\tif (this.signatureVerifier) this.reactorBuilder.withSignatureVerifier(this.signatureVerifier);\n\t\t\tif (this.documentModelLoader) this.reactorBuilder.withDocumentModelLoader(this.documentModelLoader);\n\t\t\treactorModule = await this.reactorBuilder.buildModule();\n\t\t\treactor = reactorModule.reactor;\n\t\t\teventBus = reactorModule.eventBus;\n\t\t\tdocumentIndexer = reactorModule.documentIndexer;\n\t\t\tdocumentView = reactorModule.documentView;\n\t\t} else if (this.reactor && this.eventBus && this.documentIndexer && this.documentView) {\n\t\t\treactor = this.reactor;\n\t\t\teventBus = this.eventBus;\n\t\t\tdocumentIndexer = this.documentIndexer;\n\t\t\tdocumentView = this.documentView;\n\t\t\treactorModule = void 0;\n\t\t} else throw new Error(\"Either ReactorBuilder or (Reactor + EventBus + DocumentIndexer + DocumentView) is required\");\n\t\tconst signer = this.signer ?? new PassthroughSigner();\n\t\tconst subscriptionManager = this.subscriptionManager ?? reactorModule?.subscriptionManager ?? new ReactorSubscriptionManager(new DefaultSubscriptionErrorHandler());\n\t\tconst jobAwaiter = this.jobAwaiter ?? new JobAwaiter(eventBus, (jobId, signal) => reactor.getJobStatus(jobId, signal));\n\t\treturn {\n\t\t\tclient: new ReactorClient(this.logger, reactor, signer, subscriptionManager, jobAwaiter, documentIndexer, documentView),\n\t\t\treactor,\n\t\t\teventBus,\n\t\t\tdocumentIndexer,\n\t\t\tdocumentView,\n\t\t\tsigner,\n\t\t\tsubscriptionManager,\n\t\t\tjobAwaiter,\n\t\t\treactorModule\n\t\t};\n\t}\n};\n//#endregion\n//#region src/shared/drive-url.ts\n/**\n* Parse a drive URL to extract drive ID and construct GraphQL endpoint.\n* Preserves any subpath prefix so the result is correct when the reactor is\n* served behind a proxy at a non-root path.\n* e.g., \"http://localhost:4001/d/abc123\" -> { driveId: \"abc123\", graphqlEndpoint: \"http://localhost:4001/graphql/r\" }\n* e.g., \"https://example.com/api/reactor/d/abc123\" -> { ..., graphqlEndpoint: \"https://example.com/api/reactor/graphql/r\" }\n*/\nfunction parseDriveUrl(url) {\n\tconst parsedUrl = new URL(url);\n\tconst driveId = url.split(\"/\").pop() ?? \"\";\n\tconst basePath = parsedUrl.pathname.replace(/\\/d\\/[^/]+\\/?$/, \"\");\n\treturn {\n\t\turl,\n\t\tdriveId,\n\t\tgraphqlEndpoint: `${parsedUrl.protocol}//${parsedUrl.host}${basePath}/graphql/r`\n\t};\n}\n/**\n* Extract drive ID from a drive URL.\n*/\nfunction driveIdFromUrl(url) {\n\treturn url.split(\"/\").pop() ?? \"\";\n}\n//#endregion\n//#region src/admin/passthrough-keyframe-store.ts\nconst passthroughKeyframeStore = {\n\tputKeyframe: () => Promise.resolve(),\n\tfindNearestKeyframe: () => Promise.resolve(void 0),\n\tlistKeyframes: () => Promise.resolve([]),\n\tdeleteKeyframes: () => Promise.resolve(0)\n};\n//#endregion\n//#region src/admin/document-integrity-service.ts\nvar DocumentIntegrityService = class {\n\tkeyframeStore;\n\toperationStore;\n\twriteCache;\n\tdocumentView;\n\tdocumentModelRegistry;\n\tconstructor(keyframeStore, operationStore, writeCache, documentView, documentModelRegistry) {\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.operationStore = operationStore;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentView = documentView;\n\t\tthis.documentModelRegistry = documentModelRegistry;\n\t}\n\tasync validateDocument(documentId, branch = \"main\", signal) {\n\t\tconst keyframeIssues = [];\n\t\tconst snapshotIssues = [];\n\t\tconst replayCache = new KyselyWriteCache(passthroughKeyframeStore, this.operationStore, this.documentModelRegistry, {\n\t\t\tmaxDocuments: 1,\n\t\t\tringBufferSize: 1,\n\t\t\tkeyframeInterval: Number.MAX_SAFE_INTEGER\n\t\t});\n\t\tconst keyframes = await this.keyframeStore.listKeyframes(documentId, void 0, branch, signal);\n\t\tfor (const keyframe of keyframes) {\n\t\t\tthrowIfAborted(signal);\n\t\t\treplayCache.invalidate(documentId, keyframe.scope, branch);\n\t\t\tconst replayedDoc = await replayCache.getState(documentId, keyframe.scope, branch, keyframe.revision, signal);\n\t\t\tconst kfHash = hashDocumentStateForScope(keyframe.document, keyframe.scope);\n\t\t\tconst replayHash = hashDocumentStateForScope(replayedDoc, keyframe.scope);\n\t\t\tif (kfHash !== replayHash) keyframeIssues.push({\n\t\t\t\tscope: keyframe.scope,\n\t\t\t\tbranch,\n\t\t\t\trevision: keyframe.revision,\n\t\t\t\tkeyframeHash: kfHash,\n\t\t\t\treplayedHash: replayHash\n\t\t\t});\n\t\t}\n\t\tlet currentDoc;\n\t\ttry {\n\t\t\tcurrentDoc = await this.documentView.get(documentId);\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tdocumentId,\n\t\t\t\tisConsistent: keyframeIssues.length === 0,\n\t\t\t\tkeyframeIssues,\n\t\t\t\tsnapshotIssues\n\t\t\t};\n\t\t}\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tconst allScopes = Object.keys(revisions.revision);\n\t\tfor (const scope of allScopes) {\n\t\t\tif (scope === \"document\") continue;\n\t\t\treplayCache.invalidate(documentId, scope, branch);\n\t\t\tlet replayedDoc;\n\t\t\ttry {\n\t\t\t\treplayedDoc = await replayCache.getState(documentId, scope, branch, void 0, signal);\n\t\t\t} catch {\n\t\t\t\tthrowIfAborted(signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst snapshotHash = hashDocumentStateForScope(currentDoc, scope);\n\t\t\tconst replayHash = hashDocumentStateForScope(replayedDoc, scope);\n\t\t\tif (snapshotHash !== replayHash) snapshotIssues.push({\n\t\t\t\tscope,\n\t\t\t\tbranch,\n\t\t\t\tsnapshotHash,\n\t\t\t\treplayedHash: replayHash\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tdocumentId,\n\t\t\tisConsistent: keyframeIssues.length === 0 && snapshotIssues.length === 0,\n\t\t\tkeyframeIssues,\n\t\t\tsnapshotIssues\n\t\t};\n\t}\n\tasync rebuildKeyframes(documentId, branch = \"main\", signal) {\n\t\treturn {\n\t\t\tdocumentId,\n\t\t\tkeyframesDeleted: await this.keyframeStore.deleteKeyframes(documentId, void 0, branch, signal),\n\t\t\tscopesInvalidated: 0\n\t\t};\n\t}\n\tasync rebuildSnapshots(documentId, branch = \"main\", signal) {\n\t\tconst scopes = await this.discoverScopes(documentId, branch, signal);\n\t\tfor (const scope of scopes) {\n\t\t\tthrowIfAborted(signal);\n\t\t\tthis.writeCache.invalidate(documentId, scope, branch);\n\t\t}\n\t\treturn {\n\t\t\tdocumentId,\n\t\t\tkeyframesDeleted: 0,\n\t\t\tscopesInvalidated: scopes.length\n\t\t};\n\t}\n\tasync discoverScopes(documentId, branch, signal) {\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\treturn Object.keys(revisions.revision);\n\t}\n};\n//#endregion\nexport { BaseReadModel, ChannelError, ChannelErrorSource, ChannelScheme, ConsistencyTracker, DEFAULT_DRIVE_CONTAINER_TYPES, DefaultSubscriptionErrorHandler, DocumentChangeType, DocumentIntegrityService, DocumentModelRegistry, DocumentModelResolver, DriveClient, DriveCollectionId, DuplicateManifestError, DuplicateModuleError, DuplicateOperationError, EventBus, EventBusAggregateError, GqlRequestChannel, GqlRequestChannelFactory, GqlResponseChannel, GqlResponseChannelFactory, SimpleJobExecutor as InMemoryJobExecutor, SimpleJobExecutor, InMemoryJobTracker, InMemoryQueue, IntervalPollTimer, InvalidModuleError, JobAwaiter, JobExecutorEventTypes, JobStatus, KyselyDocumentIndexer, KyselyDocumentView, KyselyKeyframeStore, KyselyOperationStore, KyselySyncCursorStorage, KyselySyncRemoteStorage, KyselyWriteCache, Mailbox, ModuleNotFoundError, NullDocumentModelResolver, OptimisticLockError, PollBehavior, PollingChannelError, ProcessorManager, PropagationMode, QueueEventTypes, REACTOR_SCHEMA, Reactor, ReactorBuilder, ReactorClient, ReactorClientBuilder, ReactorEventTypes, ReactorSubscriptionManager, ReadModelCoordinator, RelationalDbProcessor, RelationshipChangeType, RevisionMismatchError, SimpleJobExecutorManager, SyncBuilder, SyncEventTypes, SyncOperation, SyncOperationAggregateError, SyncOperationStatus, SyncStatus, SyncStatusTracker, addRelationshipAction, batchOperationsByDocument, consolidateSyncOperations, createDocumentAction, createForwardingLogger, createMutableShutdownStatus, createRelationalDb, deleteDocumentAction, documentActions, driveIdFromUrl, envelopesToSyncOperations, errorToInfo, getMigrationStatus, instrumentPgPool, makeConsistencyKey, parseDriveUrl, parsePagingOptions, removeRelationshipAction, runMigrations, sanitizeArg, trimMailboxFromAckOrdinal, updateRelationshipAction, upgradeDocumentAction, workerEntryPath };\n\n//# sourceMappingURL=index.js.map","import { t as makePHEventFunctions } from \"./make-ph-event-functions-BHoLPif5.js\";\nimport { logger } from \"document-model\";\nimport { buildSignedAction } from \"@powerhousedao/shared/document-model\";\nimport { DocumentChangeType } from \"@powerhousedao/reactor\";\nimport { use, useCallback, useSyncExternalStore } from \"react\";\nimport { BrowserAnalyticsStore } from \"@powerhousedao/analytics-engine-browser\";\nimport { AnalyticsQueryEngine } from \"@powerhousedao/analytics-engine-core\";\n//#region src/actions/queue.ts\nasync function queueActions(document, actionOrActions) {\n\tif (!document) throw new Error(\"No document provided\");\n\tif (!actionOrActions) throw new Error(\"No actions provided\");\n\tconst actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];\n\tif (actions.length === 0) throw new Error(\"No actions provided\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(document.header.id, \"main\", actions);\n}\nasync function queueOperations(documentId, operationOrOperations) {\n\tif (!documentId) throw new Error(\"No documentId provided\");\n\tif (!operationOrOperations) throw new Error(\"No operations provided\");\n\tconst operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];\n\tif (operations.length === 0) throw new Error(\"No operations provided\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst actions = operations.map((op) => op.action);\n\treturn await reactorClient.execute(documentId, \"main\", actions);\n}\nasync function uploadOperations(documentId, allOperations, pushOperations, options) {\n\tconst operationsLimit = options?.operationsLimit || 50;\n\tconst onProgress = options?.onProgress;\n\tlogger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(\",\")}, limit:${operationsLimit})`);\n\tconst allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);\n\tconst totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);\n\tlet uploadedOperations = 0;\n\tfor (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {\n\t\tlogger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);\n\t\tconst chunk = operations.slice(i, i + operationsLimit);\n\t\tconst operation = chunk.at(-1);\n\t\tif (!operation) break;\n\t\tconst scope = operation.action.scope;\n\t\tawait pushOperations(documentId, chunk);\n\t\tuploadedOperations += chunk.length;\n\t\tif (onProgress) onProgress({\n\t\t\tstage: \"uploading\",\n\t\t\tprogress: Math.round(uploadedOperations / totalOperations * 100),\n\t\t\ttotalOperations,\n\t\t\tuploadedOperations\n\t\t});\n\t\tlogger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);\n\t}\n\tlogger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);\n}\n//#endregion\n//#region src/actions/sign.ts\nasync function signAction(action, document) {\n\tconst reactor = window.ph?.reactorClient;\n\tif (!reactor) return action;\n\tconst reducer = (await reactor.getDocumentModelModule(document.header.documentType)).reducer;\n\tconst renown = window.ph?.renown;\n\tif (!renown?.user) return action;\n\tif (!action.context?.signer) return action;\n\tconst actionSigner = action.context.signer;\n\treturn await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);\n}\nfunction addActionContext(action) {\n\tconst renown = window.ph?.renown;\n\tif (!renown?.user) return action;\n\treturn {\n\t\tcontext: { signer: {\n\t\t\tapp: {\n\t\t\t\tname: \"Connect\",\n\t\t\t\tkey: renown.did\n\t\t\t},\n\t\t\tuser: {\n\t\t\t\taddress: renown.user.address,\n\t\t\t\tnetworkId: renown.user.networkId,\n\t\t\t\tchainId: renown.user.chainId\n\t\t\t},\n\t\t\tsignatures: []\n\t\t} },\n\t\t...action\n\t};\n}\nasync function makeSignedActionWithContext(action, document) {\n\tif (!action) {\n\t\tlogger.error(\"No action found\");\n\t\treturn;\n\t}\n\tif (!document) {\n\t\tlogger.error(\"No document found\");\n\t\treturn;\n\t}\n\treturn addActionContext(await signAction(action, document));\n}\nasync function makeSignedActionsWithContext(actionOrActions, document) {\n\tif (!actionOrActions) {\n\t\tlogger.error(\"No actions found\");\n\t\treturn;\n\t}\n\tconst actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];\n\treturn (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);\n}\n//#endregion\n//#region src/actions/dispatch.ts\nasync function getDocument(documentId) {\n\ttry {\n\t\treturn await window.ph?.reactorClient?.get(documentId);\n\t} catch (error) {\n\t\tlogger.debug(`Failed to get document with id ${documentId}:`, error);\n\t\treturn;\n\t}\n}\nfunction getActionErrors(result, actions) {\n\treturn actions.reduce((errors, a) => {\n\t\tconst scopeOperations = result.operations[a.scope];\n\t\tif (!scopeOperations) return errors;\n\t\tconst op = scopeOperations.findLast((op) => op.action.id === a.id);\n\t\tif (op?.error) errors.push(new Error(op.error));\n\t\treturn errors;\n\t}, new Array());\n}\nasync function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {\n\tconst document = typeof documentOrDocumentId === \"string\" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;\n\tif (!document) {\n\t\tlogger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);\n\t\treturn;\n\t}\n\tconst signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);\n\tif (!signedActionsWithContext) {\n\t\tlogger.error(\"No signed actions with context found\");\n\t\treturn;\n\t}\n\tconst result = await queueActions(document, signedActionsWithContext);\n\tif (onErrors && result) {\n\t\tconst errors = getActionErrors(result, signedActionsWithContext);\n\t\tif (errors.length) onErrors(errors);\n\t}\n\tif (onSuccess && result) onSuccess(result);\n\treturn result;\n}\n//#endregion\n//#region src/global/core.ts\nfunction getGlobal(namespace) {\n\tif (typeof window === \"undefined\") return void 0;\n\treturn window.powerhouse?.[namespace];\n}\nfunction setGlobal(namespace, value) {\n\tif (typeof window === \"undefined\") return;\n\twindow.powerhouse = window.powerhouse || {};\n\twindow.powerhouse[namespace] = value;\n}\nfunction clearGlobal(namespace) {\n\tif (typeof window === \"undefined\") return;\n\tif (window.powerhouse?.[namespace]) {\n\t\tdelete window.powerhouse[namespace];\n\t\tif (Object.keys(window.powerhouse).length === 0) delete window.powerhouse;\n\t}\n}\n//#endregion\n//#region src/analytics/store.ts\nasync function createAnalyticsStore(options) {\n\tconst store = new BrowserAnalyticsStore(options);\n\tawait store.init();\n\treturn {\n\t\tstore,\n\t\tengine: new AnalyticsQueryEngine(store),\n\t\toptions\n\t};\n}\nasync function getAnalyticsStore() {\n\treturn (await getGlobal(\"analytics\"))?.store ?? null;\n}\n//#endregion\n//#region src/document-cache.ts\nfunction addPromiseState(promise) {\n\tif (\"status\" in promise) return promise;\n\tconst promiseWithState = promise;\n\tpromiseWithState.status = \"pending\";\n\tpromiseWithState.then((value) => {\n\t\tpromiseWithState.status = \"fulfilled\";\n\t\tpromiseWithState.value = value;\n\t}, (reason) => {\n\t\tpromiseWithState.status = \"rejected\";\n\t\tpromiseWithState.reason = reason;\n\t\tthrow reason;\n\t});\n\treturn promiseWithState;\n}\nfunction readPromiseState(promise) {\n\treturn \"status\" in promise ? promise : { status: \"pending\" };\n}\n/**\n* Resolves an array of document promises using `Promise.allSettled`,\n* returning only the fulfilled values. A single missing/rejected\n* document does not poison the whole batch. Rejected entries are\n* logged at warn level so developers can see dangling references.\n*/\nfunction fulfilledOnly(promises) {\n\treturn Promise.allSettled(promises).then((results) => {\n\t\tconst documents = [];\n\t\tfor (const result of results) if (result.status === \"fulfilled\") documents.push(result.value);\n\t\telse console.warn(\"[DocumentCache] Skipped unavailable document:\", result.reason);\n\t\treturn documents;\n\t});\n}\n/**\n* Document cache implementation that uses the new ReactorClient API.\n*\n* This cache subscribes to document change events via IReactorClient.subscribe()\n* and automatically updates the cache when documents are created, updated, or deleted.\n*/\nvar DocumentCache = class {\n\tdocuments = /* @__PURE__ */ new Map();\n\tbatchPromises = /* @__PURE__ */ new Map();\n\tlisteners = /* @__PURE__ */ new Map();\n\tunsubscribe = null;\n\tconstructor(client) {\n\t\tthis.client = client;\n\t\tthis.unsubscribe = client.subscribe({}, (event) => {\n\t\t\tthis.handleDocumentChange(event);\n\t\t});\n\t}\n\thandleDocumentChange(event) {\n\t\tif (event.type === DocumentChangeType.Deleted) {\n\t\t\tconst documentId = event.context?.childId;\n\t\t\tif (documentId) this.handleDocumentDeleted(documentId);\n\t\t} else if (event.type === DocumentChangeType.Updated) for (const doc of event.documents) this.handleDocumentUpdated(doc.header.id).catch(console.warn);\n\t}\n\thandleDocumentDeleted(documentId) {\n\t\tconst listeners = this.listeners.get(documentId);\n\t\tthis.documents.delete(documentId);\n\t\tthis.invalidateBatchesContaining(documentId);\n\t\tif (listeners) listeners.forEach((listener) => listener());\n\t\tthis.listeners.delete(documentId);\n\t}\n\tasync handleDocumentUpdated(documentId) {\n\t\tif (this.documents.has(documentId)) {\n\t\t\tawait this.get(documentId, true);\n\t\t\tconst listeners = this.listeners.get(documentId);\n\t\t\tif (listeners) listeners.forEach((listener) => listener());\n\t\t}\n\t}\n\tinvalidateBatchesContaining(documentId) {\n\t\tfor (const key of this.batchPromises.keys()) if (key.split(\",\").includes(documentId)) this.batchPromises.delete(key);\n\t}\n\tget(id, refetch) {\n\t\tconst currentData = this.documents.get(id);\n\t\tif (currentData) {\n\t\t\tif (currentData.status === \"pending\") return currentData;\n\t\t\tif (!refetch) return currentData;\n\t\t}\n\t\tconst documentPromise = this.client.get(id);\n\t\tthis.documents.set(id, addPromiseState(documentPromise));\n\t\treturn documentPromise;\n\t}\n\tgetBatch(ids) {\n\t\tconst key = ids.join(\",\");\n\t\tconst cached = this.batchPromises.get(key);\n\t\tconst hasDeletedDocuments = ids.some((id) => !this.documents.has(id));\n\t\tconst currentPromises = ids.map((id) => this.get(id));\n\t\tif (hasDeletedDocuments) {\n\t\t\tconst batchPromise = fulfilledOnly(currentPromises);\n\t\t\tthis.batchPromises.set(key, {\n\t\t\t\tpromises: currentPromises,\n\t\t\t\tpromise: batchPromise\n\t\t\t});\n\t\t\treturn batchPromise;\n\t\t}\n\t\tif (cached) {\n\t\t\tif (currentPromises.every((p, i) => p === cached.promises[i])) return cached.promise;\n\t\t}\n\t\tconst states = currentPromises.map((p) => readPromiseState(p));\n\t\tif (states.every((s) => s.status !== \"pending\")) {\n\t\t\tconst values = states.filter((s) => s.status === \"fulfilled\").map((s) => s.value);\n\t\t\tconst batchPromise = Promise.resolve(values);\n\t\t\tbatchPromise.status = \"fulfilled\";\n\t\t\tbatchPromise.value = values;\n\t\t\tthis.batchPromises.set(key, {\n\t\t\t\tpromises: currentPromises,\n\t\t\t\tpromise: batchPromise\n\t\t\t});\n\t\t\treturn batchPromise;\n\t\t}\n\t\tif (cached) return cached.promise;\n\t\tconst batchPromise = fulfilledOnly(currentPromises);\n\t\tthis.batchPromises.set(key, {\n\t\t\tpromises: currentPromises,\n\t\t\tpromise: batchPromise\n\t\t});\n\t\treturn batchPromise;\n\t}\n\tsubscribe(id, callback) {\n\t\tconst ids = Array.isArray(id) ? id : [id];\n\t\tfor (const docId of ids) {\n\t\t\tconst listeners = this.listeners.get(docId) ?? [];\n\t\t\tthis.listeners.set(docId, [...listeners, callback]);\n\t\t}\n\t\treturn () => {\n\t\t\tfor (const docId of ids) {\n\t\t\t\tconst listeners = this.listeners.get(docId) ?? [];\n\t\t\t\tthis.listeners.set(docId, listeners.filter((listener) => listener !== callback));\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Disposes of the cache and unsubscribes from document change events.\n\t*/\n\tdispose() {\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t\tthis.unsubscribe = null;\n\t\t}\n\t}\n};\n//#endregion\n//#region src/hooks/document-cache.ts\nconst documentEventFunctions = makePHEventFunctions(\"documentCache\");\n/** Returns all documents in the reactor. */\nconst useDocumentCache = documentEventFunctions.useValue;\n/** Sets all of the documents in the reactor. */\nconst setDocumentCache = documentEventFunctions.setValue;\n/** Adds an event handler for all of the documents in the reactor. */\nconst addDocumentCacheEventHandler = documentEventFunctions.addEventHandler;\n/**\n* Reads the state of a document promise and converts it to a query state object.\n* @param promise - The document promise to read\n* @returns An object containing the status, data, error, and isPending flag\n*/\nfunction getDocumentQueryState(promise) {\n\tconst state = readPromiseState(promise);\n\tswitch (state.status) {\n\t\tcase \"pending\": return {\n\t\t\tstatus: \"pending\",\n\t\t\tisPending: true,\n\t\t\terror: void 0,\n\t\t\tdata: void 0\n\t\t};\n\t\tcase \"fulfilled\": return {\n\t\t\tstatus: \"success\",\n\t\t\tisPending: false,\n\t\t\terror: void 0,\n\t\t\tdata: state.value\n\t\t};\n\t\tcase \"rejected\": return {\n\t\t\tstatus: \"error\",\n\t\t\tisPending: false,\n\t\t\terror: state.reason,\n\t\t\tdata: void 0\n\t\t};\n\t}\n}\n/**\n* Retrieves a document from the reactor and subscribes to changes using React Suspense.\n* This hook will suspend rendering while the document is loading.\n* @param id - The document ID to retrieve, or null/undefined to skip retrieval\n* @returns The document if found, or undefined if id is null/undefined\n*/\nfunction useDocument(id) {\n\tconst documentCache = useDocumentCache();\n\tconst document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);\n\treturn document ? use(document) : void 0;\n}\n/**\n* Retrieves a document from the reactor and subscribes to changes without\n* suspending or throwing. Use this when the ID might be stale (e.g., a\n* previously selected node that has since been deleted) and the consumer\n* wants to render a placeholder instead of crashing.\n*\n* Unlike {@link useGetDocumentAsync}, this hook subscribes to cache\n* updates, so the returned state stays in sync with reactor changes.\n*\n* @param id - The document ID to retrieve, or null/undefined to skip retrieval\n* @returns An object containing:\n* - status: \"initial\" | \"pending\" | \"success\" | \"error\"\n* - data: The document if successfully loaded\n* - isPending: Whether the document is currently loading\n* - error: Any error that occurred during loading (e.g., document not found)\n* - reload: Function to force a refetch, or undefined when no id is supplied\n*/\nfunction useDocumentSafe(id) {\n\tconst documentCache = useDocumentCache();\n\tconst promise = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);\n\tif (!promise || !documentCache || !id) return {\n\t\tstatus: \"initial\",\n\t\tisPending: false,\n\t\terror: void 0,\n\t\tdata: void 0,\n\t\treload: void 0\n\t};\n\treturn {\n\t\t...getDocumentQueryState(promise),\n\t\treload: () => documentCache.get(id, true)\n\t};\n}\n/**\n* Retrieves multiple documents from the reactor using React Suspense.\n* This hook will suspend rendering while any of the documents are loading.\n*\n* Uses getBatch from the document cache which handles promise caching internally,\n* ensuring stable references for useSyncExternalStore.\n*\n* @param ids - Array of document IDs to retrieve, or null/undefined to skip retrieval\n* @returns An array of documents if found, or empty array if ids is null/undefined\n*/\nfunction useDocuments(ids) {\n\tconst documentCache = useDocumentCache();\n\tconst documents = useSyncExternalStore((cb) => ids?.length && documentCache ? documentCache.subscribe(ids, cb) : () => {}, () => ids?.length && documentCache ? documentCache.getBatch(ids) : void 0);\n\treturn documents ? use(documents) : [];\n}\n/**\n* Returns a function to retrieve a document from the cache.\n* The returned function fetches and returns a document by ID.\n* @returns A function that takes a document ID and returns a Promise of the document\n*/\nfunction useGetDocument() {\n\tconst documentCache = useDocumentCache();\n\treturn useCallback((id) => {\n\t\tif (!documentCache) return Promise.reject(/* @__PURE__ */ new Error(\"Document cache not initialized\"));\n\t\treturn documentCache.get(id);\n\t}, [documentCache]);\n}\n/**\n* Returns a function to retrieve multiple documents from the cache.\n* The returned function fetches and returns documents by their IDs.\n* @returns A function that takes an array of document IDs and returns a Promise of the documents\n*/\nfunction useGetDocuments() {\n\tconst documentCache = useDocumentCache();\n\treturn useCallback((ids) => {\n\t\tif (!documentCache) return Promise.reject(/* @__PURE__ */ new Error(\"Document cache not initialized\"));\n\t\treturn documentCache.getBatch(ids);\n\t}, [documentCache]);\n}\n/**\n* Retrieves a document from the reactor without suspending rendering.\n* Returns the current state of the document loading operation.\n* @param id - The document ID to retrieve, or null/undefined to skip retrieval\n* @returns An object containing:\n* - status: \"initial\" | \"pending\" | \"success\" | \"error\"\n* - data: The document if successfully loaded\n* - isPending: Boolean indicating if the document is currently loading\n* - error: Any error that occurred during loading\n* - reload: Function to force reload the document from cache\n*/\nfunction useGetDocumentAsync(id) {\n\tconst documentCache = useDocumentCache();\n\tif (!id || !documentCache) return {\n\t\tstatus: \"initial\",\n\t\tdata: void 0,\n\t\tisPending: false,\n\t\terror: void 0,\n\t\treload: void 0\n\t};\n\treturn {\n\t\t...getDocumentQueryState(documentCache.get(id)),\n\t\treload: () => documentCache.get(id, true)\n\t};\n}\n//#endregion\n//#region src/hooks/dispatch.ts\nfunction useDispatch(document) {\n\t/**\n\t* Dispatches actions to the document.\n\t* @param actionOrActions - The action or actions to dispatch.\n\t* @param onErrors - Callback invoked with any errors that occurred during action execution.\n\t*/\n\tfunction dispatch(actionOrActions, onErrors, onSuccess) {\n\t\tdispatchActions(actionOrActions, document, onErrors, onSuccess).catch(logger.error);\n\t}\n\treturn [document, dispatch];\n}\n//#endregion\n//#region src/hooks/document-by-id.ts\n/** Returns a document by id. */\nfunction useDocumentById(id) {\n\tconst document = useDocument(id);\n\tconst [, dispatch] = useDispatch(document);\n\treturn [document, dispatch];\n}\n/** Returns documents by ids. */\nfunction useDocumentsByIds(ids) {\n\treturn useDocuments(ids);\n}\n//#endregion\nexport { queueOperations as C, queueActions as S, getAnalyticsStore as _, setDocumentCache as a, setGlobal as b, useDocumentSafe as c, useGetDocumentAsync as d, useGetDocuments as f, createAnalyticsStore as g, readPromiseState as h, addDocumentCacheEventHandler as i, useDocuments as l, addPromiseState as m, useDocumentsByIds as n, useDocument as o, DocumentCache as p, useDispatch as r, useDocumentCache as s, useDocumentById as t, useGetDocument as u, clearGlobal as v, uploadOperations as w, dispatchActions as x, getGlobal as y };\n\n//# sourceMappingURL=document-by-id-dLYFX-xz.js.map","export function devAssert(condition, message) {\n const booleanCondition = Boolean(condition);\n\n if (!booleanCondition) {\n throw new Error(message);\n }\n}\n","/**\n * Return true if `value` is object-like. A value is object-like if it's not\n * `null` and has a `typeof` result of \"object\".\n */\nexport function isObjectLike(value) {\n return typeof value == 'object' && value !== null;\n}\n","export function invariant(condition, message) {\n const booleanCondition = Boolean(condition);\n\n if (!booleanCondition) {\n throw new Error(\n message != null ? message : 'Unexpected invariant triggered.',\n );\n }\n}\n","import { invariant } from '../jsutils/invariant.mjs';\nconst LineRegExp = /\\r\\n|[\\n\\r]/g;\n/**\n * Represents a location in a Source.\n */\n\n/**\n * Takes a Source and a UTF-8 character offset, and returns the corresponding\n * line and column as a SourceLocation.\n */\nexport function getLocation(source, position) {\n let lastLineStart = 0;\n let line = 1;\n\n for (const match of source.body.matchAll(LineRegExp)) {\n typeof match.index === 'number' || invariant(false);\n\n if (match.index >= position) {\n break;\n }\n\n lastLineStart = match.index + match[0].length;\n line += 1;\n }\n\n return {\n line,\n column: position + 1 - lastLineStart,\n };\n}\n","import { getLocation } from './location.mjs';\n\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\nexport function printLocation(location) {\n return printSourceLocation(\n location.source,\n getLocation(location.source, location.start),\n );\n}\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\n\nexport function printSourceLocation(source, sourceLocation) {\n const firstLineColumnOffset = source.locationOffset.column - 1;\n const body = ''.padStart(firstLineColumnOffset) + source.body;\n const lineIndex = sourceLocation.line - 1;\n const lineOffset = source.locationOffset.line - 1;\n const lineNum = sourceLocation.line + lineOffset;\n const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;\n const columnNum = sourceLocation.column + columnOffset;\n const locationStr = `${source.name}:${lineNum}:${columnNum}\\n`;\n const lines = body.split(/\\r\\n|[\\n\\r]/g);\n const locationLine = lines[lineIndex]; // Special case for minified documents\n\n if (locationLine.length > 120) {\n const subLineIndex = Math.floor(columnNum / 80);\n const subLineColumnNum = columnNum % 80;\n const subLines = [];\n\n for (let i = 0; i < locationLine.length; i += 80) {\n subLines.push(locationLine.slice(i, i + 80));\n }\n\n return (\n locationStr +\n printPrefixedLines([\n [`${lineNum} |`, subLines[0]],\n ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]),\n ['|', '^'.padStart(subLineColumnNum)],\n ['|', subLines[subLineIndex + 1]],\n ])\n );\n }\n\n return (\n locationStr +\n printPrefixedLines([\n // Lines specified like this: [\"prefix\", \"string\"],\n [`${lineNum - 1} |`, lines[lineIndex - 1]],\n [`${lineNum} |`, locationLine],\n ['|', '^'.padStart(columnNum)],\n [`${lineNum + 1} |`, lines[lineIndex + 1]],\n ])\n );\n}\n\nfunction printPrefixedLines(lines) {\n const existingLines = lines.filter(([_, line]) => line !== undefined);\n const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));\n return existingLines\n .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : ''))\n .join('\\n');\n}\n","import { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { getLocation } from '../language/location.mjs';\nimport {\n printLocation,\n printSourceLocation,\n} from '../language/printLocation.mjs';\n\nfunction toNormalizedOptions(args) {\n const firstArg = args[0];\n\n if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) {\n return {\n nodes: firstArg,\n source: args[1],\n positions: args[2],\n path: args[3],\n originalError: args[4],\n extensions: args[5],\n };\n }\n\n return firstArg;\n}\n/**\n * A GraphQLError describes an Error found during the parse, validate, or\n * execute phases of performing a GraphQL operation. In addition to a message\n * and stack trace, it also includes information about the locations in a\n * GraphQL document and/or execution result that correspond to the Error.\n */\n\nexport class GraphQLError extends Error {\n /**\n * An array of `{ line, column }` locations within the source GraphQL document\n * which correspond to this error.\n *\n * Errors during validation often contain multiple locations, for example to\n * point out two things with the same name. Errors during execution include a\n * single location, the field which produced the error.\n *\n * Enumerable, and appears in the result of JSON.stringify().\n */\n\n /**\n * An array describing the JSON-path into the execution response which\n * corresponds to this error. Only included for errors during execution.\n *\n * Enumerable, and appears in the result of JSON.stringify().\n */\n\n /**\n * An array of GraphQL AST Nodes corresponding to this error.\n */\n\n /**\n * The source GraphQL document for the first location of this error.\n *\n * Note that if this Error represents more than one node, the source may not\n * represent nodes after the first node.\n */\n\n /**\n * An array of character offsets within the source GraphQL document\n * which correspond to this error.\n */\n\n /**\n * The original error thrown from a field resolver during execution.\n */\n\n /**\n * Extension fields to add to the formatted error.\n */\n\n /**\n * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.\n */\n constructor(message, ...rawArgs) {\n var _this$nodes, _nodeLocations$, _ref;\n\n const { nodes, source, positions, path, originalError, extensions } =\n toNormalizedOptions(rawArgs);\n super(message);\n this.name = 'GraphQLError';\n this.path = path !== null && path !== void 0 ? path : undefined;\n this.originalError =\n originalError !== null && originalError !== void 0\n ? originalError\n : undefined; // Compute list of blame nodes.\n\n this.nodes = undefinedIfEmpty(\n Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined,\n );\n const nodeLocations = undefinedIfEmpty(\n (_this$nodes = this.nodes) === null || _this$nodes === void 0\n ? void 0\n : _this$nodes.map((node) => node.loc).filter((loc) => loc != null),\n ); // Compute locations in the source for the given nodes/positions.\n\n this.source =\n source !== null && source !== void 0\n ? source\n : nodeLocations === null || nodeLocations === void 0\n ? void 0\n : (_nodeLocations$ = nodeLocations[0]) === null ||\n _nodeLocations$ === void 0\n ? void 0\n : _nodeLocations$.source;\n this.positions =\n positions !== null && positions !== void 0\n ? positions\n : nodeLocations === null || nodeLocations === void 0\n ? void 0\n : nodeLocations.map((loc) => loc.start);\n this.locations =\n positions && source\n ? positions.map((pos) => getLocation(source, pos))\n : nodeLocations === null || nodeLocations === void 0\n ? void 0\n : nodeLocations.map((loc) => getLocation(loc.source, loc.start));\n const originalExtensions = isObjectLike(\n originalError === null || originalError === void 0\n ? void 0\n : originalError.extensions,\n )\n ? originalError === null || originalError === void 0\n ? void 0\n : originalError.extensions\n : undefined;\n this.extensions =\n (_ref =\n extensions !== null && extensions !== void 0\n ? extensions\n : originalExtensions) !== null && _ref !== void 0\n ? _ref\n : Object.create(null); // Only properties prescribed by the spec should be enumerable.\n // Keep the rest as non-enumerable.\n\n Object.defineProperties(this, {\n message: {\n writable: true,\n enumerable: true,\n },\n name: {\n enumerable: false,\n },\n nodes: {\n enumerable: false,\n },\n source: {\n enumerable: false,\n },\n positions: {\n enumerable: false,\n },\n originalError: {\n enumerable: false,\n },\n }); // Include (non-enumerable) stack trace.\n\n /* c8 ignore start */\n // FIXME: https://github.com/graphql/graphql-js/issues/2317\n\n if (\n originalError !== null &&\n originalError !== void 0 &&\n originalError.stack\n ) {\n Object.defineProperty(this, 'stack', {\n value: originalError.stack,\n writable: true,\n configurable: true,\n });\n } else if (Error.captureStackTrace) {\n Error.captureStackTrace(this, GraphQLError);\n } else {\n Object.defineProperty(this, 'stack', {\n value: Error().stack,\n writable: true,\n configurable: true,\n });\n }\n /* c8 ignore stop */\n }\n\n get [Symbol.toStringTag]() {\n return 'GraphQLError';\n }\n\n toString() {\n let output = this.message;\n\n if (this.nodes) {\n for (const node of this.nodes) {\n if (node.loc) {\n output += '\\n\\n' + printLocation(node.loc);\n }\n }\n } else if (this.source && this.locations) {\n for (const location of this.locations) {\n output += '\\n\\n' + printSourceLocation(this.source, location);\n }\n }\n\n return output;\n }\n\n toJSON() {\n const formattedError = {\n message: this.message,\n };\n\n if (this.locations != null) {\n formattedError.locations = this.locations;\n }\n\n if (this.path != null) {\n formattedError.path = this.path;\n }\n\n if (this.extensions != null && Object.keys(this.extensions).length > 0) {\n formattedError.extensions = this.extensions;\n }\n\n return formattedError;\n }\n}\n\nfunction undefinedIfEmpty(array) {\n return array === undefined || array.length === 0 ? undefined : array;\n}\n/**\n * See: https://spec.graphql.org/draft/#sec-Errors\n */\n\n/**\n * Prints a GraphQLError to a string, representing useful location information\n * about the error's position in the source.\n *\n * @deprecated Please use `error.toString` instead. Will be removed in v17\n */\nexport function printError(error) {\n return error.toString();\n}\n/**\n * Given a GraphQLError, format it according to the rules described by the\n * Response Format, Errors section of the GraphQL Specification.\n *\n * @deprecated Please use `error.toJSON` instead. Will be removed in v17\n */\n\nexport function formatError(error) {\n return error.toJSON();\n}\n","import { GraphQLError } from './GraphQLError.mjs';\n/**\n * Produces a GraphQLError representing a syntax error, containing useful\n * descriptive information about the syntax error's position in the source.\n */\n\nexport function syntaxError(source, position, description) {\n return new GraphQLError(`Syntax Error: ${description}`, {\n source,\n positions: [position],\n });\n}\n","/**\n * Contains a range of UTF-8 character offsets and token references that\n * identify the region of the source from which the AST derived.\n */\nexport class Location {\n /**\n * The character offset at which this Node begins.\n */\n\n /**\n * The character offset at which this Node ends.\n */\n\n /**\n * The Token at which this Node begins.\n */\n\n /**\n * The Token at which this Node ends.\n */\n\n /**\n * The Source document the AST represents.\n */\n constructor(startToken, endToken, source) {\n this.start = startToken.start;\n this.end = endToken.end;\n this.startToken = startToken;\n this.endToken = endToken;\n this.source = source;\n }\n\n get [Symbol.toStringTag]() {\n return 'Location';\n }\n\n toJSON() {\n return {\n start: this.start,\n end: this.end,\n };\n }\n}\n/**\n * Represents a range of characters represented by a lexical token\n * within a Source.\n */\n\nexport class Token {\n /**\n * The kind of Token.\n */\n\n /**\n * The character offset at which this Node begins.\n */\n\n /**\n * The character offset at which this Node ends.\n */\n\n /**\n * The 1-indexed line number on which this Token appears.\n */\n\n /**\n * The 1-indexed column number at which this Token begins.\n */\n\n /**\n * For non-punctuation tokens, represents the interpreted value of the token.\n *\n * Note: is undefined for punctuation tokens, but typed as string for\n * convenience in the parser.\n */\n\n /**\n * Tokens exist as nodes in a double-linked-list amongst all tokens\n * including ignored tokens. <SOF> is always the first node and <EOF>\n * the last.\n */\n constructor(kind, start, end, line, column, value) {\n this.kind = kind;\n this.start = start;\n this.end = end;\n this.line = line;\n this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\n this.value = value;\n this.prev = null;\n this.next = null;\n }\n\n get [Symbol.toStringTag]() {\n return 'Token';\n }\n\n toJSON() {\n return {\n kind: this.kind,\n value: this.value,\n line: this.line,\n column: this.column,\n };\n }\n}\n/**\n * The list of all possible AST node types.\n */\n\n/**\n * @internal\n */\nexport const QueryDocumentKeys = {\n Name: [],\n Document: ['definitions'],\n OperationDefinition: [\n 'description',\n 'name',\n 'variableDefinitions',\n 'directives',\n 'selectionSet',\n ],\n VariableDefinition: [\n 'description',\n 'variable',\n 'type',\n 'defaultValue',\n 'directives',\n ],\n Variable: ['name'],\n SelectionSet: ['selections'],\n Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],\n Argument: ['name', 'value'],\n FragmentSpread: ['name', 'directives'],\n InlineFragment: ['typeCondition', 'directives', 'selectionSet'],\n FragmentDefinition: [\n 'description',\n 'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0\n 'variableDefinitions',\n 'typeCondition',\n 'directives',\n 'selectionSet',\n ],\n IntValue: [],\n FloatValue: [],\n StringValue: [],\n BooleanValue: [],\n NullValue: [],\n EnumValue: [],\n ListValue: ['values'],\n ObjectValue: ['fields'],\n ObjectField: ['name', 'value'],\n Directive: ['name', 'arguments'],\n NamedType: ['name'],\n ListType: ['type'],\n NonNullType: ['type'],\n SchemaDefinition: ['description', 'directives', 'operationTypes'],\n OperationTypeDefinition: ['type'],\n ScalarTypeDefinition: ['description', 'name', 'directives'],\n ObjectTypeDefinition: [\n 'description',\n 'name',\n 'interfaces',\n 'directives',\n 'fields',\n ],\n FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],\n InputValueDefinition: [\n 'description',\n 'name',\n 'type',\n 'defaultValue',\n 'directives',\n ],\n InterfaceTypeDefinition: [\n 'description',\n 'name',\n 'interfaces',\n 'directives',\n 'fields',\n ],\n UnionTypeDefinition: ['description', 'name', 'directives', 'types'],\n EnumTypeDefinition: ['description', 'name', 'directives', 'values'],\n EnumValueDefinition: ['description', 'name', 'directives'],\n InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],\n DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],\n SchemaExtension: ['directives', 'operationTypes'],\n ScalarTypeExtension: ['name', 'directives'],\n ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n UnionTypeExtension: ['name', 'directives', 'types'],\n EnumTypeExtension: ['name', 'directives', 'values'],\n InputObjectTypeExtension: ['name', 'directives', 'fields'],\n TypeCoordinate: ['name'],\n MemberCoordinate: ['name', 'memberName'],\n ArgumentCoordinate: ['name', 'fieldName', 'argumentName'],\n DirectiveCoordinate: ['name'],\n DirectiveArgumentCoordinate: ['name', 'argumentName'],\n};\nconst kindValues = new Set(Object.keys(QueryDocumentKeys));\n/**\n * @internal\n */\n\nexport function isNode(maybeNode) {\n const maybeKind =\n maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind;\n return typeof maybeKind === 'string' && kindValues.has(maybeKind);\n}\n/** Name */\n\nvar OperationTypeNode;\n\n(function (OperationTypeNode) {\n OperationTypeNode['QUERY'] = 'query';\n OperationTypeNode['MUTATION'] = 'mutation';\n OperationTypeNode['SUBSCRIPTION'] = 'subscription';\n})(OperationTypeNode || (OperationTypeNode = {}));\n\nexport { OperationTypeNode };\n","/**\n * The set of allowed directive location values.\n */\nvar DirectiveLocation;\n\n(function (DirectiveLocation) {\n DirectiveLocation['QUERY'] = 'QUERY';\n DirectiveLocation['MUTATION'] = 'MUTATION';\n DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION';\n DirectiveLocation['FIELD'] = 'FIELD';\n DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION';\n DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD';\n DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT';\n DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION';\n DirectiveLocation['SCHEMA'] = 'SCHEMA';\n DirectiveLocation['SCALAR'] = 'SCALAR';\n DirectiveLocation['OBJECT'] = 'OBJECT';\n DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION';\n DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION';\n DirectiveLocation['INTERFACE'] = 'INTERFACE';\n DirectiveLocation['UNION'] = 'UNION';\n DirectiveLocation['ENUM'] = 'ENUM';\n DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE';\n DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT';\n DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION';\n})(DirectiveLocation || (DirectiveLocation = {}));\n\nexport { DirectiveLocation };\n/**\n * The enum type representing the directive location values.\n *\n * @deprecated Please use `DirectiveLocation`. Will be remove in v17.\n */\n","/**\n * The set of allowed kind values for AST nodes.\n */\nvar Kind;\n\n(function (Kind) {\n Kind['NAME'] = 'Name';\n Kind['DOCUMENT'] = 'Document';\n Kind['OPERATION_DEFINITION'] = 'OperationDefinition';\n Kind['VARIABLE_DEFINITION'] = 'VariableDefinition';\n Kind['SELECTION_SET'] = 'SelectionSet';\n Kind['FIELD'] = 'Field';\n Kind['ARGUMENT'] = 'Argument';\n Kind['FRAGMENT_SPREAD'] = 'FragmentSpread';\n Kind['INLINE_FRAGMENT'] = 'InlineFragment';\n Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition';\n Kind['VARIABLE'] = 'Variable';\n Kind['INT'] = 'IntValue';\n Kind['FLOAT'] = 'FloatValue';\n Kind['STRING'] = 'StringValue';\n Kind['BOOLEAN'] = 'BooleanValue';\n Kind['NULL'] = 'NullValue';\n Kind['ENUM'] = 'EnumValue';\n Kind['LIST'] = 'ListValue';\n Kind['OBJECT'] = 'ObjectValue';\n Kind['OBJECT_FIELD'] = 'ObjectField';\n Kind['DIRECTIVE'] = 'Directive';\n Kind['NAMED_TYPE'] = 'NamedType';\n Kind['LIST_TYPE'] = 'ListType';\n Kind['NON_NULL_TYPE'] = 'NonNullType';\n Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition';\n Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition';\n Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition';\n Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition';\n Kind['FIELD_DEFINITION'] = 'FieldDefinition';\n Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition';\n Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition';\n Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition';\n Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition';\n Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition';\n Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition';\n Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition';\n Kind['SCHEMA_EXTENSION'] = 'SchemaExtension';\n Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension';\n Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension';\n Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension';\n Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension';\n Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension';\n Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension';\n Kind['TYPE_COORDINATE'] = 'TypeCoordinate';\n Kind['MEMBER_COORDINATE'] = 'MemberCoordinate';\n Kind['ARGUMENT_COORDINATE'] = 'ArgumentCoordinate';\n Kind['DIRECTIVE_COORDINATE'] = 'DirectiveCoordinate';\n Kind['DIRECTIVE_ARGUMENT_COORDINATE'] = 'DirectiveArgumentCoordinate';\n})(Kind || (Kind = {}));\n\nexport { Kind };\n/**\n * The enum type representing the possible kind values of AST nodes.\n *\n * @deprecated Please use `Kind`. Will be remove in v17.\n */\n","/**\n * ```\n * WhiteSpace ::\n * - \"Horizontal Tab (U+0009)\"\n * - \"Space (U+0020)\"\n * ```\n * @internal\n */\nexport function isWhiteSpace(code) {\n return code === 0x0009 || code === 0x0020;\n}\n/**\n * ```\n * Digit :: one of\n * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`\n * ```\n * @internal\n */\n\nexport function isDigit(code) {\n return code >= 0x0030 && code <= 0x0039;\n}\n/**\n * ```\n * Letter :: one of\n * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M`\n * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z`\n * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m`\n * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z`\n * ```\n * @internal\n */\n\nexport function isLetter(code) {\n return (\n (code >= 0x0061 && code <= 0x007a) || // A-Z\n (code >= 0x0041 && code <= 0x005a) // a-z\n );\n}\n/**\n * ```\n * NameStart ::\n * - Letter\n * - `_`\n * ```\n * @internal\n */\n\nexport function isNameStart(code) {\n return isLetter(code) || code === 0x005f;\n}\n/**\n * ```\n * NameContinue ::\n * - Letter\n * - Digit\n * - `_`\n * ```\n * @internal\n */\n\nexport function isNameContinue(code) {\n return isLetter(code) || isDigit(code) || code === 0x005f;\n}\n","import { isWhiteSpace } from './characterClasses.mjs';\n/**\n * Produces the value of a block string from its parsed raw value, similar to\n * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.\n *\n * This implements the GraphQL spec's BlockStringValue() static algorithm.\n *\n * @internal\n */\n\nexport function dedentBlockStringLines(lines) {\n var _firstNonEmptyLine2;\n\n let commonIndent = Number.MAX_SAFE_INTEGER;\n let firstNonEmptyLine = null;\n let lastNonEmptyLine = -1;\n\n for (let i = 0; i < lines.length; ++i) {\n var _firstNonEmptyLine;\n\n const line = lines[i];\n const indent = leadingWhitespace(line);\n\n if (indent === line.length) {\n continue; // skip empty lines\n }\n\n firstNonEmptyLine =\n (_firstNonEmptyLine = firstNonEmptyLine) !== null &&\n _firstNonEmptyLine !== void 0\n ? _firstNonEmptyLine\n : i;\n lastNonEmptyLine = i;\n\n if (i !== 0 && indent < commonIndent) {\n commonIndent = indent;\n }\n }\n\n return lines // Remove common indentation from all lines but first.\n .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines.\n .slice(\n (_firstNonEmptyLine2 = firstNonEmptyLine) !== null &&\n _firstNonEmptyLine2 !== void 0\n ? _firstNonEmptyLine2\n : 0,\n lastNonEmptyLine + 1,\n );\n}\n\nfunction leadingWhitespace(str) {\n let i = 0;\n\n while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {\n ++i;\n }\n\n return i;\n}\n/**\n * @internal\n */\n\nexport function isPrintableAsBlockString(value) {\n if (value === '') {\n return true; // empty string is printable\n }\n\n let isEmptyLine = true;\n let hasIndent = false;\n let hasCommonIndent = true;\n let seenNonEmptyLine = false;\n\n for (let i = 0; i < value.length; ++i) {\n switch (value.codePointAt(i)) {\n case 0x0000:\n case 0x0001:\n case 0x0002:\n case 0x0003:\n case 0x0004:\n case 0x0005:\n case 0x0006:\n case 0x0007:\n case 0x0008:\n case 0x000b:\n case 0x000c:\n case 0x000e:\n case 0x000f:\n return false;\n // Has non-printable characters\n\n case 0x000d:\n // \\r\n return false;\n // Has \\r or \\r\\n which will be replaced as \\n\n\n case 10:\n // \\n\n if (isEmptyLine && !seenNonEmptyLine) {\n return false; // Has leading new line\n }\n\n seenNonEmptyLine = true;\n isEmptyLine = true;\n hasIndent = false;\n break;\n\n case 9: // \\t\n\n case 32:\n // <space>\n hasIndent || (hasIndent = isEmptyLine);\n break;\n\n default:\n hasCommonIndent && (hasCommonIndent = hasIndent);\n isEmptyLine = false;\n }\n }\n\n if (isEmptyLine) {\n return false; // Has trailing empty lines\n }\n\n if (hasCommonIndent && seenNonEmptyLine) {\n return false; // Has internal indent\n }\n\n return true;\n}\n/**\n * Print a block string in the indented block form by adding a leading and\n * trailing blank line. However, if a block string starts with whitespace and is\n * a single-line, adding a leading blank line would strip that whitespace.\n *\n * @internal\n */\n\nexport function printBlockString(value, options) {\n const escapedValue = value.replace(/\"\"\"/g, '\\\\\"\"\"'); // Expand a block string's raw value into independent lines.\n\n const lines = escapedValue.split(/\\r\\n|[\\n\\r]/g);\n const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line\n\n const forceLeadingNewLine =\n lines.length > 1 &&\n lines\n .slice(1)\n .every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line\n\n const hasTrailingTripleQuotes = escapedValue.endsWith('\\\\\"\"\"'); // Trailing quote (single or double) or slash forces trailing new line\n\n const hasTrailingQuote = value.endsWith('\"') && !hasTrailingTripleQuotes;\n const hasTrailingSlash = value.endsWith('\\\\');\n const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;\n const printAsMultipleLines =\n !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability\n (!isSingleLine ||\n value.length > 70 ||\n forceTrailingNewline ||\n forceLeadingNewLine ||\n hasTrailingTripleQuotes);\n let result = ''; // Format a multi-line block quote to account for leading space.\n\n const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));\n\n if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) {\n result += '\\n';\n }\n\n result += escapedValue;\n\n if (printAsMultipleLines || forceTrailingNewline) {\n result += '\\n';\n }\n\n return '\"\"\"' + result + '\"\"\"';\n}\n","/**\n * An exported enum describing the different kinds of tokens that the\n * lexer emits.\n */\nvar TokenKind;\n\n(function (TokenKind) {\n TokenKind['SOF'] = '<SOF>';\n TokenKind['EOF'] = '<EOF>';\n TokenKind['BANG'] = '!';\n TokenKind['DOLLAR'] = '$';\n TokenKind['AMP'] = '&';\n TokenKind['PAREN_L'] = '(';\n TokenKind['PAREN_R'] = ')';\n TokenKind['DOT'] = '.';\n TokenKind['SPREAD'] = '...';\n TokenKind['COLON'] = ':';\n TokenKind['EQUALS'] = '=';\n TokenKind['AT'] = '@';\n TokenKind['BRACKET_L'] = '[';\n TokenKind['BRACKET_R'] = ']';\n TokenKind['BRACE_L'] = '{';\n TokenKind['PIPE'] = '|';\n TokenKind['BRACE_R'] = '}';\n TokenKind['NAME'] = 'Name';\n TokenKind['INT'] = 'Int';\n TokenKind['FLOAT'] = 'Float';\n TokenKind['STRING'] = 'String';\n TokenKind['BLOCK_STRING'] = 'BlockString';\n TokenKind['COMMENT'] = 'Comment';\n})(TokenKind || (TokenKind = {}));\n\nexport { TokenKind };\n/**\n * The enum type representing the token kinds values.\n *\n * @deprecated Please use `TokenKind`. Will be remove in v17.\n */\n","import { syntaxError } from '../error/syntaxError.mjs';\nimport { Token } from './ast.mjs';\nimport { dedentBlockStringLines } from './blockString.mjs';\nimport { isDigit, isNameContinue, isNameStart } from './characterClasses.mjs';\nimport { TokenKind } from './tokenKind.mjs';\n/**\n * A Lexer interface which provides common properties and methods required for\n * lexing GraphQL source.\n *\n * @internal\n */\n\n/**\n * Given a Source object, creates a Lexer for that source.\n * A Lexer is a stateful stream generator in that every time\n * it is advanced, it returns the next token in the Source. Assuming the\n * source lexes, the final Token emitted by the lexer will be of kind\n * EOF, after which the lexer will repeatedly return the same EOF token\n * whenever called.\n */\nexport class Lexer {\n /**\n * The previously focused non-ignored token.\n */\n\n /**\n * The currently focused non-ignored token.\n */\n\n /**\n * The (1-indexed) line containing the current token.\n */\n\n /**\n * The character offset at which the current line begins.\n */\n constructor(source) {\n const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);\n this.source = source;\n this.lastToken = startOfFileToken;\n this.token = startOfFileToken;\n this.line = 1;\n this.lineStart = 0;\n }\n\n get [Symbol.toStringTag]() {\n return 'Lexer';\n }\n /**\n * Advances the token stream to the next non-ignored token.\n */\n\n advance() {\n this.lastToken = this.token;\n const token = (this.token = this.lookahead());\n return token;\n }\n /**\n * Looks ahead and returns the next non-ignored token, but does not change\n * the state of Lexer.\n */\n\n lookahead() {\n let token = this.token;\n\n if (token.kind !== TokenKind.EOF) {\n do {\n if (token.next) {\n token = token.next;\n } else {\n // Read the next token and form a link in the token linked-list.\n const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing.\n\n token.next = nextToken; // @ts-expect-error prev is only mutable during parsing.\n\n nextToken.prev = token;\n token = nextToken;\n }\n } while (token.kind === TokenKind.COMMENT);\n }\n\n return token;\n }\n}\n/**\n * @internal\n */\n\nexport function isPunctuatorTokenKind(kind) {\n return (\n kind === TokenKind.BANG ||\n kind === TokenKind.DOLLAR ||\n kind === TokenKind.AMP ||\n kind === TokenKind.PAREN_L ||\n kind === TokenKind.PAREN_R ||\n kind === TokenKind.DOT ||\n kind === TokenKind.SPREAD ||\n kind === TokenKind.COLON ||\n kind === TokenKind.EQUALS ||\n kind === TokenKind.AT ||\n kind === TokenKind.BRACKET_L ||\n kind === TokenKind.BRACKET_R ||\n kind === TokenKind.BRACE_L ||\n kind === TokenKind.PIPE ||\n kind === TokenKind.BRACE_R\n );\n}\n/**\n * A Unicode scalar value is any Unicode code point except surrogate code\n * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and\n * 0xE000 to 0x10FFFF.\n *\n * SourceCharacter ::\n * - \"Any Unicode scalar value\"\n */\n\nfunction isUnicodeScalarValue(code) {\n return (\n (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff)\n );\n}\n/**\n * The GraphQL specification defines source text as a sequence of unicode scalar\n * values (which Unicode defines to exclude surrogate code points). However\n * JavaScript defines strings as a sequence of UTF-16 code units which may\n * include surrogates. A surrogate pair is a valid source character as it\n * encodes a supplementary code point (above U+FFFF), but unpaired surrogate\n * code points are not valid source characters.\n */\n\nfunction isSupplementaryCodePoint(body, location) {\n return (\n isLeadingSurrogate(body.charCodeAt(location)) &&\n isTrailingSurrogate(body.charCodeAt(location + 1))\n );\n}\n\nfunction isLeadingSurrogate(code) {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nfunction isTrailingSurrogate(code) {\n return code >= 0xdc00 && code <= 0xdfff;\n}\n/**\n * Prints the code point (or end of file reference) at a given location in a\n * source for use in error messages.\n *\n * Printable ASCII is printed quoted, while other points are printed in Unicode\n * code point form (ie. U+1234).\n *\n * @internal\n */\n\nexport function printCodePointAt(lexer, location) {\n const code = lexer.source.body.codePointAt(location);\n\n if (code === undefined) {\n return TokenKind.EOF;\n } else if (code >= 0x0020 && code <= 0x007e) {\n // Printable ASCII\n const char = String.fromCodePoint(code);\n return char === '\"' ? \"'\\\"'\" : `\"${char}\"`;\n } // Unicode code point\n\n return 'U+' + code.toString(16).toUpperCase().padStart(4, '0');\n}\n/**\n * Create a token with line and column location information.\n *\n * @internal\n */\n\nexport function createToken(lexer, kind, start, end, value) {\n const line = lexer.line;\n const col = 1 + start - lexer.lineStart;\n return new Token(kind, start, end, line, col, value);\n}\n/**\n * Gets the next token from the source starting at the given position.\n *\n * This skips over whitespace until it finds the next lexable token, then lexes\n * punctuators immediately or calls the appropriate helper function for more\n * complicated tokens.\n */\n\nfunction readNextToken(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start;\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // SourceCharacter\n\n switch (code) {\n // Ignored ::\n // - UnicodeBOM\n // - WhiteSpace\n // - LineTerminator\n // - Comment\n // - Comma\n //\n // UnicodeBOM :: \"Byte Order Mark (U+FEFF)\"\n //\n // WhiteSpace ::\n // - \"Horizontal Tab (U+0009)\"\n // - \"Space (U+0020)\"\n //\n // Comma :: ,\n case 0xfeff: // <BOM>\n\n case 0x0009: // \\t\n\n case 0x0020: // <space>\n\n case 0x002c:\n // ,\n ++position;\n continue;\n // LineTerminator ::\n // - \"New Line (U+000A)\"\n // - \"Carriage Return (U+000D)\" [lookahead != \"New Line (U+000A)\"]\n // - \"Carriage Return (U+000D)\" \"New Line (U+000A)\"\n\n case 0x000a:\n // \\n\n ++position;\n ++lexer.line;\n lexer.lineStart = position;\n continue;\n\n case 0x000d:\n // \\r\n if (body.charCodeAt(position + 1) === 0x000a) {\n position += 2;\n } else {\n ++position;\n }\n\n ++lexer.line;\n lexer.lineStart = position;\n continue;\n // Comment\n\n case 0x0023:\n // #\n return readComment(lexer, position);\n // Token ::\n // - Punctuator\n // - Name\n // - IntValue\n // - FloatValue\n // - StringValue\n //\n // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }\n\n case 0x0021:\n // !\n return createToken(lexer, TokenKind.BANG, position, position + 1);\n\n case 0x0024:\n // $\n return createToken(lexer, TokenKind.DOLLAR, position, position + 1);\n\n case 0x0026:\n // &\n return createToken(lexer, TokenKind.AMP, position, position + 1);\n\n case 0x0028:\n // (\n return createToken(lexer, TokenKind.PAREN_L, position, position + 1);\n\n case 0x0029:\n // )\n return createToken(lexer, TokenKind.PAREN_R, position, position + 1);\n\n case 0x002e:\n // .\n if (\n body.charCodeAt(position + 1) === 0x002e &&\n body.charCodeAt(position + 2) === 0x002e\n ) {\n return createToken(lexer, TokenKind.SPREAD, position, position + 3);\n }\n\n break;\n\n case 0x003a:\n // :\n return createToken(lexer, TokenKind.COLON, position, position + 1);\n\n case 0x003d:\n // =\n return createToken(lexer, TokenKind.EQUALS, position, position + 1);\n\n case 0x0040:\n // @\n return createToken(lexer, TokenKind.AT, position, position + 1);\n\n case 0x005b:\n // [\n return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);\n\n case 0x005d:\n // ]\n return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);\n\n case 0x007b:\n // {\n return createToken(lexer, TokenKind.BRACE_L, position, position + 1);\n\n case 0x007c:\n // |\n return createToken(lexer, TokenKind.PIPE, position, position + 1);\n\n case 0x007d:\n // }\n return createToken(lexer, TokenKind.BRACE_R, position, position + 1);\n // StringValue\n\n case 0x0022:\n // \"\n if (\n body.charCodeAt(position + 1) === 0x0022 &&\n body.charCodeAt(position + 2) === 0x0022\n ) {\n return readBlockString(lexer, position);\n }\n\n return readString(lexer, position);\n } // IntValue | FloatValue (Digit | -)\n\n if (isDigit(code) || code === 0x002d) {\n return readNumber(lexer, position, code);\n } // Name\n\n if (isNameStart(code)) {\n return readName(lexer, position);\n }\n\n throw syntaxError(\n lexer.source,\n position,\n code === 0x0027\n ? 'Unexpected single quote character (\\'), did you mean to use a double quote (\")?'\n : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position)\n ? `Unexpected character: ${printCodePointAt(lexer, position)}.`\n : `Invalid character: ${printCodePointAt(lexer, position)}.`,\n );\n }\n\n return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);\n}\n/**\n * Reads a comment token from the source file.\n *\n * ```\n * Comment :: # CommentChar* [lookahead != CommentChar]\n *\n * CommentChar :: SourceCharacter but not LineTerminator\n * ```\n */\n\nfunction readComment(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start + 1;\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // LineTerminator (\\n | \\r)\n\n if (code === 0x000a || code === 0x000d) {\n break;\n } // SourceCharacter\n\n if (isUnicodeScalarValue(code)) {\n ++position;\n } else if (isSupplementaryCodePoint(body, position)) {\n position += 2;\n } else {\n break;\n }\n }\n\n return createToken(\n lexer,\n TokenKind.COMMENT,\n start,\n position,\n body.slice(start + 1, position),\n );\n}\n/**\n * Reads a number token from the source file, either a FloatValue or an IntValue\n * depending on whether a FractionalPart or ExponentPart is encountered.\n *\n * ```\n * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}]\n *\n * IntegerPart ::\n * - NegativeSign? 0\n * - NegativeSign? NonZeroDigit Digit*\n *\n * NegativeSign :: -\n *\n * NonZeroDigit :: Digit but not `0`\n *\n * FloatValue ::\n * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}]\n * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}]\n * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}]\n *\n * FractionalPart :: . Digit+\n *\n * ExponentPart :: ExponentIndicator Sign? Digit+\n *\n * ExponentIndicator :: one of `e` `E`\n *\n * Sign :: one of + -\n * ```\n */\n\nfunction readNumber(lexer, start, firstCode) {\n const body = lexer.source.body;\n let position = start;\n let code = firstCode;\n let isFloat = false; // NegativeSign (-)\n\n if (code === 0x002d) {\n code = body.charCodeAt(++position);\n } // Zero (0)\n\n if (code === 0x0030) {\n code = body.charCodeAt(++position);\n\n if (isDigit(code)) {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid number, unexpected digit after 0: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n } else {\n position = readDigits(lexer, position, code);\n code = body.charCodeAt(position);\n } // Full stop (.)\n\n if (code === 0x002e) {\n isFloat = true;\n code = body.charCodeAt(++position);\n position = readDigits(lexer, position, code);\n code = body.charCodeAt(position);\n } // E e\n\n if (code === 0x0045 || code === 0x0065) {\n isFloat = true;\n code = body.charCodeAt(++position); // + -\n\n if (code === 0x002b || code === 0x002d) {\n code = body.charCodeAt(++position);\n }\n\n position = readDigits(lexer, position, code);\n code = body.charCodeAt(position);\n } // Numbers cannot be followed by . or NameStart\n\n if (code === 0x002e || isNameStart(code)) {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid number, expected digit but got: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n\n return createToken(\n lexer,\n isFloat ? TokenKind.FLOAT : TokenKind.INT,\n start,\n position,\n body.slice(start, position),\n );\n}\n/**\n * Returns the new position in the source after reading one or more digits.\n */\n\nfunction readDigits(lexer, start, firstCode) {\n if (!isDigit(firstCode)) {\n throw syntaxError(\n lexer.source,\n start,\n `Invalid number, expected digit but got: ${printCodePointAt(\n lexer,\n start,\n )}.`,\n );\n }\n\n const body = lexer.source.body;\n let position = start + 1; // +1 to skip first firstCode\n\n while (isDigit(body.charCodeAt(position))) {\n ++position;\n }\n\n return position;\n}\n/**\n * Reads a single-quote string token from the source file.\n *\n * ```\n * StringValue ::\n * - `\"\"` [lookahead != `\"`]\n * - `\"` StringCharacter+ `\"`\n *\n * StringCharacter ::\n * - SourceCharacter but not `\"` or `\\` or LineTerminator\n * - `\\u` EscapedUnicode\n * - `\\` EscapedCharacter\n *\n * EscapedUnicode ::\n * - `{` HexDigit+ `}`\n * - HexDigit HexDigit HexDigit HexDigit\n *\n * EscapedCharacter :: one of `\"` `\\` `/` `b` `f` `n` `r` `t`\n * ```\n */\n\nfunction readString(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start + 1;\n let chunkStart = position;\n let value = '';\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // Closing Quote (\")\n\n if (code === 0x0022) {\n value += body.slice(chunkStart, position);\n return createToken(lexer, TokenKind.STRING, start, position + 1, value);\n } // Escape Sequence (\\)\n\n if (code === 0x005c) {\n value += body.slice(chunkStart, position);\n const escape =\n body.charCodeAt(position + 1) === 0x0075 // u\n ? body.charCodeAt(position + 2) === 0x007b // {\n ? readEscapedUnicodeVariableWidth(lexer, position)\n : readEscapedUnicodeFixedWidth(lexer, position)\n : readEscapedCharacter(lexer, position);\n value += escape.value;\n position += escape.size;\n chunkStart = position;\n continue;\n } // LineTerminator (\\n | \\r)\n\n if (code === 0x000a || code === 0x000d) {\n break;\n } // SourceCharacter\n\n if (isUnicodeScalarValue(code)) {\n ++position;\n } else if (isSupplementaryCodePoint(body, position)) {\n position += 2;\n } else {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid character within String: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n }\n\n throw syntaxError(lexer.source, position, 'Unterminated string.');\n} // The string value and lexed size of an escape sequence.\n\nfunction readEscapedUnicodeVariableWidth(lexer, position) {\n const body = lexer.source.body;\n let point = 0;\n let size = 3; // Cannot be larger than 12 chars (\\u{00000000}).\n\n while (size < 12) {\n const code = body.charCodeAt(position + size++); // Closing Brace (})\n\n if (code === 0x007d) {\n // Must be at least 5 chars (\\u{0}) and encode a Unicode scalar value.\n if (size < 5 || !isUnicodeScalarValue(point)) {\n break;\n }\n\n return {\n value: String.fromCodePoint(point),\n size,\n };\n } // Append this hex digit to the code point.\n\n point = (point << 4) | readHexDigit(code);\n\n if (point < 0) {\n break;\n }\n }\n\n throw syntaxError(\n lexer.source,\n position,\n `Invalid Unicode escape sequence: \"${body.slice(\n position,\n position + size,\n )}\".`,\n );\n}\n\nfunction readEscapedUnicodeFixedWidth(lexer, position) {\n const body = lexer.source.body;\n const code = read16BitHexCode(body, position + 2);\n\n if (isUnicodeScalarValue(code)) {\n return {\n value: String.fromCodePoint(code),\n size: 6,\n };\n } // GraphQL allows JSON-style surrogate pair escape sequences, but only when\n // a valid pair is formed.\n\n if (isLeadingSurrogate(code)) {\n // \\u\n if (\n body.charCodeAt(position + 6) === 0x005c &&\n body.charCodeAt(position + 7) === 0x0075\n ) {\n const trailingCode = read16BitHexCode(body, position + 8);\n\n if (isTrailingSurrogate(trailingCode)) {\n // JavaScript defines strings as a sequence of UTF-16 code units and\n // encodes Unicode code points above U+FFFF using a surrogate pair of\n // code units. Since this is a surrogate pair escape sequence, just\n // include both codes into the JavaScript string value. Had JavaScript\n // not been internally based on UTF-16, then this surrogate pair would\n // be decoded to retrieve the supplementary code point.\n return {\n value: String.fromCodePoint(code, trailingCode),\n size: 12,\n };\n }\n }\n }\n\n throw syntaxError(\n lexer.source,\n position,\n `Invalid Unicode escape sequence: \"${body.slice(position, position + 6)}\".`,\n );\n}\n/**\n * Reads four hexadecimal characters and returns the positive integer that 16bit\n * hexadecimal string represents. For example, \"000f\" will return 15, and \"dead\"\n * will return 57005.\n *\n * Returns a negative number if any char was not a valid hexadecimal digit.\n */\n\nfunction read16BitHexCode(body, position) {\n // readHexDigit() returns -1 on error. ORing a negative value with any other\n // value always produces a negative value.\n return (\n (readHexDigit(body.charCodeAt(position)) << 12) |\n (readHexDigit(body.charCodeAt(position + 1)) << 8) |\n (readHexDigit(body.charCodeAt(position + 2)) << 4) |\n readHexDigit(body.charCodeAt(position + 3))\n );\n}\n/**\n * Reads a hexadecimal character and returns its positive integer value (0-15).\n *\n * '0' becomes 0, '9' becomes 9\n * 'A' becomes 10, 'F' becomes 15\n * 'a' becomes 10, 'f' becomes 15\n *\n * Returns -1 if the provided character code was not a valid hexadecimal digit.\n *\n * HexDigit :: one of\n * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`\n * - `A` `B` `C` `D` `E` `F`\n * - `a` `b` `c` `d` `e` `f`\n */\n\nfunction readHexDigit(code) {\n return code >= 0x0030 && code <= 0x0039 // 0-9\n ? code - 0x0030\n : code >= 0x0041 && code <= 0x0046 // A-F\n ? code - 0x0037\n : code >= 0x0061 && code <= 0x0066 // a-f\n ? code - 0x0057\n : -1;\n}\n/**\n * | Escaped Character | Code Point | Character Name |\n * | ----------------- | ---------- | ---------------------------- |\n * | `\"` | U+0022 | double quote |\n * | `\\` | U+005C | reverse solidus (back slash) |\n * | `/` | U+002F | solidus (forward slash) |\n * | `b` | U+0008 | backspace |\n * | `f` | U+000C | form feed |\n * | `n` | U+000A | line feed (new line) |\n * | `r` | U+000D | carriage return |\n * | `t` | U+0009 | horizontal tab |\n */\n\nfunction readEscapedCharacter(lexer, position) {\n const body = lexer.source.body;\n const code = body.charCodeAt(position + 1);\n\n switch (code) {\n case 0x0022:\n // \"\n return {\n value: '\\u0022',\n size: 2,\n };\n\n case 0x005c:\n // \\\n return {\n value: '\\u005c',\n size: 2,\n };\n\n case 0x002f:\n // /\n return {\n value: '\\u002f',\n size: 2,\n };\n\n case 0x0062:\n // b\n return {\n value: '\\u0008',\n size: 2,\n };\n\n case 0x0066:\n // f\n return {\n value: '\\u000c',\n size: 2,\n };\n\n case 0x006e:\n // n\n return {\n value: '\\u000a',\n size: 2,\n };\n\n case 0x0072:\n // r\n return {\n value: '\\u000d',\n size: 2,\n };\n\n case 0x0074:\n // t\n return {\n value: '\\u0009',\n size: 2,\n };\n }\n\n throw syntaxError(\n lexer.source,\n position,\n `Invalid character escape sequence: \"${body.slice(\n position,\n position + 2,\n )}\".`,\n );\n}\n/**\n * Reads a block string token from the source file.\n *\n * ```\n * StringValue ::\n * - `\"\"\"` BlockStringCharacter* `\"\"\"`\n *\n * BlockStringCharacter ::\n * - SourceCharacter but not `\"\"\"` or `\\\"\"\"`\n * - `\\\"\"\"`\n * ```\n */\n\nfunction readBlockString(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let lineStart = lexer.lineStart;\n let position = start + 3;\n let chunkStart = position;\n let currentLine = '';\n const blockLines = [];\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // Closing Triple-Quote (\"\"\")\n\n if (\n code === 0x0022 &&\n body.charCodeAt(position + 1) === 0x0022 &&\n body.charCodeAt(position + 2) === 0x0022\n ) {\n currentLine += body.slice(chunkStart, position);\n blockLines.push(currentLine);\n const token = createToken(\n lexer,\n TokenKind.BLOCK_STRING,\n start,\n position + 3, // Return a string of the lines joined with U+000A.\n dedentBlockStringLines(blockLines).join('\\n'),\n );\n lexer.line += blockLines.length - 1;\n lexer.lineStart = lineStart;\n return token;\n } // Escaped Triple-Quote (\\\"\"\")\n\n if (\n code === 0x005c &&\n body.charCodeAt(position + 1) === 0x0022 &&\n body.charCodeAt(position + 2) === 0x0022 &&\n body.charCodeAt(position + 3) === 0x0022\n ) {\n currentLine += body.slice(chunkStart, position);\n chunkStart = position + 1; // skip only slash\n\n position += 4;\n continue;\n } // LineTerminator\n\n if (code === 0x000a || code === 0x000d) {\n currentLine += body.slice(chunkStart, position);\n blockLines.push(currentLine);\n\n if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) {\n position += 2;\n } else {\n ++position;\n }\n\n currentLine = '';\n chunkStart = position;\n lineStart = position;\n continue;\n } // SourceCharacter\n\n if (isUnicodeScalarValue(code)) {\n ++position;\n } else if (isSupplementaryCodePoint(body, position)) {\n position += 2;\n } else {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid character within String: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n }\n\n throw syntaxError(lexer.source, position, 'Unterminated string.');\n}\n/**\n * Reads an alphanumeric + underscore name from the source.\n *\n * ```\n * Name ::\n * - NameStart NameContinue* [lookahead != NameContinue]\n * ```\n *\n * @internal\n */\n\nexport function readName(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start + 1;\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position);\n\n if (isNameContinue(code)) {\n ++position;\n } else {\n break;\n }\n }\n\n return createToken(\n lexer,\n TokenKind.NAME,\n start,\n position,\n body.slice(start, position),\n );\n}\n","const MAX_ARRAY_LENGTH = 10;\nconst MAX_RECURSIVE_DEPTH = 2;\n/**\n * Used to print values in error messages.\n */\n\nexport function inspect(value) {\n return formatValue(value, []);\n}\n\nfunction formatValue(value, seenValues) {\n switch (typeof value) {\n case 'string':\n return JSON.stringify(value);\n\n case 'function':\n return value.name ? `[function ${value.name}]` : '[function]';\n\n case 'object':\n return formatObjectValue(value, seenValues);\n\n default:\n return String(value);\n }\n}\n\nfunction formatObjectValue(value, previouslySeenValues) {\n if (value === null) {\n return 'null';\n }\n\n if (previouslySeenValues.includes(value)) {\n return '[Circular]';\n }\n\n const seenValues = [...previouslySeenValues, value];\n\n if (isJSONable(value)) {\n const jsonValue = value.toJSON(); // check for infinite recursion\n\n if (jsonValue !== value) {\n return typeof jsonValue === 'string'\n ? jsonValue\n : formatValue(jsonValue, seenValues);\n }\n } else if (Array.isArray(value)) {\n return formatArray(value, seenValues);\n }\n\n return formatObject(value, seenValues);\n}\n\nfunction isJSONable(value) {\n return typeof value.toJSON === 'function';\n}\n\nfunction formatObject(object, seenValues) {\n const entries = Object.entries(object);\n\n if (entries.length === 0) {\n return '{}';\n }\n\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[' + getObjectTag(object) + ']';\n }\n\n const properties = entries.map(\n ([key, value]) => key + ': ' + formatValue(value, seenValues),\n );\n return '{ ' + properties.join(', ') + ' }';\n}\n\nfunction formatArray(array, seenValues) {\n if (array.length === 0) {\n return '[]';\n }\n\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[Array]';\n }\n\n const len = Math.min(MAX_ARRAY_LENGTH, array.length);\n const remaining = array.length - len;\n const items = [];\n\n for (let i = 0; i < len; ++i) {\n items.push(formatValue(array[i], seenValues));\n }\n\n if (remaining === 1) {\n items.push('... 1 more item');\n } else if (remaining > 1) {\n items.push(`... ${remaining} more items`);\n }\n\n return '[' + items.join(', ') + ']';\n}\n\nfunction getObjectTag(object) {\n const tag = Object.prototype.toString\n .call(object)\n .replace(/^\\[object /, '')\n .replace(/]$/, '');\n\n if (tag === 'Object' && typeof object.constructor === 'function') {\n const name = object.constructor.name;\n\n if (typeof name === 'string' && name !== '') {\n return name;\n }\n }\n\n return tag;\n}\n","import { inspect } from './inspect.mjs';\n/* c8 ignore next 3 */\n\nconst isProduction =\n globalThis.process && // eslint-disable-next-line no-undef\n process.env.NODE_ENV === 'production';\n/**\n * A replacement for instanceof which includes an error warning when multi-realm\n * constructors are detected.\n * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production\n * See: https://webpack.js.org/guides/production/\n */\n\nexport const instanceOf =\n /* c8 ignore next 6 */\n // FIXME: https://github.com/graphql/graphql-js/issues/2317\n isProduction\n ? function instanceOf(value, constructor) {\n return value instanceof constructor;\n }\n : function instanceOf(value, constructor) {\n if (value instanceof constructor) {\n return true;\n }\n\n if (typeof value === 'object' && value !== null) {\n var _value$constructor;\n\n // Prefer Symbol.toStringTag since it is immune to minification.\n const className = constructor.prototype[Symbol.toStringTag];\n const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library.\n Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009\n ? value[Symbol.toStringTag]\n : (_value$constructor = value.constructor) === null ||\n _value$constructor === void 0\n ? void 0\n : _value$constructor.name;\n\n if (className === valueClassName) {\n const stringifiedValue = inspect(value);\n throw new Error(`Cannot use ${className} \"${stringifiedValue}\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.`);\n }\n }\n\n return false;\n };\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { instanceOf } from '../jsutils/instanceOf.mjs';\n\n/**\n * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are\n * optional, but they are useful for clients who store GraphQL documents in source files.\n * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might\n * be useful for `name` to be `\"Foo.graphql\"` and location to be `{ line: 40, column: 1 }`.\n * The `line` and `column` properties in `locationOffset` are 1-indexed.\n */\nexport class Source {\n constructor(\n body,\n name = 'GraphQL request',\n locationOffset = {\n line: 1,\n column: 1,\n },\n ) {\n typeof body === 'string' ||\n devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);\n this.body = body;\n this.name = name;\n this.locationOffset = locationOffset;\n this.locationOffset.line > 0 ||\n devAssert(\n false,\n 'line in locationOffset is 1-indexed and must be positive.',\n );\n this.locationOffset.column > 0 ||\n devAssert(\n false,\n 'column in locationOffset is 1-indexed and must be positive.',\n );\n }\n\n get [Symbol.toStringTag]() {\n return 'Source';\n }\n}\n/**\n * Test if the given value is a Source object.\n *\n * @internal\n */\n\nexport function isSource(source) {\n return instanceOf(source, Source);\n}\n","import { syntaxError } from '../error/syntaxError.mjs';\nimport { Location, OperationTypeNode } from './ast.mjs';\nimport { DirectiveLocation } from './directiveLocation.mjs';\nimport { Kind } from './kinds.mjs';\nimport { isPunctuatorTokenKind, Lexer } from './lexer.mjs';\nimport { SchemaCoordinateLexer } from './schemaCoordinateLexer.mjs';\nimport { isSource, Source } from './source.mjs';\nimport { TokenKind } from './tokenKind.mjs';\n/**\n * Configuration options to control parser behavior\n */\n\n/**\n * Given a GraphQL source, parses it into a Document.\n * Throws GraphQLError if a syntax error is encountered.\n */\nexport function parse(source, options) {\n const parser = new Parser(source, options);\n const document = parser.parseDocument();\n Object.defineProperty(document, 'tokenCount', {\n enumerable: false,\n value: parser.tokenCount,\n });\n return document;\n}\n/**\n * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for\n * that value.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Values directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: valueFromAST().\n */\n\nexport function parseValue(source, options) {\n const parser = new Parser(source, options);\n parser.expectToken(TokenKind.SOF);\n const value = parser.parseValueLiteral(false);\n parser.expectToken(TokenKind.EOF);\n return value;\n}\n/**\n * Similar to parseValue(), but raises a parse error if it encounters a\n * variable. The return type will be a constant value.\n */\n\nexport function parseConstValue(source, options) {\n const parser = new Parser(source, options);\n parser.expectToken(TokenKind.SOF);\n const value = parser.parseConstValueLiteral();\n parser.expectToken(TokenKind.EOF);\n return value;\n}\n/**\n * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for\n * that type.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Types directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: typeFromAST().\n */\n\nexport function parseType(source, options) {\n const parser = new Parser(source, options);\n parser.expectToken(TokenKind.SOF);\n const type = parser.parseTypeReference();\n parser.expectToken(TokenKind.EOF);\n return type;\n}\n/**\n * Given a string containing a GraphQL Schema Coordinate (ex. `Type.field`),\n * parse the AST for that schema coordinate.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * Consider providing the results to the utility function:\n * resolveASTSchemaCoordinate(). Or calling resolveSchemaCoordinate() directly\n * with an unparsed source.\n */\n\nexport function parseSchemaCoordinate(source) {\n const sourceObj = isSource(source) ? source : new Source(source);\n const lexer = new SchemaCoordinateLexer(sourceObj);\n const parser = new Parser(source, {\n lexer,\n });\n parser.expectToken(TokenKind.SOF);\n const coordinate = parser.parseSchemaCoordinate();\n parser.expectToken(TokenKind.EOF);\n return coordinate;\n}\n/**\n * This class is exported only to assist people in implementing their own parsers\n * without duplicating too much code and should be used only as last resort for cases\n * such as experimental syntax or if certain features could not be contributed upstream.\n *\n * It is still part of the internal API and is versioned, so any changes to it are never\n * considered breaking changes. If you still need to support multiple versions of the\n * library, please use the `versionInfo` variable for version detection.\n *\n * @internal\n */\n\nexport class Parser {\n constructor(source, options = {}) {\n const { lexer, ..._options } = options;\n\n if (lexer) {\n this._lexer = lexer;\n } else {\n const sourceObj = isSource(source) ? source : new Source(source);\n this._lexer = new Lexer(sourceObj);\n }\n\n this._options = _options;\n this._tokenCounter = 0;\n }\n\n get tokenCount() {\n return this._tokenCounter;\n }\n /**\n * Converts a name lex token into a name parse node.\n */\n\n parseName() {\n const token = this.expectToken(TokenKind.NAME);\n return this.node(token, {\n kind: Kind.NAME,\n value: token.value,\n });\n } // Implements the parsing rules in the Document section.\n\n /**\n * Document : Definition+\n */\n\n parseDocument() {\n return this.node(this._lexer.token, {\n kind: Kind.DOCUMENT,\n definitions: this.many(\n TokenKind.SOF,\n this.parseDefinition,\n TokenKind.EOF,\n ),\n });\n }\n /**\n * Definition :\n * - ExecutableDefinition\n * - TypeSystemDefinition\n * - TypeSystemExtension\n *\n * ExecutableDefinition :\n * - OperationDefinition\n * - FragmentDefinition\n *\n * TypeSystemDefinition :\n * - SchemaDefinition\n * - TypeDefinition\n * - DirectiveDefinition\n *\n * TypeDefinition :\n * - ScalarTypeDefinition\n * - ObjectTypeDefinition\n * - InterfaceTypeDefinition\n * - UnionTypeDefinition\n * - EnumTypeDefinition\n * - InputObjectTypeDefinition\n */\n\n parseDefinition() {\n if (this.peek(TokenKind.BRACE_L)) {\n return this.parseOperationDefinition();\n } // Many definitions begin with a description and require a lookahead.\n\n const hasDescription = this.peekDescription();\n const keywordToken = hasDescription\n ? this._lexer.lookahead()\n : this._lexer.token;\n\n if (hasDescription && keywordToken.kind === TokenKind.BRACE_L) {\n throw syntaxError(\n this._lexer.source,\n this._lexer.token.start,\n 'Unexpected description, descriptions are not supported on shorthand queries.',\n );\n }\n\n if (keywordToken.kind === TokenKind.NAME) {\n switch (keywordToken.value) {\n case 'schema':\n return this.parseSchemaDefinition();\n\n case 'scalar':\n return this.parseScalarTypeDefinition();\n\n case 'type':\n return this.parseObjectTypeDefinition();\n\n case 'interface':\n return this.parseInterfaceTypeDefinition();\n\n case 'union':\n return this.parseUnionTypeDefinition();\n\n case 'enum':\n return this.parseEnumTypeDefinition();\n\n case 'input':\n return this.parseInputObjectTypeDefinition();\n\n case 'directive':\n return this.parseDirectiveDefinition();\n }\n\n switch (keywordToken.value) {\n case 'query':\n case 'mutation':\n case 'subscription':\n return this.parseOperationDefinition();\n\n case 'fragment':\n return this.parseFragmentDefinition();\n }\n\n if (hasDescription) {\n throw syntaxError(\n this._lexer.source,\n this._lexer.token.start,\n 'Unexpected description, only GraphQL definitions support descriptions.',\n );\n }\n\n switch (keywordToken.value) {\n case 'extend':\n return this.parseTypeSystemExtension();\n }\n }\n\n throw this.unexpected(keywordToken);\n } // Implements the parsing rules in the Operations section.\n\n /**\n * OperationDefinition :\n * - SelectionSet\n * - OperationType Name? VariableDefinitions? Directives? SelectionSet\n */\n\n parseOperationDefinition() {\n const start = this._lexer.token;\n\n if (this.peek(TokenKind.BRACE_L)) {\n return this.node(start, {\n kind: Kind.OPERATION_DEFINITION,\n operation: OperationTypeNode.QUERY,\n description: undefined,\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: this.parseSelectionSet(),\n });\n }\n\n const description = this.parseDescription();\n const operation = this.parseOperationType();\n let name;\n\n if (this.peek(TokenKind.NAME)) {\n name = this.parseName();\n }\n\n return this.node(start, {\n kind: Kind.OPERATION_DEFINITION,\n operation,\n description,\n name,\n variableDefinitions: this.parseVariableDefinitions(),\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n /**\n * OperationType : one of query mutation subscription\n */\n\n parseOperationType() {\n const operationToken = this.expectToken(TokenKind.NAME);\n\n switch (operationToken.value) {\n case 'query':\n return OperationTypeNode.QUERY;\n\n case 'mutation':\n return OperationTypeNode.MUTATION;\n\n case 'subscription':\n return OperationTypeNode.SUBSCRIPTION;\n }\n\n throw this.unexpected(operationToken);\n }\n /**\n * VariableDefinitions : ( VariableDefinition+ )\n */\n\n parseVariableDefinitions() {\n return this.optionalMany(\n TokenKind.PAREN_L,\n this.parseVariableDefinition,\n TokenKind.PAREN_R,\n );\n }\n /**\n * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?\n */\n\n parseVariableDefinition() {\n return this.node(this._lexer.token, {\n kind: Kind.VARIABLE_DEFINITION,\n description: this.parseDescription(),\n variable: this.parseVariable(),\n type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),\n defaultValue: this.expectOptionalToken(TokenKind.EQUALS)\n ? this.parseConstValueLiteral()\n : undefined,\n directives: this.parseConstDirectives(),\n });\n }\n /**\n * Variable : $ Name\n */\n\n parseVariable() {\n const start = this._lexer.token;\n this.expectToken(TokenKind.DOLLAR);\n return this.node(start, {\n kind: Kind.VARIABLE,\n name: this.parseName(),\n });\n }\n /**\n * ```\n * SelectionSet : { Selection+ }\n * ```\n */\n\n parseSelectionSet() {\n return this.node(this._lexer.token, {\n kind: Kind.SELECTION_SET,\n selections: this.many(\n TokenKind.BRACE_L,\n this.parseSelection,\n TokenKind.BRACE_R,\n ),\n });\n }\n /**\n * Selection :\n * - Field\n * - FragmentSpread\n * - InlineFragment\n */\n\n parseSelection() {\n return this.peek(TokenKind.SPREAD)\n ? this.parseFragment()\n : this.parseField();\n }\n /**\n * Field : Alias? Name Arguments? Directives? SelectionSet?\n *\n * Alias : Name :\n */\n\n parseField() {\n const start = this._lexer.token;\n const nameOrAlias = this.parseName();\n let alias;\n let name;\n\n if (this.expectOptionalToken(TokenKind.COLON)) {\n alias = nameOrAlias;\n name = this.parseName();\n } else {\n name = nameOrAlias;\n }\n\n return this.node(start, {\n kind: Kind.FIELD,\n alias,\n name,\n arguments: this.parseArguments(false),\n directives: this.parseDirectives(false),\n selectionSet: this.peek(TokenKind.BRACE_L)\n ? this.parseSelectionSet()\n : undefined,\n });\n }\n /**\n * Arguments[Const] : ( Argument[?Const]+ )\n */\n\n parseArguments(isConst) {\n const item = isConst ? this.parseConstArgument : this.parseArgument;\n return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);\n }\n /**\n * Argument[Const] : Name : Value[?Const]\n */\n\n parseArgument(isConst = false) {\n const start = this._lexer.token;\n const name = this.parseName();\n this.expectToken(TokenKind.COLON);\n return this.node(start, {\n kind: Kind.ARGUMENT,\n name,\n value: this.parseValueLiteral(isConst),\n });\n }\n\n parseConstArgument() {\n return this.parseArgument(true);\n } // Implements the parsing rules in the Fragments section.\n\n /**\n * Corresponds to both FragmentSpread and InlineFragment in the spec.\n *\n * FragmentSpread : ... FragmentName Directives?\n *\n * InlineFragment : ... TypeCondition? Directives? SelectionSet\n */\n\n parseFragment() {\n const start = this._lexer.token;\n this.expectToken(TokenKind.SPREAD);\n const hasTypeCondition = this.expectOptionalKeyword('on');\n\n if (!hasTypeCondition && this.peek(TokenKind.NAME)) {\n return this.node(start, {\n kind: Kind.FRAGMENT_SPREAD,\n name: this.parseFragmentName(),\n directives: this.parseDirectives(false),\n });\n }\n\n return this.node(start, {\n kind: Kind.INLINE_FRAGMENT,\n typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n /**\n * FragmentDefinition :\n * - fragment FragmentName on TypeCondition Directives? SelectionSet\n *\n * TypeCondition : NamedType\n */\n\n parseFragmentDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes\n // the grammar of FragmentDefinition:\n // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet\n\n if (this._options.allowLegacyFragmentVariables === true) {\n return this.node(start, {\n kind: Kind.FRAGMENT_DEFINITION,\n description,\n name: this.parseFragmentName(),\n variableDefinitions: this.parseVariableDefinitions(),\n typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n\n return this.node(start, {\n kind: Kind.FRAGMENT_DEFINITION,\n description,\n name: this.parseFragmentName(),\n typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n /**\n * FragmentName : Name but not `on`\n */\n\n parseFragmentName() {\n if (this._lexer.token.value === 'on') {\n throw this.unexpected();\n }\n\n return this.parseName();\n } // Implements the parsing rules in the Values section.\n\n /**\n * Value[Const] :\n * - [~Const] Variable\n * - IntValue\n * - FloatValue\n * - StringValue\n * - BooleanValue\n * - NullValue\n * - EnumValue\n * - ListValue[?Const]\n * - ObjectValue[?Const]\n *\n * BooleanValue : one of `true` `false`\n *\n * NullValue : `null`\n *\n * EnumValue : Name but not `true`, `false` or `null`\n */\n\n parseValueLiteral(isConst) {\n const token = this._lexer.token;\n\n switch (token.kind) {\n case TokenKind.BRACKET_L:\n return this.parseList(isConst);\n\n case TokenKind.BRACE_L:\n return this.parseObject(isConst);\n\n case TokenKind.INT:\n this.advanceLexer();\n return this.node(token, {\n kind: Kind.INT,\n value: token.value,\n });\n\n case TokenKind.FLOAT:\n this.advanceLexer();\n return this.node(token, {\n kind: Kind.FLOAT,\n value: token.value,\n });\n\n case TokenKind.STRING:\n case TokenKind.BLOCK_STRING:\n return this.parseStringLiteral();\n\n case TokenKind.NAME:\n this.advanceLexer();\n\n switch (token.value) {\n case 'true':\n return this.node(token, {\n kind: Kind.BOOLEAN,\n value: true,\n });\n\n case 'false':\n return this.node(token, {\n kind: Kind.BOOLEAN,\n value: false,\n });\n\n case 'null':\n return this.node(token, {\n kind: Kind.NULL,\n });\n\n default:\n return this.node(token, {\n kind: Kind.ENUM,\n value: token.value,\n });\n }\n\n case TokenKind.DOLLAR:\n if (isConst) {\n this.expectToken(TokenKind.DOLLAR);\n\n if (this._lexer.token.kind === TokenKind.NAME) {\n const varName = this._lexer.token.value;\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Unexpected variable \"$${varName}\" in constant value.`,\n );\n } else {\n throw this.unexpected(token);\n }\n }\n\n return this.parseVariable();\n\n default:\n throw this.unexpected();\n }\n }\n\n parseConstValueLiteral() {\n return this.parseValueLiteral(true);\n }\n\n parseStringLiteral() {\n const token = this._lexer.token;\n this.advanceLexer();\n return this.node(token, {\n kind: Kind.STRING,\n value: token.value,\n block: token.kind === TokenKind.BLOCK_STRING,\n });\n }\n /**\n * ListValue[Const] :\n * - [ ]\n * - [ Value[?Const]+ ]\n */\n\n parseList(isConst) {\n const item = () => this.parseValueLiteral(isConst);\n\n return this.node(this._lexer.token, {\n kind: Kind.LIST,\n values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),\n });\n }\n /**\n * ```\n * ObjectValue[Const] :\n * - { }\n * - { ObjectField[?Const]+ }\n * ```\n */\n\n parseObject(isConst) {\n const item = () => this.parseObjectField(isConst);\n\n return this.node(this._lexer.token, {\n kind: Kind.OBJECT,\n fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),\n });\n }\n /**\n * ObjectField[Const] : Name : Value[?Const]\n */\n\n parseObjectField(isConst) {\n const start = this._lexer.token;\n const name = this.parseName();\n this.expectToken(TokenKind.COLON);\n return this.node(start, {\n kind: Kind.OBJECT_FIELD,\n name,\n value: this.parseValueLiteral(isConst),\n });\n } // Implements the parsing rules in the Directives section.\n\n /**\n * Directives[Const] : Directive[?Const]+\n */\n\n parseDirectives(isConst) {\n const directives = [];\n\n while (this.peek(TokenKind.AT)) {\n directives.push(this.parseDirective(isConst));\n }\n\n return directives;\n }\n\n parseConstDirectives() {\n return this.parseDirectives(true);\n }\n /**\n * ```\n * Directive[Const] : @ Name Arguments[?Const]?\n * ```\n */\n\n parseDirective(isConst) {\n const start = this._lexer.token;\n this.expectToken(TokenKind.AT);\n return this.node(start, {\n kind: Kind.DIRECTIVE,\n name: this.parseName(),\n arguments: this.parseArguments(isConst),\n });\n } // Implements the parsing rules in the Types section.\n\n /**\n * Type :\n * - NamedType\n * - ListType\n * - NonNullType\n */\n\n parseTypeReference() {\n const start = this._lexer.token;\n let type;\n\n if (this.expectOptionalToken(TokenKind.BRACKET_L)) {\n const innerType = this.parseTypeReference();\n this.expectToken(TokenKind.BRACKET_R);\n type = this.node(start, {\n kind: Kind.LIST_TYPE,\n type: innerType,\n });\n } else {\n type = this.parseNamedType();\n }\n\n if (this.expectOptionalToken(TokenKind.BANG)) {\n return this.node(start, {\n kind: Kind.NON_NULL_TYPE,\n type,\n });\n }\n\n return type;\n }\n /**\n * NamedType : Name\n */\n\n parseNamedType() {\n return this.node(this._lexer.token, {\n kind: Kind.NAMED_TYPE,\n name: this.parseName(),\n });\n } // Implements the parsing rules in the Type Definition section.\n\n peekDescription() {\n return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);\n }\n /**\n * Description : StringValue\n */\n\n parseDescription() {\n if (this.peekDescription()) {\n return this.parseStringLiteral();\n }\n }\n /**\n * ```\n * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }\n * ```\n */\n\n parseSchemaDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('schema');\n const directives = this.parseConstDirectives();\n const operationTypes = this.many(\n TokenKind.BRACE_L,\n this.parseOperationTypeDefinition,\n TokenKind.BRACE_R,\n );\n return this.node(start, {\n kind: Kind.SCHEMA_DEFINITION,\n description,\n directives,\n operationTypes,\n });\n }\n /**\n * OperationTypeDefinition : OperationType : NamedType\n */\n\n parseOperationTypeDefinition() {\n const start = this._lexer.token;\n const operation = this.parseOperationType();\n this.expectToken(TokenKind.COLON);\n const type = this.parseNamedType();\n return this.node(start, {\n kind: Kind.OPERATION_TYPE_DEFINITION,\n operation,\n type,\n });\n }\n /**\n * ScalarTypeDefinition : Description? scalar Name Directives[Const]?\n */\n\n parseScalarTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('scalar');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.SCALAR_TYPE_DEFINITION,\n description,\n name,\n directives,\n });\n }\n /**\n * ObjectTypeDefinition :\n * Description?\n * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?\n */\n\n parseObjectTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('type');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n return this.node(start, {\n kind: Kind.OBJECT_TYPE_DEFINITION,\n description,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * ImplementsInterfaces :\n * - implements `&`? NamedType\n * - ImplementsInterfaces & NamedType\n */\n\n parseImplementsInterfaces() {\n return this.expectOptionalKeyword('implements')\n ? this.delimitedMany(TokenKind.AMP, this.parseNamedType)\n : [];\n }\n /**\n * ```\n * FieldsDefinition : { FieldDefinition+ }\n * ```\n */\n\n parseFieldsDefinition() {\n return this.optionalMany(\n TokenKind.BRACE_L,\n this.parseFieldDefinition,\n TokenKind.BRACE_R,\n );\n }\n /**\n * FieldDefinition :\n * - Description? Name ArgumentsDefinition? : Type Directives[Const]?\n */\n\n parseFieldDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n const name = this.parseName();\n const args = this.parseArgumentDefs();\n this.expectToken(TokenKind.COLON);\n const type = this.parseTypeReference();\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.FIELD_DEFINITION,\n description,\n name,\n arguments: args,\n type,\n directives,\n });\n }\n /**\n * ArgumentsDefinition : ( InputValueDefinition+ )\n */\n\n parseArgumentDefs() {\n return this.optionalMany(\n TokenKind.PAREN_L,\n this.parseInputValueDef,\n TokenKind.PAREN_R,\n );\n }\n /**\n * InputValueDefinition :\n * - Description? Name : Type DefaultValue? Directives[Const]?\n */\n\n parseInputValueDef() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n const name = this.parseName();\n this.expectToken(TokenKind.COLON);\n const type = this.parseTypeReference();\n let defaultValue;\n\n if (this.expectOptionalToken(TokenKind.EQUALS)) {\n defaultValue = this.parseConstValueLiteral();\n }\n\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.INPUT_VALUE_DEFINITION,\n description,\n name,\n type,\n defaultValue,\n directives,\n });\n }\n /**\n * InterfaceTypeDefinition :\n * - Description? interface Name Directives[Const]? FieldsDefinition?\n */\n\n parseInterfaceTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('interface');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n return this.node(start, {\n kind: Kind.INTERFACE_TYPE_DEFINITION,\n description,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * UnionTypeDefinition :\n * - Description? union Name Directives[Const]? UnionMemberTypes?\n */\n\n parseUnionTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('union');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const types = this.parseUnionMemberTypes();\n return this.node(start, {\n kind: Kind.UNION_TYPE_DEFINITION,\n description,\n name,\n directives,\n types,\n });\n }\n /**\n * UnionMemberTypes :\n * - = `|`? NamedType\n * - UnionMemberTypes | NamedType\n */\n\n parseUnionMemberTypes() {\n return this.expectOptionalToken(TokenKind.EQUALS)\n ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType)\n : [];\n }\n /**\n * EnumTypeDefinition :\n * - Description? enum Name Directives[Const]? EnumValuesDefinition?\n */\n\n parseEnumTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('enum');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const values = this.parseEnumValuesDefinition();\n return this.node(start, {\n kind: Kind.ENUM_TYPE_DEFINITION,\n description,\n name,\n directives,\n values,\n });\n }\n /**\n * ```\n * EnumValuesDefinition : { EnumValueDefinition+ }\n * ```\n */\n\n parseEnumValuesDefinition() {\n return this.optionalMany(\n TokenKind.BRACE_L,\n this.parseEnumValueDefinition,\n TokenKind.BRACE_R,\n );\n }\n /**\n * EnumValueDefinition : Description? EnumValue Directives[Const]?\n */\n\n parseEnumValueDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n const name = this.parseEnumValueName();\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.ENUM_VALUE_DEFINITION,\n description,\n name,\n directives,\n });\n }\n /**\n * EnumValue : Name but not `true`, `false` or `null`\n */\n\n parseEnumValueName() {\n if (\n this._lexer.token.value === 'true' ||\n this._lexer.token.value === 'false' ||\n this._lexer.token.value === 'null'\n ) {\n throw syntaxError(\n this._lexer.source,\n this._lexer.token.start,\n `${getTokenDesc(\n this._lexer.token,\n )} is reserved and cannot be used for an enum value.`,\n );\n }\n\n return this.parseName();\n }\n /**\n * InputObjectTypeDefinition :\n * - Description? input Name Directives[Const]? InputFieldsDefinition?\n */\n\n parseInputObjectTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('input');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n return this.node(start, {\n kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,\n description,\n name,\n directives,\n fields,\n });\n }\n /**\n * ```\n * InputFieldsDefinition : { InputValueDefinition+ }\n * ```\n */\n\n parseInputFieldsDefinition() {\n return this.optionalMany(\n TokenKind.BRACE_L,\n this.parseInputValueDef,\n TokenKind.BRACE_R,\n );\n }\n /**\n * TypeSystemExtension :\n * - SchemaExtension\n * - TypeExtension\n *\n * TypeExtension :\n * - ScalarTypeExtension\n * - ObjectTypeExtension\n * - InterfaceTypeExtension\n * - UnionTypeExtension\n * - EnumTypeExtension\n * - InputObjectTypeDefinition\n */\n\n parseTypeSystemExtension() {\n const keywordToken = this._lexer.lookahead();\n\n if (keywordToken.kind === TokenKind.NAME) {\n switch (keywordToken.value) {\n case 'schema':\n return this.parseSchemaExtension();\n\n case 'scalar':\n return this.parseScalarTypeExtension();\n\n case 'type':\n return this.parseObjectTypeExtension();\n\n case 'interface':\n return this.parseInterfaceTypeExtension();\n\n case 'union':\n return this.parseUnionTypeExtension();\n\n case 'enum':\n return this.parseEnumTypeExtension();\n\n case 'input':\n return this.parseInputObjectTypeExtension();\n }\n }\n\n throw this.unexpected(keywordToken);\n }\n /**\n * ```\n * SchemaExtension :\n * - extend schema Directives[Const]? { OperationTypeDefinition+ }\n * - extend schema Directives[Const]\n * ```\n */\n\n parseSchemaExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('schema');\n const directives = this.parseConstDirectives();\n const operationTypes = this.optionalMany(\n TokenKind.BRACE_L,\n this.parseOperationTypeDefinition,\n TokenKind.BRACE_R,\n );\n\n if (directives.length === 0 && operationTypes.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.SCHEMA_EXTENSION,\n directives,\n operationTypes,\n });\n }\n /**\n * ScalarTypeExtension :\n * - extend scalar Name Directives[Const]\n */\n\n parseScalarTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('scalar');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n\n if (directives.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.SCALAR_TYPE_EXTENSION,\n name,\n directives,\n });\n }\n /**\n * ObjectTypeExtension :\n * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n * - extend type Name ImplementsInterfaces? Directives[Const]\n * - extend type Name ImplementsInterfaces\n */\n\n parseObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('type');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.OBJECT_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * InterfaceTypeExtension :\n * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n * - extend interface Name ImplementsInterfaces? Directives[Const]\n * - extend interface Name ImplementsInterfaces\n */\n\n parseInterfaceTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('interface');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.INTERFACE_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * UnionTypeExtension :\n * - extend union Name Directives[Const]? UnionMemberTypes\n * - extend union Name Directives[Const]\n */\n\n parseUnionTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('union');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const types = this.parseUnionMemberTypes();\n\n if (directives.length === 0 && types.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.UNION_TYPE_EXTENSION,\n name,\n directives,\n types,\n });\n }\n /**\n * EnumTypeExtension :\n * - extend enum Name Directives[Const]? EnumValuesDefinition\n * - extend enum Name Directives[Const]\n */\n\n parseEnumTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('enum');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const values = this.parseEnumValuesDefinition();\n\n if (directives.length === 0 && values.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.ENUM_TYPE_EXTENSION,\n name,\n directives,\n values,\n });\n }\n /**\n * InputObjectTypeExtension :\n * - extend input Name Directives[Const]? InputFieldsDefinition\n * - extend input Name Directives[Const]\n */\n\n parseInputObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('input');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n\n if (directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n name,\n directives,\n fields,\n });\n }\n /**\n * ```\n * DirectiveDefinition :\n * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations\n * ```\n */\n\n parseDirectiveDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('directive');\n this.expectToken(TokenKind.AT);\n const name = this.parseName();\n const args = this.parseArgumentDefs();\n const repeatable = this.expectOptionalKeyword('repeatable');\n this.expectKeyword('on');\n const locations = this.parseDirectiveLocations();\n return this.node(start, {\n kind: Kind.DIRECTIVE_DEFINITION,\n description,\n name,\n arguments: args,\n repeatable,\n locations,\n });\n }\n /**\n * DirectiveLocations :\n * - `|`? DirectiveLocation\n * - DirectiveLocations | DirectiveLocation\n */\n\n parseDirectiveLocations() {\n return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);\n }\n /*\n * DirectiveLocation :\n * - ExecutableDirectiveLocation\n * - TypeSystemDirectiveLocation\n *\n * ExecutableDirectiveLocation : one of\n * `QUERY`\n * `MUTATION`\n * `SUBSCRIPTION`\n * `FIELD`\n * `FRAGMENT_DEFINITION`\n * `FRAGMENT_SPREAD`\n * `INLINE_FRAGMENT`\n *\n * TypeSystemDirectiveLocation : one of\n * `SCHEMA`\n * `SCALAR`\n * `OBJECT`\n * `FIELD_DEFINITION`\n * `ARGUMENT_DEFINITION`\n * `INTERFACE`\n * `UNION`\n * `ENUM`\n * `ENUM_VALUE`\n * `INPUT_OBJECT`\n * `INPUT_FIELD_DEFINITION`\n */\n\n parseDirectiveLocation() {\n const start = this._lexer.token;\n const name = this.parseName();\n\n if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) {\n return name;\n }\n\n throw this.unexpected(start);\n } // Schema Coordinates\n\n /**\n * SchemaCoordinate :\n * - Name\n * - Name . Name\n * - Name . Name ( Name : )\n * - \\@ Name\n * - \\@ Name ( Name : )\n */\n\n parseSchemaCoordinate() {\n const start = this._lexer.token;\n const ofDirective = this.expectOptionalToken(TokenKind.AT);\n const name = this.parseName();\n let memberName;\n\n if (!ofDirective && this.expectOptionalToken(TokenKind.DOT)) {\n memberName = this.parseName();\n }\n\n let argumentName;\n\n if (\n (ofDirective || memberName) &&\n this.expectOptionalToken(TokenKind.PAREN_L)\n ) {\n argumentName = this.parseName();\n this.expectToken(TokenKind.COLON);\n this.expectToken(TokenKind.PAREN_R);\n }\n\n if (ofDirective) {\n if (argumentName) {\n return this.node(start, {\n kind: Kind.DIRECTIVE_ARGUMENT_COORDINATE,\n name,\n argumentName,\n });\n }\n\n return this.node(start, {\n kind: Kind.DIRECTIVE_COORDINATE,\n name,\n });\n } else if (memberName) {\n if (argumentName) {\n return this.node(start, {\n kind: Kind.ARGUMENT_COORDINATE,\n name,\n fieldName: memberName,\n argumentName,\n });\n }\n\n return this.node(start, {\n kind: Kind.MEMBER_COORDINATE,\n name,\n memberName,\n });\n }\n\n return this.node(start, {\n kind: Kind.TYPE_COORDINATE,\n name,\n });\n } // Core parsing utility functions\n\n /**\n * Returns a node that, if configured to do so, sets a \"loc\" field as a\n * location object, used to identify the place in the source that created a\n * given parsed object.\n */\n\n node(startToken, node) {\n if (this._options.noLocation !== true) {\n node.loc = new Location(\n startToken,\n this._lexer.lastToken,\n this._lexer.source,\n );\n }\n\n return node;\n }\n /**\n * Determines if the next token is of a given kind\n */\n\n peek(kind) {\n return this._lexer.token.kind === kind;\n }\n /**\n * If the next token is of the given kind, return that token after advancing the lexer.\n * Otherwise, do not change the parser state and throw an error.\n */\n\n expectToken(kind) {\n const token = this._lexer.token;\n\n if (token.kind === kind) {\n this.advanceLexer();\n return token;\n }\n\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`,\n );\n }\n /**\n * If the next token is of the given kind, return \"true\" after advancing the lexer.\n * Otherwise, do not change the parser state and return \"false\".\n */\n\n expectOptionalToken(kind) {\n const token = this._lexer.token;\n\n if (token.kind === kind) {\n this.advanceLexer();\n return true;\n }\n\n return false;\n }\n /**\n * If the next token is a given keyword, advance the lexer.\n * Otherwise, do not change the parser state and throw an error.\n */\n\n expectKeyword(value) {\n const token = this._lexer.token;\n\n if (token.kind === TokenKind.NAME && token.value === value) {\n this.advanceLexer();\n } else {\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Expected \"${value}\", found ${getTokenDesc(token)}.`,\n );\n }\n }\n /**\n * If the next token is a given keyword, return \"true\" after advancing the lexer.\n * Otherwise, do not change the parser state and return \"false\".\n */\n\n expectOptionalKeyword(value) {\n const token = this._lexer.token;\n\n if (token.kind === TokenKind.NAME && token.value === value) {\n this.advanceLexer();\n return true;\n }\n\n return false;\n }\n /**\n * Helper function for creating an error when an unexpected lexed token is encountered.\n */\n\n unexpected(atToken) {\n const token =\n atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;\n return syntaxError(\n this._lexer.source,\n token.start,\n `Unexpected ${getTokenDesc(token)}.`,\n );\n }\n /**\n * Returns a possibly empty list of parse nodes, determined by the parseFn.\n * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n * Advances the parser to the next lex token after the closing token.\n */\n\n any(openKind, parseFn, closeKind) {\n this.expectToken(openKind);\n const nodes = [];\n\n while (!this.expectOptionalToken(closeKind)) {\n nodes.push(parseFn.call(this));\n }\n\n return nodes;\n }\n /**\n * Returns a list of parse nodes, determined by the parseFn.\n * It can be empty only if open token is missing otherwise it will always return non-empty list\n * that begins with a lex token of openKind and ends with a lex token of closeKind.\n * Advances the parser to the next lex token after the closing token.\n */\n\n optionalMany(openKind, parseFn, closeKind) {\n if (this.expectOptionalToken(openKind)) {\n const nodes = [];\n\n do {\n nodes.push(parseFn.call(this));\n } while (!this.expectOptionalToken(closeKind));\n\n return nodes;\n }\n\n return [];\n }\n /**\n * Returns a non-empty list of parse nodes, determined by the parseFn.\n * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n * Advances the parser to the next lex token after the closing token.\n */\n\n many(openKind, parseFn, closeKind) {\n this.expectToken(openKind);\n const nodes = [];\n\n do {\n nodes.push(parseFn.call(this));\n } while (!this.expectOptionalToken(closeKind));\n\n return nodes;\n }\n /**\n * Returns a non-empty list of parse nodes, determined by the parseFn.\n * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.\n * Advances the parser to the next lex token after last item in the list.\n */\n\n delimitedMany(delimiterKind, parseFn) {\n this.expectOptionalToken(delimiterKind);\n const nodes = [];\n\n do {\n nodes.push(parseFn.call(this));\n } while (this.expectOptionalToken(delimiterKind));\n\n return nodes;\n }\n\n advanceLexer() {\n const { maxTokens } = this._options;\n\n const token = this._lexer.advance();\n\n if (token.kind !== TokenKind.EOF) {\n ++this._tokenCounter;\n\n if (maxTokens !== undefined && this._tokenCounter > maxTokens) {\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Document contains more that ${maxTokens} tokens. Parsing aborted.`,\n );\n }\n }\n }\n}\n/**\n * A helper function to describe a token as a string for debugging.\n */\n\nfunction getTokenDesc(token) {\n const value = token.value;\n return getTokenKindDesc(token.kind) + (value != null ? ` \"${value}\"` : '');\n}\n/**\n * A helper function to describe a token kind as a string for debugging.\n */\n\nfunction getTokenKindDesc(kind) {\n return isPunctuatorTokenKind(kind) ? `\"${kind}\"` : kind;\n}\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","import { __assign } from \"tslib\";\nimport { parse } from 'graphql';\nvar docCache = new Map();\nvar fragmentSourceMap = new Map();\nvar printFragmentWarnings = true;\nvar experimentalFragmentVariables = false;\nfunction normalize(string) {\n return string.replace(/[\\s,]+/g, ' ').trim();\n}\nfunction cacheKeyFromLoc(loc) {\n return normalize(loc.source.body.substring(loc.start, loc.end));\n}\nfunction processFragments(ast) {\n var seenKeys = new Set();\n var definitions = [];\n ast.definitions.forEach(function (fragmentDefinition) {\n if (fragmentDefinition.kind === 'FragmentDefinition') {\n var fragmentName = fragmentDefinition.name.value;\n var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);\n var sourceKeySet = fragmentSourceMap.get(fragmentName);\n if (sourceKeySet && !sourceKeySet.has(sourceKey)) {\n if (printFragmentWarnings) {\n console.warn(\"Warning: fragment with name \" + fragmentName + \" already exists.\\n\"\n + \"graphql-tag enforces all fragment names across your application to be unique; read more about\\n\"\n + \"this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names\");\n }\n }\n else if (!sourceKeySet) {\n fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);\n }\n sourceKeySet.add(sourceKey);\n if (!seenKeys.has(sourceKey)) {\n seenKeys.add(sourceKey);\n definitions.push(fragmentDefinition);\n }\n }\n else {\n definitions.push(fragmentDefinition);\n }\n });\n return __assign(__assign({}, ast), { definitions: definitions });\n}\nfunction stripLoc(doc) {\n var workSet = new Set(doc.definitions);\n workSet.forEach(function (node) {\n if (node.loc)\n delete node.loc;\n Object.keys(node).forEach(function (key) {\n var value = node[key];\n if (value && typeof value === 'object') {\n workSet.add(value);\n }\n });\n });\n var loc = doc.loc;\n if (loc) {\n delete loc.startToken;\n delete loc.endToken;\n }\n return doc;\n}\nfunction parseDocument(source) {\n var cacheKey = normalize(source);\n if (!docCache.has(cacheKey)) {\n var parsed = parse(source, {\n experimentalFragmentVariables: experimentalFragmentVariables,\n allowLegacyFragmentVariables: experimentalFragmentVariables\n });\n if (!parsed || parsed.kind !== 'Document') {\n throw new Error('Not a valid GraphQL document.');\n }\n docCache.set(cacheKey, stripLoc(processFragments(parsed)));\n }\n return docCache.get(cacheKey);\n}\nexport function gql(literals) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (typeof literals === 'string') {\n literals = [literals];\n }\n var result = literals[0];\n args.forEach(function (arg, i) {\n if (arg && arg.kind === 'Document') {\n result += arg.loc.source.body;\n }\n else {\n result += arg;\n }\n result += literals[i + 1];\n });\n return parseDocument(result);\n}\nexport function resetCaches() {\n docCache.clear();\n fragmentSourceMap.clear();\n}\nexport function disableFragmentWarnings() {\n printFragmentWarnings = false;\n}\nexport function enableExperimentalFragmentVariables() {\n experimentalFragmentVariables = true;\n}\nexport function disableExperimentalFragmentVariables() {\n experimentalFragmentVariables = false;\n}\nvar extras = {\n gql: gql,\n resetCaches: resetCaches,\n disableFragmentWarnings: disableFragmentWarnings,\n enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,\n disableExperimentalFragmentVariables: disableExperimentalFragmentVariables\n};\n(function (gql_1) {\n gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;\n})(gql || (gql = {}));\ngql[\"default\"] = gql;\nexport default gql;\n//# sourceMappingURL=index.js.map","import { GraphQLClient } from \"graphql-request\";\nimport { gql } from \"graphql-tag\";\n//#region src/graphql/gen/schema.ts\nlet PropagationMode = /* @__PURE__ */ function(PropagationMode) {\n\tPropagationMode[\"Cascade\"] = \"CASCADE\";\n\tPropagationMode[\"Orphan\"] = \"ORPHAN\";\n\treturn PropagationMode;\n}({});\nconst PhDocumentFieldsFragmentDoc = gql`\n fragment PHDocumentFields on PHDocument {\n id\n slug\n name\n documentType\n state\n revisionsList {\n scope\n revision\n }\n createdAtUtcIso\n lastModifiedAtUtcIso\n }\n`;\nconst GetDocumentModelsDocument = gql`\n query GetDocumentModels($namespace: String, $paging: PagingInput) {\n documentModels(namespace: $namespace, paging: $paging) {\n items {\n id\n name\n namespace\n version\n specification\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n`;\nconst GetDocumentDocument = gql`\n query GetDocument($identifier: String!, $view: ViewFilterInput) {\n document(identifier: $identifier, view: $view) {\n document {\n ...PHDocumentFields\n }\n childIds\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst GetDocumentWithOperationsDocument = gql`\n query GetDocumentWithOperations(\n $identifier: String!\n $view: ViewFilterInput\n $operationsFilter: DocumentOperationsFilterInput\n $operationsPaging: PagingInput\n ) {\n document(identifier: $identifier, view: $view) {\n document {\n ...PHDocumentFields\n operations(filter: $operationsFilter, paging: $operationsPaging) {\n items {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n childIds\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst GetDocumentOutgoingRelationshipsDocument = gql`\n query GetDocumentOutgoingRelationships(\n $sourceIdentifier: String!\n $relationshipType: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentOutgoingRelationships(\n sourceIdentifier: $sourceIdentifier\n relationshipType: $relationshipType\n view: $view\n paging: $paging\n ) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst GetDocumentIncomingRelationshipsDocument = gql`\n query GetDocumentIncomingRelationships(\n $targetIdentifier: String!\n $relationshipType: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentIncomingRelationships(\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\n view: $view\n paging: $paging\n ) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst FindDocumentsDocument = gql`\n query FindDocuments(\n $search: SearchFilterInput\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n findDocuments(search: $search, view: $view, paging: $paging) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst GetDocumentOperationsDocument = gql`\n query GetDocumentOperations(\n $filter: OperationsFilterInput!\n $paging: PagingInput\n ) {\n documentOperations(filter: $filter, paging: $paging) {\n items {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n`;\nconst GetJobStatusDocument = gql`\n query GetJobStatus($jobId: String!) {\n jobStatus(jobId: $jobId) {\n id\n status\n result\n error\n createdAt\n completedAt\n }\n }\n`;\nconst CreateDocumentDocument = gql`\n mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {\n createDocument(document: $document, parentIdentifier: $parentIdentifier) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst CreateEmptyDocumentDocument = gql`\n mutation CreateEmptyDocument(\n $documentType: String!\n $parentIdentifier: String\n ) {\n createEmptyDocument(\n documentType: $documentType\n parentIdentifier: $parentIdentifier\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst MutateDocumentDocument = gql`\n mutation MutateDocument(\n $documentIdentifier: String!\n $actions: [JSONObject!]!\n $view: ViewFilterInput\n ) {\n mutateDocument(\n documentIdentifier: $documentIdentifier\n actions: $actions\n view: $view\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst MutateDocumentAsyncDocument = gql`\n mutation MutateDocumentAsync(\n $documentIdentifier: String!\n $actions: [JSONObject!]!\n $view: ViewFilterInput\n ) {\n mutateDocumentAsync(\n documentIdentifier: $documentIdentifier\n actions: $actions\n view: $view\n )\n }\n`;\nconst RenameDocumentDocument = gql`\n mutation RenameDocument(\n $documentIdentifier: String!\n $name: String!\n $branch: String\n ) {\n renameDocument(\n documentIdentifier: $documentIdentifier\n name: $name\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst SetPreferredEditorDocument = gql`\n mutation SetPreferredEditor(\n $documentIdentifier: String!\n $preferredEditor: String\n $branch: String\n ) {\n setPreferredEditor(\n documentIdentifier: $documentIdentifier\n preferredEditor: $preferredEditor\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst AddRelationshipDocument = gql`\n mutation AddRelationship(\n $sourceIdentifier: String!\n $targetIdentifier: String!\n $relationshipType: String!\n $branch: String\n ) {\n addRelationship(\n sourceIdentifier: $sourceIdentifier\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst RemoveRelationshipDocument = gql`\n mutation RemoveRelationship(\n $sourceIdentifier: String!\n $targetIdentifier: String!\n $relationshipType: String!\n $branch: String\n ) {\n removeRelationship(\n sourceIdentifier: $sourceIdentifier\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst MoveRelationshipDocument = gql`\n mutation MoveRelationship(\n $sourceParentIdentifier: String!\n $targetParentIdentifier: String!\n $targetIdentifier: String!\n $relationshipType: String!\n $branch: String\n ) {\n moveRelationship(\n sourceParentIdentifier: $sourceParentIdentifier\n targetParentIdentifier: $targetParentIdentifier\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\n branch: $branch\n ) {\n source {\n ...PHDocumentFields\n }\n target {\n ...PHDocumentFields\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst DeleteDocumentDocument = gql`\n mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {\n deleteDocument(identifier: $identifier, propagate: $propagate)\n }\n`;\nconst DeleteDocumentsDocument = gql`\n mutation DeleteDocuments(\n $identifiers: [String!]!\n $propagate: PropagationMode\n ) {\n deleteDocuments(identifiers: $identifiers, propagate: $propagate)\n }\n`;\nconst DocumentChangesDocument = gql`\n subscription DocumentChanges(\n $search: SearchFilterInput\n $view: ViewFilterInput\n ) {\n documentChanges(search: $search, view: $view) {\n type\n documents {\n ...PHDocumentFields\n }\n context {\n parentId\n childId\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst JobChangesDocument = gql`\n subscription JobChanges($jobId: String!) {\n jobChanges(jobId: $jobId) {\n jobId\n status\n result\n error\n }\n }\n`;\nconst PollSyncEnvelopesDocument = gql`\n query PollSyncEnvelopes(\n $channelId: String!\n $outboxAck: Int!\n $outboxLatest: Int!\n ) {\n pollSyncEnvelopes(\n channelId: $channelId\n outboxAck: $outboxAck\n outboxLatest: $outboxLatest\n ) {\n envelopes {\n type\n channelMeta {\n id\n }\n operations {\n operation {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n context {\n documentId\n documentType\n scope\n branch\n }\n }\n cursor {\n remoteName\n cursorOrdinal\n lastSyncedAtUtcMs\n }\n key\n dependsOn\n }\n ackOrdinal\n deadLetters {\n documentId\n error\n }\n hasMore\n }\n }\n`;\nconst TouchChannelDocument = gql`\n mutation TouchChannel($input: TouchChannelInput!) {\n touchChannel(input: $input) {\n success\n ackOrdinal\n }\n }\n`;\nconst PushSyncEnvelopesDocument = gql`\n mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {\n pushSyncEnvelopes(envelopes: $envelopes)\n }\n`;\nconst defaultWrapper = (action, _operationName, _operationType, _variables) => action();\nfunction getSdk(client, withWrapper = defaultWrapper) {\n\treturn {\n\t\tGetDocumentModels(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentModelsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentModels\", \"query\", variables);\n\t\t},\n\t\tGetDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocument\", \"query\", variables);\n\t\t},\n\t\tGetDocumentWithOperations(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentWithOperationsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentWithOperations\", \"query\", variables);\n\t\t},\n\t\tGetDocumentOutgoingRelationships(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentOutgoingRelationshipsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentOutgoingRelationships\", \"query\", variables);\n\t\t},\n\t\tGetDocumentIncomingRelationships(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentIncomingRelationshipsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentIncomingRelationships\", \"query\", variables);\n\t\t},\n\t\tFindDocuments(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: FindDocumentsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"FindDocuments\", \"query\", variables);\n\t\t},\n\t\tGetDocumentOperations(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentOperationsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentOperations\", \"query\", variables);\n\t\t},\n\t\tGetJobStatus(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetJobStatusDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetJobStatus\", \"query\", variables);\n\t\t},\n\t\tCreateDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: CreateDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"CreateDocument\", \"mutation\", variables);\n\t\t},\n\t\tCreateEmptyDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: CreateEmptyDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"CreateEmptyDocument\", \"mutation\", variables);\n\t\t},\n\t\tMutateDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: MutateDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"MutateDocument\", \"mutation\", variables);\n\t\t},\n\t\tMutateDocumentAsync(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: MutateDocumentAsyncDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"MutateDocumentAsync\", \"mutation\", variables);\n\t\t},\n\t\tRenameDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: RenameDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"RenameDocument\", \"mutation\", variables);\n\t\t},\n\t\tSetPreferredEditor(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: SetPreferredEditorDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"SetPreferredEditor\", \"mutation\", variables);\n\t\t},\n\t\tAddRelationship(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: AddRelationshipDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"AddRelationship\", \"mutation\", variables);\n\t\t},\n\t\tRemoveRelationship(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: RemoveRelationshipDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"RemoveRelationship\", \"mutation\", variables);\n\t\t},\n\t\tMoveRelationship(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: MoveRelationshipDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"MoveRelationship\", \"mutation\", variables);\n\t\t},\n\t\tDeleteDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: DeleteDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"DeleteDocument\", \"mutation\", variables);\n\t\t},\n\t\tDeleteDocuments(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: DeleteDocumentsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"DeleteDocuments\", \"mutation\", variables);\n\t\t},\n\t\tDocumentChanges(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: DocumentChangesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"DocumentChanges\", \"subscription\", variables);\n\t\t},\n\t\tJobChanges(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: JobChangesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"JobChanges\", \"subscription\", variables);\n\t\t},\n\t\tPollSyncEnvelopes(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: PollSyncEnvelopesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"PollSyncEnvelopes\", \"query\", variables);\n\t\t},\n\t\tTouchChannel(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: TouchChannelDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"TouchChannel\", \"mutation\", variables);\n\t\t},\n\t\tPushSyncEnvelopes(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: PushSyncEnvelopesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"PushSyncEnvelopes\", \"mutation\", variables);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/graphql/batch-queries.ts\n/** Get the source string from a GraphQL document (string or DocumentNode). */\nfunction getDocumentSource(doc) {\n\treturn typeof doc === \"string\" ? doc : doc.loc?.source.body ?? \"\";\n}\n/**\n* Extract the inner selection set of a named field from a GraphQL document source.\n* Returns the `{ ... }` block including braces.\n*/\nfunction extractSelectionSet(doc, fieldName, fallback) {\n\tconst source = getDocumentSource(doc);\n\treturn new RegExp(`${fieldName}\\\\([^)]*\\\\)\\\\s*(\\\\{[\\\\s\\\\S]*\\\\})\\\\s*\\\\}`).exec(source)?.[1] ?? fallback;\n}\n/**\n* Extract the query body and any fragment definitions from a GraphQL document.\n* Returns { body, fragments } where body is the content inside the query `{ ... }`\n* and fragments are any trailing fragment definitions.\n*/\nfunction extractQueryParts(doc, fallbackBody) {\n\tconst source = getDocumentSource(doc);\n\tconst queryMatch = /^[^{]*\\{([\\s\\S]*?)\\}\\s*(fragment[\\s\\S]*)?$/.exec(source);\n\treturn {\n\t\tbody: queryMatch?.[1]?.trim() ?? fallbackBody,\n\t\tfragments: queryMatch?.[2]?.trim() ?? \"\"\n\t};\n}\nconst operationsSelectionSet = extractSelectionSet(GetDocumentOperationsDocument, \"documentOperations\", \"{ items { index } }\");\nconst documentParts = extractQueryParts(GetDocumentDocument, \"document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }\");\n/**\n* Build a single GraphQL query that fetches documentOperations for\n* multiple filters using aliases. Each filter gets its own alias\n* (`scope_0`, `scope_1`, …) so all scopes are fetched in one HTTP request.\n*/\nfunction buildBatchOperationsQuery(filters, pagings) {\n\tconst query = `query BatchGetDocumentOperations(${filters.flatMap((_, i) => [`$filter_${i}: OperationsFilterInput!`, `$paging_${i}: PagingInput`]).join(\", \")}) {\n ${filters.map((_, i) => `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`).join(\"\\n \")}\n }`;\n\tconst variables = {};\n\tfor (let i = 0; i < filters.length; i++) {\n\t\tvariables[`filter_${i}`] = filters[i];\n\t\tvariables[`paging_${i}`] = pagings[i] ?? null;\n\t}\n\treturn {\n\t\tquery,\n\t\tvariables\n\t};\n}\n/**\n* Build a single GraphQL query that fetches a document AND\n* documentOperations for multiple filters, all in one HTTP request.\n*/\nfunction buildBatchDocumentWithOperationsQuery(identifier, view, filters, pagings) {\n\tconst docVarDefs = \"$identifier: String!, $view: ViewFilterInput\";\n\tconst opsVarDefs = filters.flatMap((_, i) => [`$filter_${i}: OperationsFilterInput!`, `$paging_${i}: PagingInput`]).join(\", \");\n\tconst opsFields = filters.map((_, i) => `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`).join(\"\\n \");\n\tconst query = `query BatchGetDocumentWithOperations(${docVarDefs}, ${opsVarDefs}) {\n ${documentParts.body}\n ${opsFields}\n }\n ${documentParts.fragments}`;\n\tconst variables = {\n\t\tidentifier,\n\t\tview: view ?? null\n\t};\n\tfor (let i = 0; i < filters.length; i++) {\n\t\tvariables[`filter_${i}`] = filters[i];\n\t\tvariables[`paging_${i}`] = pagings[i] ?? null;\n\t}\n\treturn {\n\t\tquery,\n\t\tvariables\n\t};\n}\n//#endregion\n//#region src/graphql/client.ts\n/**\n* Creates a GraphQL client for the Reactor Subgraph API.\n* @param urlOrGQLClient The URL of the GraphQL API or a GraphQL client instance.\n* @param middleware An optional middleware function to wrap the GraphQL client calls.\n* @returns A GraphQL client for the Reactor Subgraph API.\n*/\nfunction createClient(urlOrGQLClient, middleware) {\n\tconst client = typeof urlOrGQLClient === \"string\" ? new GraphQLClient(urlOrGQLClient) : urlOrGQLClient;\n\tconst runWithMiddleware = async (operationName, run) => {\n\t\tif (!middleware) return run();\n\t\treturn middleware(run, operationName, \"query\");\n\t};\n\treturn {\n\t\t...getSdk(client, middleware),\n\t\tasync BatchGetDocumentOperations(filters, pagings) {\n\t\t\tconst { query, variables } = buildBatchOperationsQuery(filters, pagings);\n\t\t\tconst data = await runWithMiddleware(\"BatchGetDocumentOperations\", (requestHeaders) => client.request(query, variables, requestHeaders));\n\t\t\treturn filters.map((_, i) => data[`scope_${i}`]);\n\t\t},\n\t\tasync BatchGetDocumentWithOperations(identifier, view, filters, pagings) {\n\t\t\tconst { query, variables } = buildBatchDocumentWithOperationsQuery(identifier, view, filters, pagings);\n\t\t\tconst data = await runWithMiddleware(\"BatchGetDocumentWithOperations\", (requestHeaders) => client.request(query, variables, requestHeaders));\n\t\t\treturn {\n\t\t\t\tdocument: data.document ?? null,\n\t\t\t\toperations: filters.map((_, i) => data[`scope_${i}`])\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\nexport { GetDocumentWithOperationsDocument as n, PropagationMode as r, createClient as t };\n\n//# sourceMappingURL=client-_Gh2Uf0E.js.map","import { t as makePHEventFunctions } from \"./make-ph-event-functions-BHoLPif5.js\";\nimport { logger } from \"document-model\";\nimport { Children, cloneElement, forwardRef, isValidElement, useCallback, useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { BrowserKeyStorage, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, DOMAIN_TYPE, ISSUER_TYPE, RenownBuilder, RenownCryptoBuilder, VERIFIABLE_CREDENTIAL_EIP712_TYPE } from \"@renown/sdk\";\nimport { Fragment, jsx, jsxs } from \"react/jsx-runtime\";\n//#region src/hooks/loading.ts\nconst { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions(\"loading\");\nconst loading = null;\n//#endregion\n//#region src/hooks/renown.ts\nconst renownEventFunctions = makePHEventFunctions(\"renown\");\n/** Adds an event handler for the renown instance */\nconst addRenownEventHandler = renownEventFunctions.addEventHandler;\n/** Returns the renown instance */\nconst useRenown = renownEventFunctions.useValue;\n/** Sets the renown instance */\nconst setRenown = renownEventFunctions.setValue;\n/** Returns the DID from the renown instance */\nfunction useDid() {\n\treturn useRenown()?.did;\n}\n/** Returns the current user from the renown instance, subscribing to user events */\nfunction useUser() {\n\tconst renown = useRenown();\n\tconst [user, setUser] = useState(renown?.user);\n\tuseEffect(() => {\n\t\tsetUser(renown?.user);\n\t\tif (!renown) return;\n\t\treturn renown.on(\"user\", setUser);\n\t}, [renown]);\n\treturn user;\n}\n/** Returns the login status, subscribing to renown status events */\nfunction useLoginStatus() {\n\tconst renown = useRenown();\n\treturn useSyncExternalStore((cb) => {\n\t\tif (!renown) return () => {};\n\t\treturn renown.on(\"status\", cb);\n\t}, () => renown === null ? \"loading\" : renown?.status, () => void 0);\n}\n//#endregion\n//#region src/renown/constants.ts\nconst RENOWN_URL = \"https://www.renown.id\";\nconst RENOWN_NETWORK_ID = \"eip155\";\nconst RENOWN_CHAIN_ID = \"1\";\n//#endregion\n//#region src/renown/utils.ts\nfunction openRenown(documentId) {\n\tconst renown = window.ph?.renown;\n\tlet renownUrl = renown?.baseUrl;\n\tif (!renownUrl) {\n\t\tlogger.warn(\"Renown instance not found, falling back to: @url\", RENOWN_URL);\n\t\trenownUrl = RENOWN_URL;\n\t}\n\tif (documentId) {\n\t\twindow.open(`${renownUrl}/profile/${documentId}`, \"_blank\")?.focus();\n\t\treturn;\n\t}\n\tconst url = new URL(renownUrl);\n\turl.searchParams.set(\"app\", renown?.did ?? \"\");\n\turl.searchParams.set(\"connect\", renown?.did ?? \"\");\n\turl.searchParams.set(\"network\", RENOWN_NETWORK_ID);\n\turl.searchParams.set(\"chain\", \"1\");\n\tconst returnUrl = new URL(window.location.pathname, window.location.origin);\n\turl.searchParams.set(\"returnUrl\", returnUrl.toJSON());\n\twindow.open(url, \"_self\")?.focus();\n}\n/**\n* Reads the `?user=` DID from the URL if present.\n* Returns the DID and cleans up the URL parameter.\n*/\nfunction consumeDidFromUrl() {\n\tif (typeof window === \"undefined\") return;\n\tconst userParam = new URLSearchParams(window.location.search).get(\"user\");\n\tif (!userParam) return;\n\tconst userDid = decodeURIComponent(userParam);\n\tconst cleanUrl = new URL(window.location.href);\n\tcleanUrl.searchParams.delete(\"user\");\n\twindow.history.replaceState({}, \"\", cleanUrl.toString());\n\treturn userDid;\n}\n/**\n* Log in the user. Resolves the user DID from (in order):\n* 1. Explicit `userDid` argument\n* 2. `?user=` URL parameter (from Renown portal redirect)\n* 3. Previously stored session in the Renown instance\n*/\nasync function login(userDid, renown) {\n\tif (!renown) return;\n\tconst did = userDid ?? consumeDidFromUrl();\n\ttry {\n\t\tconst user = renown.user;\n\t\tif (user?.did && (user.did === did || !did)) return user;\n\t\tif (!did) return;\n\t\treturn await renown.login(did);\n\t} catch (error) {\n\t\tlogger.error(error instanceof Error ? error.message : JSON.stringify(error));\n\t}\n}\nasync function logout() {\n\tawait (window.ph?.renown)?.logout();\n\tconst url = new URL(window.location.href);\n\tif (url.searchParams.has(\"user\")) {\n\t\turl.searchParams.delete(\"user\");\n\t\twindow.history.replaceState(null, \"\", url.toString());\n\t}\n}\n//#endregion\n//#region src/renown/use-renown-auth.ts\nfunction truncateAddress$1(address) {\n\tif (address.length <= 13) return address;\n\treturn `${address.slice(0, 7)}...${address.slice(-5)}`;\n}\nfunction toRenownAuthStatus(loginStatus, user) {\n\tif (loginStatus === \"authorized\") return user ? \"authorized\" : \"checking\";\n\treturn loginStatus;\n}\nfunction useRenownAuth() {\n\tconst user = useUser();\n\tconst status = toRenownAuthStatus(useLoginStatus(), user);\n\tconst address = user?.address;\n\tconst ensName = user?.ens?.name;\n\tconst avatarUrl = user?.profile?.userImage ?? user?.ens?.avatarUrl;\n\tconst profileId = user?.profile?.documentId;\n\treturn {\n\t\tstatus,\n\t\tuser,\n\t\taddress,\n\t\tensName,\n\t\tavatarUrl,\n\t\tprofileId,\n\t\tdisplayName: ensName ?? user?.profile?.username ?? void 0,\n\t\tdisplayAddress: address ? truncateAddress$1(address) : void 0,\n\t\tlogin: useCallback(() => {\n\t\t\topenRenown();\n\t\t}, []),\n\t\tlogout: useCallback(async () => {\n\t\t\tawait logout();\n\t\t}, []),\n\t\topenProfile: useCallback(() => {\n\t\t\tif (profileId) openRenown(profileId);\n\t\t}, [profileId])\n\t};\n}\n//#endregion\n//#region src/renown/components/icons.tsx\nfunction RenownLogo({ width = 71, height = 19, hovered = false, color = \"currentColor\", className }) {\n\treturn /* @__PURE__ */ jsxs(\"svg\", {\n\t\twidth,\n\t\theight,\n\t\tviewBox: \"0 0 71 19\",\n\t\tfill: color,\n\t\txmlns: \"http://www.w3.org/2000/svg\",\n\t\tclassName,\n\t\tchildren: [\n\t\t\t/* @__PURE__ */ jsx(\"path\", { d: \"M53.6211 18.4887V9.0342H56.435V10.8096H56.4923C56.7377 10.181 57.1085 9.70244 57.6047 9.37398C58.101 9.03986 58.6981 8.8728 59.3962 8.8728C60.4105 8.8728 61.2039 9.1871 61.7765 9.8157C62.3546 10.4443 62.6436 11.3164 62.6436 12.432V18.4887H59.7397V13.0776C59.7397 12.5283 59.6007 12.1007 59.3225 11.7949C59.0499 11.4835 58.6654 11.3277 58.1692 11.3277C57.6784 11.3277 57.2803 11.4976 56.9749 11.8374C56.6695 12.1772 56.5168 12.6161 56.5168 13.1541V18.4887H53.6211Z\" }),\n\t\t\t/* @__PURE__ */ jsx(\"path\", { d: \"M53.097 9.03394L50.7412 18.4884H47.6164L46.1522 12.075H46.0949L44.6389 18.4884H41.5632L39.1992 9.03394H42.1195L43.3056 15.7532H43.3628L44.7861 9.03394H47.551L48.9906 15.7532H49.0479L50.234 9.03394H53.097Z\" }),\n\t\t\t/* @__PURE__ */ jsx(\"path\", { d: \"M37.8661 17.3926C37.0427 18.2591 35.9084 18.6923 34.4632 18.6923C33.0181 18.6923 31.8838 18.2591 31.0604 17.3926C30.2369 16.5205 29.8252 15.3086 29.8252 13.7569C29.8252 12.2336 30.2424 11.033 31.0767 10.1552C31.9111 9.2718 33.0399 8.83008 34.4632 8.83008C35.892 8.83008 37.0208 9.26896 37.8497 10.1467C38.6841 11.0188 39.1013 12.2222 39.1013 13.7569C39.1013 15.3143 38.6896 16.5262 37.8661 17.3926ZM33.2117 15.7702C33.5116 16.2402 33.9288 16.4752 34.4632 16.4752C34.9977 16.4752 35.4148 16.2402 35.7148 15.7702C36.0147 15.2945 36.1647 14.6234 36.1647 13.7569C36.1647 12.9131 36.012 12.2506 35.7066 11.7692C35.4012 11.2878 34.9868 11.0472 34.4632 11.0472C33.9343 11.0472 33.5171 11.2878 33.2117 11.7692C32.9118 12.2449 32.7618 12.9075 32.7618 13.7569C32.7618 14.6234 32.9118 15.2945 33.2117 15.7702Z\" }),\n\t\t\t/* @__PURE__ */ jsx(\"path\", { d: \"M20.0088 18.4887V9.0342H22.8227V10.8096H22.88C23.1254 10.181 23.4962 9.70244 23.9924 9.37398C24.4887 9.03986 25.0858 8.8728 25.7838 8.8728C26.7982 8.8728 27.5916 9.1871 28.1642 9.8157C28.7423 10.4443 29.0313 11.3164 29.0313 12.432V18.4887H26.1274V13.0776C26.1274 12.5283 25.9883 12.1007 25.7102 11.7949C25.4376 11.4835 25.0531 11.3277 24.5569 11.3277C24.0661 11.3277 23.668 11.4976 23.3626 11.8374C23.0572 12.1772 22.9045 12.6161 22.9045 13.1541V18.4887H20.0088Z\" }),\n\t\t\t/* @__PURE__ */ jsx(\"path\", { d: \"M14.7486 10.9707C14.2851 10.9707 13.8952 11.1321 13.5789 11.4549C13.2626 11.7777 13.0854 12.1911 13.0472 12.6951H16.4337C16.4064 12.1741 16.2374 11.7579 15.9265 11.4464C15.6212 11.1293 15.2285 10.9707 14.7486 10.9707ZM16.4991 15.5153H19.1167C18.9749 16.4837 18.5141 17.2567 17.7343 17.8343C16.9599 18.4063 15.9838 18.6923 14.8059 18.6923C13.3662 18.6923 12.2374 18.2591 11.4194 17.3926C10.6014 16.5262 10.1924 15.3313 10.1924 13.8079C10.1924 12.2845 10.5987 11.0755 11.4112 10.1807C12.2237 9.28029 13.3226 8.83008 14.7077 8.83008C16.0656 8.83008 17.1481 9.26047 17.9552 10.1213C18.7677 10.9764 19.174 12.1231 19.174 13.5616V14.4195H13.0145V14.6064C13.0145 15.184 13.1835 15.6541 13.5216 16.0165C13.8597 16.3733 14.3015 16.5517 14.8468 16.5517C15.2503 16.5517 15.5993 16.461 15.8938 16.2798C16.1883 16.0929 16.3901 15.8381 16.4991 15.5153Z\" }),\n\t\t\t/* @__PURE__ */ jsx(\"path\", { d: \"M3.00205 8.58396V12.0667H4.7771C5.32789 12.0667 5.7587 11.911 6.06954 11.5995C6.38038 11.2881 6.5358 10.8662 6.5358 10.3338C6.5358 9.80718 6.37492 9.38528 6.05318 9.06815C5.73143 8.74535 5.30335 8.58396 4.76892 8.58396H3.00205ZM3.00205 14.1989V18.4886H0V6.23096H5.07158C6.53307 6.23096 7.65373 6.5849 8.43355 7.29278C9.21337 8.00066 9.60328 8.99453 9.60328 10.2744C9.60328 11.0446 9.42605 11.7439 9.07159 12.3725C8.71712 12.9955 8.2236 13.4514 7.59101 13.7402L9.94684 18.4886H6.5767L4.55624 14.1989H3.00205Z\" }),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M65.7255 0.211478C65.0841 2.46724 63.3737 4.2455 61.2041 4.90969C60.932 4.99366 60.932 5.39096 61.2041 5.47492C63.3725 6.13912 65.0841 7.91738 65.7255 10.1731C65.8056 10.4551 66.1932 10.4551 66.2745 10.1731C66.9159 7.91738 68.6263 6.13912 70.7959 5.47492C71.068 5.39096 71.068 4.99366 70.7959 4.90969C68.6276 4.2455 66.9159 2.46724 66.2745 0.211478C66.1944 -0.0704925 65.8068 -0.0704925 65.7255 0.211478Z\",\n\t\t\t\tfill: hovered ? \"#21FFB4\" : color\n\t\t\t})\n\t\t]\n\t});\n}\nfunction CopyIcon({ size = 14, color = \"var(--muted-foreground, #9EA0A1)\" }) {\n\treturn /* @__PURE__ */ jsxs(\"svg\", {\n\t\twidth: size,\n\t\theight: size,\n\t\tviewBox: \"0 0 16 16\",\n\t\tfill: \"none\",\n\t\txmlns: \"http://www.w3.org/2000/svg\",\n\t\tchildren: [/* @__PURE__ */ jsx(\"rect\", {\n\t\t\tx: \"5\",\n\t\t\ty: \"5\",\n\t\t\twidth: \"9\",\n\t\t\theight: \"9\",\n\t\t\trx: \"1\",\n\t\t\tstroke: color,\n\t\t\tstrokeWidth: \"1.5\"\n\t\t}), /* @__PURE__ */ jsx(\"path\", {\n\t\t\td: \"M11 5V3C11 2.44772 10.5523 2 10 2H3C2.44772 2 2 2.44772 2 3V10C2 10.5523 2.44772 11 3 11H5\",\n\t\t\tstroke: color,\n\t\t\tstrokeWidth: \"1.5\"\n\t\t})]\n\t});\n}\nfunction DisconnectIcon({ size = 14, color = \"var(--destructive, #EA4335)\" }) {\n\treturn /* @__PURE__ */ jsxs(\"svg\", {\n\t\twidth: size,\n\t\theight: size,\n\t\tviewBox: \"0 0 16 16\",\n\t\tfill: \"none\",\n\t\txmlns: \"http://www.w3.org/2000/svg\",\n\t\tchildren: [\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M6 14H3.33333C2.97971 14 2.64057 13.8595 2.39052 13.6095C2.14048 13.3594 2 13.0203 2 12.6667V3.33333C2 2.97971 2.14048 2.64057 2.39052 2.39052C2.64057 2.14048 2.97971 2 3.33333 2H6\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\tstrokeLinejoin: \"round\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M10.6667 11.3333L14 8L10.6667 4.66667\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\tstrokeLinejoin: \"round\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M14 8H6\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\tstrokeLinejoin: \"round\"\n\t\t\t})\n\t\t]\n\t});\n}\nfunction SpinnerIcon({ size = 14, color = \"currentColor\" }) {\n\treturn /* @__PURE__ */ jsxs(\"svg\", {\n\t\twidth: size,\n\t\theight: size,\n\t\tviewBox: \"0 0 16 16\",\n\t\tfill: \"none\",\n\t\txmlns: \"http://www.w3.org/2000/svg\",\n\t\tstyle: { animation: \"spin 1s linear infinite\" },\n\t\tchildren: [\n\t\t\t/* @__PURE__ */ jsx(\"style\", { children: `@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }` }),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M8 1V4\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M8 12V15\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\topacity: \"0.3\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M3.05 3.05L5.17 5.17\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\topacity: \"0.9\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M10.83 10.83L12.95 12.95\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\topacity: \"0.4\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M1 8H4\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\topacity: \"0.8\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M12 8H15\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\topacity: \"0.5\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M3.05 12.95L5.17 10.83\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\topacity: \"0.7\"\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"path\", {\n\t\t\t\td: \"M10.83 5.17L12.95 3.05\",\n\t\t\t\tstroke: color,\n\t\t\t\tstrokeWidth: \"1.5\",\n\t\t\t\tstrokeLinecap: \"round\",\n\t\t\t\topacity: \"0.6\"\n\t\t\t})\n\t\t]\n\t});\n}\nfunction ChevronDownIcon({ size = 14, color = \"currentColor\", style }) {\n\treturn /* @__PURE__ */ jsx(\"svg\", {\n\t\twidth: size,\n\t\theight: size,\n\t\tviewBox: \"0 0 16 16\",\n\t\tfill: \"none\",\n\t\txmlns: \"http://www.w3.org/2000/svg\",\n\t\tstyle,\n\t\tchildren: /* @__PURE__ */ jsx(\"path\", {\n\t\t\td: \"M4 6L8 10L12 6\",\n\t\t\tstroke: color,\n\t\t\tstrokeWidth: \"1.5\",\n\t\t\tstrokeLinecap: \"round\",\n\t\t\tstrokeLinejoin: \"round\"\n\t\t})\n\t});\n}\nfunction UserIcon({ size = 24, color = \"#6366f1\" }) {\n\treturn /* @__PURE__ */ jsxs(\"svg\", {\n\t\twidth: size,\n\t\theight: size,\n\t\tviewBox: \"0 0 24 24\",\n\t\tfill: \"none\",\n\t\txmlns: \"http://www.w3.org/2000/svg\",\n\t\tchildren: [/* @__PURE__ */ jsx(\"circle\", {\n\t\t\tcx: \"12\",\n\t\t\tcy: \"8\",\n\t\t\tr: \"4\",\n\t\t\tstroke: color,\n\t\t\tstrokeWidth: \"2\"\n\t\t}), /* @__PURE__ */ jsx(\"path\", {\n\t\t\td: \"M4 20C4 16.6863 7.58172 14 12 14C16.4183 14 20 16.6863 20 20\",\n\t\t\tstroke: color,\n\t\t\tstrokeWidth: \"2\",\n\t\t\tstrokeLinecap: \"round\"\n\t\t})]\n\t});\n}\n//#endregion\n//#region src/renown/components/slot.tsx\nfunction mergeProps(parentProps, childProps) {\n\tconst merged = { ...parentProps };\n\tfor (const key of Object.keys(childProps)) {\n\t\tconst parentValue = parentProps[key];\n\t\tconst childValue = childProps[key];\n\t\tif (key === \"style\") merged[key] = {\n\t\t\t...parentValue,\n\t\t\t...childValue\n\t\t};\n\t\telse if (key === \"className\") merged[key] = [parentValue, childValue].filter(Boolean).join(\" \");\n\t\telse if (typeof parentValue === \"function\" && typeof childValue === \"function\") merged[key] = (...args) => {\n\t\t\tchildValue(...args);\n\t\t\tparentValue(...args);\n\t\t};\n\t\telse if (childValue !== void 0) merged[key] = childValue;\n\t}\n\treturn merged;\n}\nconst Slot = forwardRef(({ children, ...props }, ref) => {\n\tconst child = Children.only(children);\n\tif (!isValidElement(child)) return null;\n\tconst childElement = child;\n\tconst mergedProps = mergeProps(props, childElement.props);\n\tif (ref) mergedProps.ref = ref;\n\treturn cloneElement(childElement, mergedProps);\n});\nSlot.displayName = \"Slot\";\n//#endregion\n//#region src/renown/components/RenownLoginButton.tsx\nconst colorStyles = {\n\ttrigger: {\n\t\tbackgroundColor: \"var(--card, #ffffff)\",\n\t\tborderWidth: \"1px\",\n\t\tborderStyle: \"solid\",\n\t\tborderColor: \"var(--border, #d1d5db)\",\n\t\tcolor: \"var(--card-foreground, #111827)\"\n\t},\n\ttriggerHover: {\n\t\tbackgroundColor: \"var(--accent, #ecf3f8)\",\n\t\tborderColor: \"var(--border, #d1d5db)\"\n\t}\n};\nconst styles$1 = {\n\twrapper: {\n\t\tposition: \"relative\",\n\t\tdisplay: \"inline-block\"\n\t},\n\ttrigger: {\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tjustifyContent: \"center\",\n\t\tgap: \"8px\",\n\t\tpadding: \"8px 32px\",\n\t\tborderRadius: \"8px\",\n\t\tcursor: \"pointer\",\n\t\tfontSize: \"14px\",\n\t\tfontWeight: 500,\n\t\tfontFamily: \"inherit\",\n\t\tlineHeight: \"20px\",\n\t\ttransition: \"background-color 150ms, border-color 150ms\"\n\t}\n};\nfunction RenownLoginButton({ onLogin: onLoginProp, style, className, asChild = false, children }) {\n\tconst onLogin = onLoginProp ?? (() => openRenown());\n\tconst [isLoading, setIsLoading] = useState(false);\n\tconst [isHovered, setIsHovered] = useState(false);\n\tconst handleMouseEnter = useCallback(() => setIsHovered(true), []);\n\tconst handleMouseLeave = useCallback(() => setIsHovered(false), []);\n\tconst handleClick = () => {\n\t\tif (!isLoading) {\n\t\t\tsetIsLoading(true);\n\t\t\tonLogin();\n\t\t}\n\t};\n\tconst themeStyles = colorStyles;\n\tconst triggerStyle = {\n\t\t...styles$1.trigger,\n\t\t...themeStyles.trigger,\n\t\t...isHovered && !isLoading ? themeStyles.triggerHover : {},\n\t\tcursor: isLoading ? \"wait\" : \"pointer\",\n\t\t...style\n\t};\n\tconst triggerElement = asChild ? /* @__PURE__ */ jsx(Slot, {\n\t\tonClick: handleClick,\n\t\t\"data-renown-state\": \"login\",\n\t\t...isLoading ? { \"data-loading\": \"\" } : {},\n\t\tchildren\n\t}) : /* @__PURE__ */ jsx(\"button\", {\n\t\ttype: \"button\",\n\t\tstyle: triggerStyle,\n\t\t\"aria-label\": \"Log in with Renown\",\n\t\tonClick: handleClick,\n\t\t\"data-renown-state\": \"login\",\n\t\t...isLoading ? { \"data-loading\": \"\" } : {},\n\t\tchildren: isLoading ? /* @__PURE__ */ jsx(SpinnerIcon, { size: 16 }) : /* @__PURE__ */ jsx(\"span\", { children: \"Log in\" })\n\t});\n\treturn /* @__PURE__ */ jsx(\"div\", {\n\t\tstyle: styles$1.wrapper,\n\t\tclassName,\n\t\tonMouseEnter: handleMouseEnter,\n\t\tonMouseLeave: handleMouseLeave,\n\t\tchildren: triggerElement\n\t});\n}\n//#endregion\n//#region src/renown/components/RenownUserButton.tsx\nconst POPOVER_GAP = 4;\nconst POPOVER_HEIGHT = 150;\nconst styles = {\n\twrapper: {\n\t\tposition: \"relative\",\n\t\tdisplay: \"inline-block\"\n\t},\n\ttrigger: {\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tgap: \"8px\",\n\t\tpadding: \"6px 12px\",\n\t\tborderWidth: \"1px\",\n\t\tborderStyle: \"solid\",\n\t\tborderColor: \"var(--border, #e5e7eb)\",\n\t\tbackgroundColor: \"var(--card, #ffffff)\",\n\t\tcursor: \"pointer\",\n\t\tborderRadius: \"8px\",\n\t\tfontSize: \"12px\",\n\t\tfontWeight: 500,\n\t\tfontFamily: \"inherit\",\n\t\tcolor: \"var(--card-foreground, #111827)\",\n\t\ttransition: \"background-color 150ms, border-color 150ms\"\n\t},\n\ttriggerHover: {\n\t\tbackgroundColor: \"var(--accent, #f3f4f6)\",\n\t\tborderColor: \"var(--border, #e5e7eb)\"\n\t},\n\tavatar: {\n\t\twidth: \"28px\",\n\t\theight: \"28px\",\n\t\tborderRadius: \"50%\",\n\t\tobjectFit: \"cover\",\n\t\tflexShrink: 0\n\t},\n\tavatarPlaceholder: {\n\t\twidth: \"28px\",\n\t\theight: \"28px\",\n\t\tborderRadius: \"50%\",\n\t\tbackground: \"linear-gradient(135deg, #8b5cf6, #3b82f6)\",\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tjustifyContent: \"center\",\n\t\tflexShrink: 0\n\t},\n\tavatarInitial: {\n\t\tfontSize: \"12px\",\n\t\tfontWeight: 700,\n\t\tcolor: \"#ffffff\",\n\t\tlineHeight: 1\n\t},\n\tdisplayName: {\n\t\tmaxWidth: \"120px\",\n\t\toverflow: \"hidden\",\n\t\ttextOverflow: \"ellipsis\",\n\t\twhiteSpace: \"nowrap\"\n\t},\n\tchevron: {\n\t\tflexShrink: 0,\n\t\ttransition: \"transform 150ms\",\n\t\tcolor: \"var(--muted-foreground, #6b7280)\"\n\t},\n\tchevronOpen: { transform: \"rotate(180deg)\" },\n\tpopoverBase: {\n\t\tposition: \"absolute\",\n\t\tright: 0,\n\t\tbackgroundColor: \"var(--popover, #ffffff)\",\n\t\tborderRadius: \"8px\",\n\t\tboxShadow: \"0 4px 12px rgba(0, 0, 0, 0.12), 0 1px 3px rgba(0, 0, 0, 0.08)\",\n\t\twidth: \"100%\",\n\t\tzIndex: 1e3,\n\t\tcolor: \"var(--popover-foreground, #111827)\",\n\t\tborderWidth: \"1px\",\n\t\tborderStyle: \"solid\",\n\t\tborderColor: \"var(--border, #e5e7eb)\",\n\t\toverflow: \"hidden\"\n\t},\n\theader: {\n\t\tpadding: \"12px 16px\",\n\t\tborderBottom: \"1px solid var(--border, #e5e7eb)\"\n\t},\n\theaderUsername: {\n\t\tfontSize: \"14px\",\n\t\tfontWeight: 600,\n\t\tcolor: \"var(--foreground, #111827)\",\n\t\tmargin: 0\n\t},\n\taddressRow: {\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tgap: \"4px\",\n\t\tmarginTop: \"4px\"\n\t},\n\taddressButton: {\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tgap: \"4px\",\n\t\tpadding: 0,\n\t\tborder: \"none\",\n\t\tbackgroundColor: \"transparent\",\n\t\tcursor: \"pointer\",\n\t\tfontSize: \"12px\",\n\t\tcolor: \"var(--muted-foreground, #6b7280)\",\n\t\tfontFamily: \"inherit\",\n\t\tposition: \"relative\",\n\t\twidth: \"100%\"\n\t},\n\tcopiedText: {\n\t\tfontSize: \"12px\",\n\t\tcolor: \"var(--success, #059669)\",\n\t\tposition: \"absolute\",\n\t\tleft: 0,\n\t\ttransition: \"opacity 150ms\",\n\t\tfontWeight: 500\n\t},\n\taddressText: {\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tgap: \"4px\",\n\t\ttransition: \"opacity 150ms\"\n\t},\n\tmenuSection: { padding: \"4px 0\" },\n\tmenuItem: {\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tgap: \"8px\",\n\t\twidth: \"100%\",\n\t\tpadding: \"8px 16px\",\n\t\tborder: \"none\",\n\t\tbackgroundColor: \"transparent\",\n\t\tcursor: \"pointer\",\n\t\tfontSize: \"14px\",\n\t\tcolor: \"var(--foreground, #111827)\",\n\t\ttextDecoration: \"none\",\n\t\tfontFamily: \"inherit\",\n\t\ttransition: \"background-color 150ms\"\n\t},\n\tmenuItemHover: { backgroundColor: \"var(--accent, #f3f4f6)\" },\n\tdisconnectItem: { color: \"var(--destructive, #dc2626)\" },\n\tseparator: {\n\t\theight: \"1px\",\n\t\tbackgroundColor: \"var(--border, #e5e7eb)\",\n\t\tmargin: 0,\n\t\tborder: \"none\"\n\t}\n};\nfunction truncateAddress(address) {\n\tif (address.length <= 13) return address;\n\treturn `${address.slice(0, 7)}...${address.slice(-5)}`;\n}\nfunction RenownUserButton({ address: addressProp, username: usernameProp, avatarUrl: avatarUrlProp, userId: userIdProp, onDisconnect: onDisconnectProp, style, className, asChild = false, children, menuItems }) {\n\tconst user = useUser();\n\tconst address = addressProp ?? user?.address ?? \"\";\n\tconst username = usernameProp ?? user?.profile?.username ?? user?.ens?.name;\n\tconst avatarUrl = avatarUrlProp ?? user?.profile?.userImage ?? user?.ens?.avatarUrl;\n\tconst userId = userIdProp ?? user?.profile?.documentId;\n\tconst onDisconnect = onDisconnectProp ?? (() => void logout());\n\tconst displayName = username ?? (address ? truncateAddress(address) : \"Account\");\n\tconst profileId = userId ?? address;\n\tconst [isOpen, setIsOpen] = useState(false);\n\tconst [isHovered, setIsHovered] = useState(false);\n\tconst [isCopied, setIsCopied] = useState(false);\n\tconst [showAbove, setShowAbove] = useState(true);\n\tconst [hoveredItem, setHoveredItem] = useState(null);\n\tconst wrapperRef = useRef(null);\n\tconst closeTimeoutRef = useRef(null);\n\tconst calculatePosition = useCallback(() => {\n\t\tif (!wrapperRef.current) return;\n\t\tconst spaceAbove = wrapperRef.current.getBoundingClientRect().top;\n\t\tsetShowAbove(spaceAbove >= POPOVER_HEIGHT + POPOVER_GAP);\n\t}, []);\n\tconst handleMouseEnter = useCallback(() => {\n\t\tsetIsHovered(true);\n\t\tif (closeTimeoutRef.current) {\n\t\t\tclearTimeout(closeTimeoutRef.current);\n\t\t\tcloseTimeoutRef.current = null;\n\t\t}\n\t\tcalculatePosition();\n\t\tsetIsOpen(true);\n\t}, [calculatePosition]);\n\tconst handleMouseLeave = useCallback(() => {\n\t\tcloseTimeoutRef.current = setTimeout(() => {\n\t\t\tsetIsOpen(false);\n\t\t\tsetIsHovered(false);\n\t\t\tsetHoveredItem(null);\n\t\t}, 150);\n\t}, []);\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (closeTimeoutRef.current) clearTimeout(closeTimeoutRef.current);\n\t\t};\n\t}, []);\n\tconst copyToClipboard = useCallback(async () => {\n\t\ttry {\n\t\t\tawait navigator.clipboard.writeText(address);\n\t\t\tsetIsCopied(true);\n\t\t\tsetTimeout(() => setIsCopied(false), 2e3);\n\t\t} catch (err) {\n\t\t\tconsole.error(\"Failed to copy address:\", err);\n\t\t}\n\t}, [address]);\n\tconst triggerElement = asChild ? /* @__PURE__ */ jsx(Slot, {\n\t\t\"data-renown-state\": \"authenticated\",\n\t\tchildren\n\t}) : /* @__PURE__ */ jsxs(\"button\", {\n\t\ttype: \"button\",\n\t\tstyle: {\n\t\t\t...styles.trigger,\n\t\t\t...isHovered ? styles.triggerHover : {},\n\t\t\t...style\n\t\t},\n\t\t\"aria-label\": \"Open account menu\",\n\t\t\"data-renown-state\": \"authenticated\",\n\t\tchildren: [\n\t\t\tavatarUrl ? /* @__PURE__ */ jsx(\"img\", {\n\t\t\t\tsrc: avatarUrl,\n\t\t\t\talt: \"Avatar\",\n\t\t\t\tstyle: styles.avatar\n\t\t\t}) : /* @__PURE__ */ jsx(\"div\", {\n\t\t\t\tstyle: styles.avatarPlaceholder,\n\t\t\t\tchildren: /* @__PURE__ */ jsx(\"span\", {\n\t\t\t\t\tstyle: styles.avatarInitial,\n\t\t\t\t\tchildren: (displayName || \"U\")[0].toUpperCase()\n\t\t\t\t})\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(\"span\", {\n\t\t\t\tstyle: styles.displayName,\n\t\t\t\tchildren: displayName\n\t\t\t}),\n\t\t\t/* @__PURE__ */ jsx(ChevronDownIcon, {\n\t\t\t\tsize: 14,\n\t\t\t\tstyle: {\n\t\t\t\t\t...styles.chevron,\n\t\t\t\t\t...isOpen ? styles.chevronOpen : {}\n\t\t\t\t}\n\t\t\t})\n\t\t]\n\t});\n\treturn /* @__PURE__ */ jsxs(\"div\", {\n\t\tref: wrapperRef,\n\t\tstyle: styles.wrapper,\n\t\tclassName,\n\t\tonMouseEnter: handleMouseEnter,\n\t\tonMouseLeave: handleMouseLeave,\n\t\tchildren: [triggerElement, isOpen && /* @__PURE__ */ jsxs(\"div\", {\n\t\t\tstyle: {\n\t\t\t\t...styles.popoverBase,\n\t\t\t\t...showAbove ? { bottom: `calc(100% + ${POPOVER_GAP}px)` } : { top: `calc(100% + ${POPOVER_GAP}px)` }\n\t\t\t},\n\t\t\tchildren: [\n\t\t\t\t/* @__PURE__ */ jsxs(\"div\", {\n\t\t\t\t\tstyle: styles.header,\n\t\t\t\t\tchildren: [username && /* @__PURE__ */ jsx(\"div\", {\n\t\t\t\t\t\tstyle: styles.headerUsername,\n\t\t\t\t\t\tchildren: username\n\t\t\t\t\t}), address && /* @__PURE__ */ jsx(\"div\", {\n\t\t\t\t\t\tstyle: styles.addressRow,\n\t\t\t\t\t\tchildren: /* @__PURE__ */ jsx(\"button\", {\n\t\t\t\t\t\t\ttype: \"button\",\n\t\t\t\t\t\t\tonClick: () => void copyToClipboard(),\n\t\t\t\t\t\t\tstyle: styles.addressButton,\n\t\t\t\t\t\t\tchildren: /* @__PURE__ */ jsxs(\"div\", {\n\t\t\t\t\t\t\t\tstyle: {\n\t\t\t\t\t\t\t\t\tposition: \"relative\",\n\t\t\t\t\t\t\t\t\tdisplay: \"flex\",\n\t\t\t\t\t\t\t\t\talignItems: \"center\",\n\t\t\t\t\t\t\t\t\tgap: \"4px\",\n\t\t\t\t\t\t\t\t\twidth: \"100%\"\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tchildren: [/* @__PURE__ */ jsxs(\"div\", {\n\t\t\t\t\t\t\t\t\tstyle: {\n\t\t\t\t\t\t\t\t\t\t...styles.addressText,\n\t\t\t\t\t\t\t\t\t\topacity: isCopied ? 0 : 1\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tchildren: [/* @__PURE__ */ jsx(\"span\", { children: truncateAddress(address) }), /* @__PURE__ */ jsx(CopyIcon, {\n\t\t\t\t\t\t\t\t\t\tsize: 12,\n\t\t\t\t\t\t\t\t\t\tcolor: \"var(--muted-foreground, #9ca3af)\"\n\t\t\t\t\t\t\t\t\t})]\n\t\t\t\t\t\t\t\t}), /* @__PURE__ */ jsx(\"div\", {\n\t\t\t\t\t\t\t\t\tstyle: {\n\t\t\t\t\t\t\t\t\t\t...styles.copiedText,\n\t\t\t\t\t\t\t\t\t\topacity: isCopied ? 1 : 0\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tchildren: \"Copied!\"\n\t\t\t\t\t\t\t\t})]\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\t})]\n\t\t\t\t}),\n\t\t\t\t/* @__PURE__ */ jsxs(\"div\", {\n\t\t\t\t\tstyle: styles.menuSection,\n\t\t\t\t\tchildren: [profileId && /* @__PURE__ */ jsxs(\"button\", {\n\t\t\t\t\t\ttype: \"button\",\n\t\t\t\t\t\tonClick: () => openRenown(profileId),\n\t\t\t\t\t\tonMouseEnter: () => setHoveredItem(\"profile\"),\n\t\t\t\t\t\tonMouseLeave: () => setHoveredItem(null),\n\t\t\t\t\t\tstyle: {\n\t\t\t\t\t\t\t...styles.menuItem,\n\t\t\t\t\t\t\t...hoveredItem === \"profile\" ? styles.menuItemHover : {}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tchildren: [/* @__PURE__ */ jsx(UserIcon, {\n\t\t\t\t\t\t\tsize: 14,\n\t\t\t\t\t\t\tcolor: \"var(--muted-foreground, #6b7280)\"\n\t\t\t\t\t\t}), \"View Profile\"]\n\t\t\t\t\t}), menuItems?.map((item) => /* @__PURE__ */ jsxs(\"button\", {\n\t\t\t\t\t\ttype: \"button\",\n\t\t\t\t\t\tonClick: item.onClick,\n\t\t\t\t\t\tonMouseEnter: () => setHoveredItem(item.label),\n\t\t\t\t\t\tonMouseLeave: () => setHoveredItem(null),\n\t\t\t\t\t\tstyle: {\n\t\t\t\t\t\t\t...styles.menuItem,\n\t\t\t\t\t\t\t...hoveredItem === item.label ? styles.menuItemHover : {},\n\t\t\t\t\t\t\t...item.style\n\t\t\t\t\t\t},\n\t\t\t\t\t\tchildren: [item.icon, item.label]\n\t\t\t\t\t}, item.label))]\n\t\t\t\t}),\n\t\t\t\t/* @__PURE__ */ jsx(\"hr\", { style: styles.separator }),\n\t\t\t\t/* @__PURE__ */ jsx(\"div\", {\n\t\t\t\t\tstyle: styles.menuSection,\n\t\t\t\t\tchildren: /* @__PURE__ */ jsxs(\"button\", {\n\t\t\t\t\t\ttype: \"button\",\n\t\t\t\t\t\tonClick: onDisconnect,\n\t\t\t\t\t\tonMouseEnter: () => setHoveredItem(\"disconnect\"),\n\t\t\t\t\t\tonMouseLeave: () => setHoveredItem(null),\n\t\t\t\t\t\tstyle: {\n\t\t\t\t\t\t\t...styles.menuItem,\n\t\t\t\t\t\t\t...styles.disconnectItem,\n\t\t\t\t\t\t\t...hoveredItem === \"disconnect\" ? styles.menuItemHover : {}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tchildren: [/* @__PURE__ */ jsx(DisconnectIcon, {\n\t\t\t\t\t\t\tsize: 14,\n\t\t\t\t\t\t\tcolor: \"var(--destructive, #dc2626)\"\n\t\t\t\t\t\t}), \"Log out\"]\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t]\n\t\t})]\n\t});\n}\n//#endregion\n//#region src/renown/components/RenownAuthButton.tsx\nfunction RenownAuthButton({ className = \"\", darkMode, loginContent, userContent, loadingContent, children }) {\n\tconst auth = useRenownAuth();\n\tif (children) return /* @__PURE__ */ jsx(Fragment, { children: children(auth) });\n\tif (auth.status === \"loading\" || auth.status === \"checking\") {\n\t\tif (loadingContent) return /* @__PURE__ */ jsx(\"div\", {\n\t\t\tclassName,\n\t\t\tchildren: loadingContent\n\t\t});\n\t\treturn /* @__PURE__ */ jsxs(\"div\", {\n\t\t\tclassName,\n\t\t\tchildren: [/* @__PURE__ */ jsxs(\"div\", {\n\t\t\t\tstyle: {\n\t\t\t\t\tdisplay: \"flex\",\n\t\t\t\t\talignItems: \"center\",\n\t\t\t\t\tgap: \"8px\",\n\t\t\t\t\tpadding: \"6px 12px\",\n\t\t\t\t\tborderRadius: \"8px\",\n\t\t\t\t\tborder: \"1px solid var(--border, #f0f0f0)\",\n\t\t\t\t\tanimation: \"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite\"\n\t\t\t\t},\n\t\t\t\tchildren: [/* @__PURE__ */ jsx(\"div\", { style: {\n\t\t\t\t\twidth: \"28px\",\n\t\t\t\t\theight: \"28px\",\n\t\t\t\t\tborderRadius: \"50%\",\n\t\t\t\t\tbackgroundColor: \"var(--secondary, #f0f0f0)\"\n\t\t\t\t} }), /* @__PURE__ */ jsx(\"div\", { style: {\n\t\t\t\t\twidth: \"80px\",\n\t\t\t\t\theight: \"14px\",\n\t\t\t\t\tborderRadius: \"4px\",\n\t\t\t\t\tbackgroundColor: \"var(--secondary, #f0f0f0)\"\n\t\t\t\t} })]\n\t\t\t}), /* @__PURE__ */ jsx(\"style\", { children: `@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }` })]\n\t\t});\n\t}\n\tif (auth.status === \"authorized\") {\n\t\tif (userContent) return /* @__PURE__ */ jsx(\"div\", {\n\t\t\tclassName,\n\t\t\tchildren: userContent\n\t\t});\n\t\treturn /* @__PURE__ */ jsx(\"div\", {\n\t\t\tclassName,\n\t\t\tchildren: /* @__PURE__ */ jsx(RenownUserButton, {})\n\t\t});\n\t}\n\tif (loginContent) return /* @__PURE__ */ jsx(\"div\", {\n\t\tclassName,\n\t\tchildren: loginContent\n\t});\n\treturn /* @__PURE__ */ jsx(\"div\", {\n\t\tclassName,\n\t\tchildren: /* @__PURE__ */ jsx(RenownLoginButton, { darkMode })\n\t});\n}\n//#endregion\n//#region src/renown/crypto.ts\n/**\n* @deprecated Use {@link initRenownCrypto} instead\n*\n* Initialize ConnectCrypto\n* @returns ConnectCrypto instance\n*/\nasync function initConnectCrypto() {\n\treturn initRenownCrypto();\n}\n/**\n* Initialize RenownCrypto\n* @returns RenownCrypto instance\n*/\nasync function initRenownCrypto() {\n\tconst keyStorage = await BrowserKeyStorage.create();\n\treturn await new RenownCryptoBuilder().withKeyPairStorage(keyStorage).build();\n}\n//#endregion\n//#region src/renown/use-renown-init.ts\nasync function initRenown(appName, namespace, url) {\n\taddRenownEventHandler();\n\tsetRenown(null);\n\tconst renown = await new RenownBuilder(appName, {\n\t\tbasename: namespace,\n\t\tbaseUrl: url\n\t}).build();\n\tsetRenown(renown);\n\tawait login(void 0, renown);\n\treturn renown;\n}\n/**\n* Hook that initializes the Renown SDK.\n* Call once at the top of your app. Options are read only on first mount.\n* Returns a promise that resolves with the Renown instance.\n*\n* @example\n* ```tsx\n* function App() {\n* const renownPromise = useRenownInit({ appName: \"my-app\" });\n* return <MyApp />;\n* }\n* ```\n*/\nfunction useRenownInit({ appName, namespace, url }) {\n\tconst promiseRef = useRef(null);\n\tpromiseRef.current ??= Promise.withResolvers();\n\tconst initRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (initRef.current) return;\n\t\tinitRef.current = true;\n\t\tinitRenown(appName, namespace, url).then(promiseRef.current.resolve).catch(promiseRef.current.reject);\n\t}, []);\n\treturn promiseRef.current.promise;\n}\n//#endregion\n//#region src/renown/renown-init.tsx\n/**\n* Side-effect component that initializes the Renown SDK.\n* Renders nothing — place it alongside your app tree.\n*\n* @example\n* ```tsx\n* function App() {\n* return (\n* <>\n* <Renown appName=\"my-app\" onError={console.error} />\n* <MyApp />\n* </>\n* );\n* }\n* ```\n*/\nfunction Renown({ onError, ...initOptions }) {\n\tuseRenownInit(initOptions).catch(onError ?? console.error);\n\treturn null;\n}\n//#endregion\nexport { useLoginStatus as A, RENOWN_CHAIN_ID as C, addRenownEventHandler as D, VERIFIABLE_CREDENTIAL_EIP712_TYPE as E, setLoading as F, useLoading as I, useUser as M, addLoadingEventHandler as N, setRenown as O, loading as P, ISSUER_TYPE as S, RENOWN_URL as T, openRenown as _, RenownAuthButton as a, CREDENTIAL_TYPES as b, ChevronDownIcon as c, RenownLogo as d, SpinnerIcon as f, logout as g, login as h, initRenownCrypto as i, useRenown as j, useDid as k, CopyIcon as l, useRenownAuth as m, useRenownInit as n, RenownUserButton as o, UserIcon as p, initConnectCrypto as r, RenownLoginButton as s, Renown as t, DisconnectIcon as u, CREDENTIAL_SCHEMA_EIP712_TYPE as v, RENOWN_NETWORK_ID as w, DOMAIN_TYPE as x, CREDENTIAL_SUBJECT_TYPE as y };\n\n//# sourceMappingURL=renown-D-1c_Bvx.js.map","function e(e,t,n){let r=n=>e(n,...t);return n===void 0?r:Object.assign(r,{lazy:n,lazyArgs:t})}export{e as t};\n//# sourceMappingURL=lazyDataLastImpl-DtF3cihj.js.map","import{t as e}from\"./lazyDataLastImpl-DtF3cihj.js\";function t(t,n,r){let i=t.length-n.length;if(i===0)return t(...n);if(i===1)return e(t,n,r);throw Error(`Wrong number of arguments`)}export{t as purry};\n//# sourceMappingURL=purry.js.map","import{purry as e}from\"./purry.js\";function t(...t){return e(n,t)}const n=(e,t)=>e.length>=t;export{t as hasAtLeast};\n//# sourceMappingURL=hasAtLeast.js.map","const e=Symbol(`funnel/voidReducer`),t=()=>e;function n(n,{triggerAt:r=`end`,minQuietPeriodMs:i,maxBurstDurationMs:a,minGapMs:o,reducer:s=t}){let c,l,u,d,f=()=>{let t=u;t!==void 0&&(u=void 0,t===e?n():n(t),o!==void 0&&(l=setTimeout(p,o)))},p=()=>{clearTimeout(l),l=void 0,c===void 0&&f()},m=()=>{clearTimeout(c),c=void 0,d=void 0,l===void 0&&f()};return{call:(...e)=>{let t=c===void 0&&l===void 0;if((r!==`start`||t)&&(u=s(u,...e)),!(c===void 0&&!t)){if(i!==void 0||a!==void 0||o===void 0){clearTimeout(c);let e=Date.now();d??=e;let t=a===void 0?i??0:Math.min(i??a,Math.max(0,a-(e-d)));c=setTimeout(m,t)}r!==`end`&&t&&f()}},cancel:()=>{clearTimeout(c),c=void 0,d=void 0,clearTimeout(l),l=void 0,u=void 0},flush:()=>{m(),p()},get isIdle(){return c===void 0&&l===void 0}}}export{n as funnel};\n//# sourceMappingURL=funnel.js.map","function e(e){return e!==void 0}export{e as isDefined};\n//# sourceMappingURL=isDefined.js.map","import { baseCreateDocument, baseLoadFromInput, baseSaveToFileHandle, createPresignedHeader, createReducer, createState, defaultBaseState, generateId, isDocumentAction, replayDocumentVersioned } from \"@powerhousedao/shared/document-model\";\nimport { Migrator, sql } from \"kysely\";\nimport { BaseReadModel, addRelationshipAction, createDocumentAction, removeRelationshipAction, upgradeDocumentAction } from \"@powerhousedao/reactor\";\nimport { gql } from \"graphql-tag\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/constants.ts\nconst REACTOR_DRIVE_DOCUMENT_TYPE = \"powerhouse/reactor-drive\";\nconst DRIVE_CHILD_RELATIONSHIP_TYPE = \"drive/child\";\nconst REACTOR_DRIVE_FILE_EXTENSION = \"phrd\";\n//#endregion\n//#region src/actions.ts\nfunction setDriveNameAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"SET_DRIVE_NAME\",\n\t\tscope: \"global\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\nfunction setDriveIconAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"SET_DRIVE_ICON\",\n\t\tscope: \"global\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\nfunction setSharingTypeAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"SET_SHARING_TYPE\",\n\t\tscope: \"local\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\nfunction setAvailableOfflineAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"SET_AVAILABLE_OFFLINE\",\n\t\tscope: \"local\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\nfunction addFolderAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"ADD_FOLDER\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\nfunction updateFolderAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"UPDATE_FOLDER\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\nfunction removeFolderAction(input) {\n\treturn {\n\t\tid: generateId(),\n\t\ttype: \"REMOVE_FOLDER\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tinput\n\t};\n}\nconst reactorDriveActions = {\n\tsetDriveName: setDriveNameAction,\n\tsetDriveIcon: setDriveIconAction,\n\tsetSharingType: setSharingTypeAction,\n\tsetAvailableOffline: setAvailableOfflineAction,\n\taddFolder: addFolderAction,\n\tupdateFolder: updateFolderAction,\n\tremoveFolder: removeFolderAction\n};\n//#endregion\n//#region src/reducer/drive.ts\nconst reactorDriveStateReducer = (state, action) => {\n\tif (isDocumentAction(action)) return state;\n\tconst typedAction = action;\n\tswitch (typedAction.type) {\n\t\tcase \"SET_DRIVE_NAME\": {\n\t\t\tconst input = typedAction.input;\n\t\t\tstate.global.name = input.name;\n\t\t\treturn state;\n\t\t}\n\t\tcase \"SET_DRIVE_ICON\": {\n\t\t\tconst input = typedAction.input;\n\t\t\tstate.global.icon = input.icon;\n\t\t\treturn state;\n\t\t}\n\t\tcase \"SET_SHARING_TYPE\": {\n\t\t\tconst input = typedAction.input;\n\t\t\tstate.local.sharingType = input.sharingType;\n\t\t\treturn state;\n\t\t}\n\t\tcase \"SET_AVAILABLE_OFFLINE\": {\n\t\t\tconst input = typedAction.input;\n\t\t\tstate.local.availableOffline = input.availableOffline;\n\t\t\treturn state;\n\t\t}\n\t\tcase \"ADD_FOLDER\":\n\t\tcase \"UPDATE_FOLDER\":\n\t\tcase \"REMOVE_FOLDER\": return state;\n\t\tdefault: return state;\n\t}\n};\n//#endregion\n//#region src/module.ts\nconst initialGlobalState = {\n\tname: \"\",\n\ticon: null\n};\nconst initialLocalState = {\n\tsharingType: \"private\",\n\tavailableOffline: false\n};\nconst reactorDriveCreateState = (state) => {\n\treturn {\n\t\t...defaultBaseState(),\n\t\tglobal: {\n\t\t\t...initialGlobalState,\n\t\t\t...state?.global\n\t\t},\n\t\tlocal: {\n\t\t\t...initialLocalState,\n\t\t\t...state?.local\n\t\t}\n\t};\n};\nconst reactorDriveCreateDocument = (state) => {\n\treturn baseCreateDocument(reactorDriveCreateState, state, REACTOR_DRIVE_DOCUMENT_TYPE);\n};\nconst reactorDriveSaveToFileHandle = (document, input) => {\n\treturn baseSaveToFileHandle(document, input);\n};\nconst reactorDriveLoadFromInput = (input) => {\n\treturn baseLoadFromInput(input, reactorDriveDocumentReducer);\n};\nconst isReactorDriveState = (state) => {\n\treturn typeof state === \"object\" && state !== null && \"global\" in state && \"local\" in state;\n};\nconst assertIsReactorDriveState = (state) => {\n\tif (!isReactorDriveState(state)) throw new Error(\"Not a reactor-drive state\");\n};\nconst isReactorDriveDocument = (document) => {\n\treturn typeof document === \"object\" && document !== null && \"header\" in document && document.header.documentType === \"powerhouse/reactor-drive\";\n};\nconst assertIsReactorDriveDocument = (document) => {\n\tif (!isReactorDriveDocument(document)) throw new Error(\"Not a reactor-drive document\");\n};\nconst reactorDriveDocumentReducer = createReducer(reactorDriveStateReducer);\nconst reactorDriveDocumentGlobalState = {\n\tid: REACTOR_DRIVE_DOCUMENT_TYPE,\n\tname: \"ReactorDrive\",\n\textension: REACTOR_DRIVE_FILE_EXTENSION,\n\tdescription: \"\",\n\tauthor: {\n\t\tname: \"Powerhouse Inc\",\n\t\twebsite: \"https://www.powerhouse.inc/\"\n\t},\n\tspecifications: [{\n\t\tversion: 1,\n\t\tchangeLog: [],\n\t\tstate: {\n\t\t\tglobal: {\n\t\t\t\tschema: \"type ReactorDriveState {\\n name: String!\\n icon: String\\n}\",\n\t\t\t\tinitialValue: JSON.stringify(JSON.stringify(initialGlobalState)),\n\t\t\t\texamples: []\n\t\t\t},\n\t\t\tlocal: {\n\t\t\t\tschema: \"type ReactorDriveLocalState {\\n sharingType: String!\\n availableOffline: Boolean!\\n}\",\n\t\t\t\tinitialValue: JSON.stringify(JSON.stringify(initialLocalState)),\n\t\t\t\texamples: []\n\t\t\t}\n\t\t},\n\t\tmodules: [{\n\t\t\tid: \"reactor-drive/base-operations\",\n\t\t\tname: \"base_operations\",\n\t\t\tdescription: \"\",\n\t\t\toperations: [\n\t\t\t\t{\n\t\t\t\t\tid: \"SET_DRIVE_NAME\",\n\t\t\t\t\tname: \"SET_DRIVE_NAME\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetDriveNameInput { name: String! }\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"SET_DRIVE_ICON\",\n\t\t\t\t\tname: \"SET_DRIVE_ICON\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetDriveIconInput { icon: String }\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"global\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"SET_SHARING_TYPE\",\n\t\t\t\t\tname: \"SET_SHARING_TYPE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetSharingTypeInput { sharingType: String! }\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"SET_AVAILABLE_OFFLINE\",\n\t\t\t\t\tname: \"SET_AVAILABLE_OFFLINE\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input SetAvailableOfflineInput { availableOffline: Boolean! }\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"local\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"ADD_FOLDER\",\n\t\t\t\t\tname: \"ADD_FOLDER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input AddFolderInput { folderId: String! parentFolderId: String name: String! }\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"document\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"UPDATE_FOLDER\",\n\t\t\t\t\tname: \"UPDATE_FOLDER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input UpdateFolderInput { folderId: String! name: String parentFolderId: String }\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"document\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"REMOVE_FOLDER\",\n\t\t\t\t\tname: \"REMOVE_FOLDER\",\n\t\t\t\t\tdescription: \"\",\n\t\t\t\t\tschema: \"input RemoveFolderInput { folderId: String! }\",\n\t\t\t\t\ttemplate: \"\",\n\t\t\t\t\treducer: \"\",\n\t\t\t\t\terrors: [],\n\t\t\t\t\texamples: [],\n\t\t\t\t\tscope: \"document\"\n\t\t\t\t}\n\t\t\t]\n\t\t}]\n\t}]\n};\nconst reactorDriveDocumentModelModule = {\n\tactions: reactorDriveActions,\n\treducer: reactorDriveDocumentReducer,\n\tdocumentModel: createState(defaultBaseState(), reactorDriveDocumentGlobalState),\n\tutils: {\n\t\tfileExtension: REACTOR_DRIVE_FILE_EXTENSION,\n\t\tcreateState: reactorDriveCreateState,\n\t\tcreateDocument: reactorDriveCreateDocument,\n\t\tloadFromInput: reactorDriveLoadFromInput,\n\t\tsaveToFileHandle: reactorDriveSaveToFileHandle,\n\t\tisStateOfType: isReactorDriveState,\n\t\tassertIsStateOfType: assertIsReactorDriveState,\n\t\tisDocumentOfType: isReactorDriveDocument,\n\t\tassertIsDocumentOfType: assertIsReactorDriveDocument\n\t}\n};\n//#endregion\n//#region src/schema/migrations/0001_drive_node.ts\nvar _0001_drive_node_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$1,\n\tup: () => up$1\n});\nasync function up$1(db) {\n\tawait db.schema.createTable(\"DriveNode\").ifNotExists().addColumn(\"driveId\", \"text\", (col) => col.notNull()).addColumn(\"id\", \"text\", (col) => col.notNull()).addColumn(\"kind\", \"text\", (col) => col.notNull()).addColumn(\"name\", \"text\", (col) => col.notNull()).addColumn(\"requestedName\", \"text\", (col) => col.notNull()).addColumn(\"parentFolder\", \"text\").addColumn(\"documentType\", \"text\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addPrimaryKeyConstraint(\"pk_drive_node\", [\"driveId\", \"id\"]).addCheckConstraint(\"chk_drive_node_document_type\", sql`(kind = 'file' AND \"documentType\" IS NOT NULL) OR (kind = 'folder' AND \"documentType\" IS NULL)`).execute();\n\tawait db.schema.createIndex(\"idx_drive_node_parent_name\").ifNotExists().on(\"DriveNode\").columns([\n\t\t\"driveId\",\n\t\t\"parentFolder\",\n\t\t\"name\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_drive_node_parent_kind_id\").ifNotExists().on(\"DriveNode\").columns([\n\t\t\"driveId\",\n\t\t\"parentFolder\",\n\t\t\"kind\",\n\t\t\"id\"\n\t]).execute();\n}\nasync function down$1(db) {\n\tawait db.schema.dropTable(\"DriveNode\").execute();\n}\n//#endregion\n//#region src/schema/migrations/0002_document_name.ts\nvar _0002_document_name_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down,\n\tup: () => up\n});\nasync function up(db) {\n\tawait db.schema.createTable(\"DocumentName\").ifNotExists().addColumn(\"docId\", \"text\", (col) => col.primaryKey()).addColumn(\"name\", \"text\", (col) => col.notNull()).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\nasync function down(db) {\n\tawait db.schema.dropTable(\"DocumentName\").execute();\n}\n//#endregion\n//#region src/schema/migrations/migrator.ts\nconst migrations = {\n\t\"0001_drive_node\": _0001_drive_node_exports,\n\t\"0002_document_name\": _0002_document_name_exports\n};\nconst REACTOR_DRIVE_MIGRATION_TABLE = \"kysely_migration_reactor_drive\";\nconst REACTOR_DRIVE_MIGRATION_LOCK_TABLE = \"kysely_migration_reactor_drive_lock\";\nvar ProgrammaticMigrationProvider = class {\n\tgetMigrations() {\n\t\treturn Promise.resolve(migrations);\n\t}\n};\nasync function runReactorDriveMigrations(db, schema) {\n\ttry {\n\t\tawait sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tmigrationsExecuted: [],\n\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Failed to create schema\")\n\t\t};\n\t}\n\tconst migrator = new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema,\n\t\tmigrationTableName: REACTOR_DRIVE_MIGRATION_TABLE,\n\t\tmigrationLockTableName: REACTOR_DRIVE_MIGRATION_LOCK_TABLE\n\t});\n\tlet error;\n\tlet results;\n\ttry {\n\t\tconst result = await migrator.migrateToLatest();\n\t\terror = result.error;\n\t\tresults = result.results;\n\t} catch (e) {\n\t\terror = e;\n\t\tresults = [];\n\t}\n\tconst migrationsExecuted = results?.map((result) => result.migrationName) ?? [];\n\tif (error) return {\n\t\tsuccess: false,\n\t\tmigrationsExecuted,\n\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Unknown migration error\")\n\t};\n\treturn {\n\t\tsuccess: true,\n\t\tmigrationsExecuted\n\t};\n}\nasync function getReactorDriveMigrationStatus(db, schema) {\n\treturn await new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema,\n\t\tmigrationTableName: REACTOR_DRIVE_MIGRATION_TABLE,\n\t\tmigrationLockTableName: REACTOR_DRIVE_MIGRATION_LOCK_TABLE\n\t}).getMigrations();\n}\n//#endregion\n//#region src/processors/utils/collisions.ts\n/**\n* Deterministic per-folder name collision rule. Given a desired name and the\n* set of names already taken by siblings, returns the next available name as\n* `requested`, `requested (2)`, `requested (3)`, etc.\n*\n* The rule matches the legacy document-drive module so that migration from\n* the legacy state produces stable suffixes.\n*/\nfunction resolveCollision(requested, takenNames) {\n\tconst taken = /* @__PURE__ */ new Set();\n\tfor (const name of takenNames) taken.add(name);\n\tif (!taken.has(requested)) return requested;\n\tlet suffix = 2;\n\twhile (taken.has(`${requested} (${suffix})`)) suffix += 1;\n\treturn `${requested} (${suffix})`;\n}\n//#endregion\n//#region src/processors/node-processor.ts\nconst NAME_ACTION_TYPES = new Set([\n\t\"CREATE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"SET_NAME\"\n]);\nconst STRUCTURE_ACTION_TYPES = new Set([\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"ADD_FOLDER\",\n\t\"UPDATE_FOLDER\",\n\t\"REMOVE_FOLDER\"\n]);\nvar NodeProcessor = class extends BaseReadModel {\n\tdriveDb;\n\tbaseDb;\n\tschema;\n\tconstructor(baseDb, schema, operationIndex, writeCache, consistencyTracker) {\n\t\tconst scopedDb = baseDb.withSchema(schema);\n\t\tsuper(scopedDb, operationIndex, writeCache, consistencyTracker, {\n\t\t\treadModelId: \"reactor-drive-node-processor\",\n\t\t\trebuildStateOnInit: false\n\t\t});\n\t\tthis.driveDb = scopedDb;\n\t\tthis.baseDb = baseDb;\n\t\tthis.schema = schema;\n\t}\n\tasync init() {\n\t\tconst result = await runReactorDriveMigrations(this.baseDb, this.schema);\n\t\tif (!result.success && result.error) throw new Error(`Reactor drive migrations failed: ${result.error.message}`);\n\t\tawait super.init();\n\t}\n\tasync commitOperations(items) {\n\t\tawait this.driveDb.transaction().execute(async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tconst actionType = item.operation.action.type;\n\t\t\t\tif (NAME_ACTION_TYPES.has(actionType)) {\n\t\t\t\t\tawait this.applyNameOperation(trx, item);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (STRUCTURE_ACTION_TYPES.has(actionType)) {\n\t\t\t\t\tawait this.applyStructureOperation(trx, item);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (actionType === \"DELETE_DOCUMENT\") await this.applyDeleteDocument(trx, item);\n\t\t\t}\n\t\t});\n\t}\n\tasync applyNameOperation(trx, item) {\n\t\tconst action = item.operation.action;\n\t\tconst docId = item.context.documentId;\n\t\tlet name;\n\t\tif (action.type === \"CREATE_DOCUMENT\") name = action.input.name;\n\t\telse if (action.type === \"UPGRADE_DOCUMENT\") name = (action.input.initialState ?? {}).header?.name;\n\t\telse if (action.type === \"SET_NAME\") name = action.input.name;\n\t\tif (name === void 0) return;\n\t\tawait this.upsertDocumentName(trx, docId, name);\n\t\tconst linkedRows = await trx.selectFrom(\"DriveNode\").selectAll().where(\"id\", \"=\", docId).where(\"kind\", \"=\", \"file\").execute();\n\t\tfor (const row of linkedRows) {\n\t\t\tconst resolved = await this.resolveSiblingName(trx, row.driveId, row.parentFolder, name, docId);\n\t\t\tawait trx.updateTable(\"DriveNode\").set({\n\t\t\t\tname: resolved,\n\t\t\t\trequestedName: name,\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t\t}).where(\"driveId\", \"=\", row.driveId).where(\"id\", \"=\", docId).execute();\n\t\t}\n\t}\n\tasync applyStructureOperation(trx, item) {\n\t\tif (item.context.documentType !== \"powerhouse/reactor-drive\") return;\n\t\tconst action = item.operation.action;\n\t\tconst driveId = item.context.documentId;\n\t\tif (action.type === \"ADD_RELATIONSHIP\") {\n\t\t\tconst input = action.input;\n\t\t\tif (input.relationshipType !== \"drive/child\") return;\n\t\t\tawait this.handleAddFileRelationship(trx, driveId, input);\n\t\t\treturn;\n\t\t}\n\t\tif (action.type === \"REMOVE_RELATIONSHIP\") {\n\t\t\tconst input = action.input;\n\t\t\tif (input.relationshipType !== \"drive/child\") return;\n\t\t\tawait trx.deleteFrom(\"DriveNode\").where(\"driveId\", \"=\", driveId).where(\"id\", \"=\", input.targetId).execute();\n\t\t\treturn;\n\t\t}\n\t\tif (action.type === \"ADD_FOLDER\") {\n\t\t\tawait this.handleAddFolder(trx, driveId, action.input);\n\t\t\treturn;\n\t\t}\n\t\tif (action.type === \"UPDATE_FOLDER\") {\n\t\t\tawait this.handleUpdateFolder(trx, driveId, action.input);\n\t\t\treturn;\n\t\t}\n\t\tif (action.type === \"REMOVE_FOLDER\") {\n\t\t\tconst input = action.input;\n\t\t\tawait trx.deleteFrom(\"DriveNode\").where(\"driveId\", \"=\", driveId).where(\"id\", \"=\", input.folderId).execute();\n\t\t}\n\t}\n\tasync applyDeleteDocument(trx, item) {\n\t\tconst docId = item.operation.action.input.documentId || item.context.documentId;\n\t\tawait trx.deleteFrom(\"DriveNode\").where(\"id\", \"=\", docId).execute();\n\t\tawait trx.deleteFrom(\"DocumentName\").where(\"docId\", \"=\", docId).execute();\n\t}\n\tasync handleAddFileRelationship(trx, driveId, input) {\n\t\tconst metadata = this.parseFileMetadata(input);\n\t\tconst parentFolder = metadata.parentFolderId ?? null;\n\t\tconst documentType = metadata.documentType;\n\t\tconst requestedName = await this.lookupDocumentName(trx, input.targetId) ?? \"\";\n\t\tconst resolved = await this.resolveSiblingName(trx, driveId, parentFolder, requestedName, input.targetId);\n\t\tawait trx.insertInto(\"DriveNode\").values({\n\t\t\tdriveId,\n\t\t\tid: input.targetId,\n\t\t\tkind: \"file\",\n\t\t\tname: resolved,\n\t\t\trequestedName,\n\t\t\tparentFolder,\n\t\t\tdocumentType\n\t\t}).onConflict((oc) => oc.columns([\"driveId\", \"id\"]).doUpdateSet({\n\t\t\tparentFolder,\n\t\t\tname: resolved,\n\t\t\trequestedName,\n\t\t\tkind: \"file\",\n\t\t\tdocumentType,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t})).execute();\n\t}\n\tasync handleAddFolder(trx, driveId, input) {\n\t\tconst parentFolder = input.parentFolderId ?? null;\n\t\tconst resolved = await this.resolveSiblingName(trx, driveId, parentFolder, input.name, input.folderId);\n\t\tawait trx.insertInto(\"DriveNode\").values({\n\t\t\tdriveId,\n\t\t\tid: input.folderId,\n\t\t\tkind: \"folder\",\n\t\t\tname: resolved,\n\t\t\trequestedName: input.name,\n\t\t\tparentFolder,\n\t\t\tdocumentType: null\n\t\t}).onConflict((oc) => oc.columns([\"driveId\", \"id\"]).doUpdateSet({\n\t\t\tparentFolder,\n\t\t\tname: resolved,\n\t\t\trequestedName: input.name,\n\t\t\tkind: \"folder\",\n\t\t\tdocumentType: null,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t})).execute();\n\t}\n\tasync handleUpdateFolder(trx, driveId, input) {\n\t\tconst row = await trx.selectFrom(\"DriveNode\").selectAll().where(\"driveId\", \"=\", driveId).where(\"id\", \"=\", input.folderId).executeTakeFirst();\n\t\tif (!row) return;\n\t\tconst nextParentFolder = input.parentFolderId === void 0 ? row.parentFolder : input.parentFolderId ?? null;\n\t\tconst nextRequestedName = typeof input.name === \"string\" ? input.name : row.requestedName;\n\t\tconst resolved = await this.resolveSiblingName(trx, driveId, nextParentFolder, nextRequestedName, input.folderId);\n\t\tawait trx.updateTable(\"DriveNode\").set({\n\t\t\tparentFolder: nextParentFolder,\n\t\t\tname: resolved,\n\t\t\trequestedName: nextRequestedName,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(\"driveId\", \"=\", driveId).where(\"id\", \"=\", input.folderId).execute();\n\t}\n\tasync resolveSiblingName(trx, driveId, parentFolder, requested, excludeId) {\n\t\tlet query = trx.selectFrom(\"DriveNode\").select(\"name\").where(\"driveId\", \"=\", driveId).where(\"id\", \"!=\", excludeId);\n\t\tquery = parentFolder === null ? query.where(\"parentFolder\", \"is\", null) : query.where(\"parentFolder\", \"=\", parentFolder);\n\t\treturn resolveCollision(requested, (await query.execute()).map((r) => r.name));\n\t}\n\tasync lookupDocumentName(trx, docId) {\n\t\treturn (await trx.selectFrom(\"DocumentName\").select(\"name\").where(\"docId\", \"=\", docId).executeTakeFirst())?.name;\n\t}\n\tparseFileMetadata(input) {\n\t\tconst metadata = input.metadata;\n\t\tif (!metadata || typeof metadata !== \"object\" || metadata.kind !== \"file\" || typeof metadata.documentType !== \"string\") throw new Error(`ADD_RELATIONSHIP for target ${input.targetId}: missing or invalid drive/child file metadata (expected { kind: \"file\", parentFolderId, documentType })`);\n\t\tconst typed = metadata;\n\t\treturn {\n\t\t\tkind: \"file\",\n\t\t\tparentFolderId: typed.parentFolderId ?? null,\n\t\t\tdocumentType: typed.documentType\n\t\t};\n\t}\n\tasync upsertDocumentName(trx, docId, name) {\n\t\tawait trx.insertInto(\"DocumentName\").values({\n\t\t\tdocId,\n\t\t\tname\n\t\t}).onConflict((oc) => oc.column(\"docId\").doUpdateSet({\n\t\t\tname,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t})).execute();\n\t}\n};\n//#endregion\n//#region src/read-model/drive-node-view.ts\nconst DEFAULT_LIMIT$1 = 100;\nfunction parseListChildrenPaging(paging) {\n\tif (paging === void 0) return {\n\t\tlimit: DEFAULT_LIMIT$1,\n\t\tcursor: null\n\t};\n\tif (!Number.isInteger(paging.limit) || paging.limit < 1) throw new Error(`Invalid paging limit: ${String(paging.limit)} (must be an integer >= 1)`);\n\tif (paging.cursor === \"\") return {\n\t\tlimit: paging.limit,\n\t\tcursor: null\n\t};\n\treturn {\n\t\tlimit: paging.limit,\n\t\tcursor: decodeKeysetCursor(paging.cursor)\n\t};\n}\nfunction encodeKeysetCursor(createdAt, id) {\n\treturn globalThis.btoa(JSON.stringify({\n\t\tcreatedAt: createdAt.toISOString(),\n\t\tid\n\t}));\n}\nfunction decodeKeysetCursor(cursor) {\n\tlet decoded;\n\ttry {\n\t\tdecoded = globalThis.atob(cursor);\n\t} catch {\n\t\tthrow new Error(`Invalid paging cursor: ${JSON.stringify(cursor)} (must be a keyset cursor returned by a prior page)`);\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(decoded);\n\t} catch {\n\t\tthrow new Error(`Invalid paging cursor: ${JSON.stringify(cursor)} (must be a keyset cursor returned by a prior page)`);\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || typeof parsed.createdAt !== \"string\" || typeof parsed.id !== \"string\") throw new Error(`Invalid paging cursor: ${JSON.stringify(cursor)} (must be a keyset cursor returned by a prior page)`);\n\tconst createdAt = new Date(parsed.createdAt);\n\tif (Number.isNaN(createdAt.getTime())) throw new Error(`Invalid paging cursor: ${JSON.stringify(cursor)} (createdAt is not a valid timestamp)`);\n\treturn {\n\t\tcreatedAt,\n\t\tid: parsed.id\n\t};\n}\nvar DriveNodeView = class {\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tasync getNode(driveId, nodeId) {\n\t\tconst row = await this.db.selectFrom(\"DriveNode\").selectAll().where(\"driveId\", \"=\", driveId).where(\"id\", \"=\", nodeId).executeTakeFirst();\n\t\tif (!row) return void 0;\n\t\treturn rowToNode(row);\n\t}\n\tasync listChildren(driveId, parentFolder, paging) {\n\t\tconst { limit, cursor } = parseListChildrenPaging(paging);\n\t\tlet query = this.db.selectFrom(\"DriveNode\").selectAll().where(\"driveId\", \"=\", driveId);\n\t\tif (parentFolder === null) query = query.where(\"parentFolder\", \"is\", null);\n\t\telse if (parentFolder !== void 0) query = query.where(\"parentFolder\", \"=\", parentFolder);\n\t\tif (cursor !== null) query = query.where((eb) => eb(eb.refTuple(\"createdAt\", \"id\"), \">\", eb.tuple(cursor.createdAt, cursor.id)));\n\t\tconst rows = await query.orderBy(\"createdAt\", \"asc\").orderBy(\"id\", \"asc\").limit(limit + 1).execute();\n\t\tconst hasMore = rows.length > limit;\n\t\tconst sliced = hasMore ? rows.slice(0, limit) : rows;\n\t\tconst last = sliced[sliced.length - 1];\n\t\treturn {\n\t\t\tresults: sliced.map(rowToNode),\n\t\t\toptions: {\n\t\t\t\tcursor: paging?.cursor ?? \"\",\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor: hasMore ? encodeKeysetCursor(last.createdAt, last.id) : void 0\n\t\t};\n\t}\n\tasync listAll(driveId) {\n\t\treturn (await this.db.selectFrom(\"DriveNode\").selectAll().where(\"driveId\", \"=\", driveId).orderBy(\"createdAt\", \"asc\").orderBy(\"id\", \"asc\").execute()).map(rowToNode);\n\t}\n\tasync getDescendants(driveId, root) {\n\t\treturn (await this.db.withRecursive(\"descendants\", (qb) => qb.selectFrom(\"DriveNode\").select([\n\t\t\t\"driveId\",\n\t\t\t\"id\",\n\t\t\t\"kind\",\n\t\t\t\"name\",\n\t\t\t\"requestedName\",\n\t\t\t\"parentFolder\",\n\t\t\t\"documentType\",\n\t\t\t\"createdAt\"\n\t\t]).where(\"driveId\", \"=\", driveId).where(\"id\", \"=\", root).unionAll(qb.selectFrom(\"DriveNode\").innerJoin(\"descendants\", \"DriveNode.parentFolder\", \"descendants.id\").where(\"DriveNode.driveId\", \"=\", driveId).select([\n\t\t\t\"DriveNode.driveId\",\n\t\t\t\"DriveNode.id\",\n\t\t\t\"DriveNode.kind\",\n\t\t\t\"DriveNode.name\",\n\t\t\t\"DriveNode.requestedName\",\n\t\t\t\"DriveNode.parentFolder\",\n\t\t\t\"DriveNode.documentType\",\n\t\t\t\"DriveNode.createdAt\"\n\t\t]))).selectFrom(\"descendants\").select([\n\t\t\t\"driveId\",\n\t\t\t\"id\",\n\t\t\t\"kind\",\n\t\t\t\"name\",\n\t\t\t\"requestedName\",\n\t\t\t\"parentFolder\",\n\t\t\t\"documentType\"\n\t\t]).orderBy(\"createdAt\", \"asc\").orderBy(\"id\", \"asc\").execute()).map(rowToNode);\n\t}\n};\nfunction rowToNode(row) {\n\tif (row.kind === \"file\") {\n\t\tif (row.documentType === null) throw new Error(`DriveNode ${row.driveId}/${row.id}: file row has null documentType, which violates the schema CHECK constraint`);\n\t\treturn {\n\t\t\tkind: \"file\",\n\t\t\tid: row.id,\n\t\t\tdriveId: row.driveId,\n\t\t\tparentFolder: row.parentFolder,\n\t\t\tname: row.name,\n\t\t\tdocumentType: row.documentType\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"folder\",\n\t\tid: row.id,\n\t\tdriveId: row.driveId,\n\t\tparentFolder: row.parentFolder,\n\t\tname: row.name\n\t};\n}\n//#endregion\n//#region src/client/reactor-drive-client.ts\n/**\n* Implementation of {@link IDriveClient} backed by the reactor's relationship\n* primitives and the drive-scoped folder actions. Folder structure lives in\n* the operation log (ADD_FOLDER/UPDATE_FOLDER/REMOVE_FOLDER + ADD_RELATIONSHIP\n* for files) and is materialised by `NodeProcessor` into the `DriveNode`\n* table consumed via {@link IDriveReadModel}.\n*/\nvar ReactorDriveClient = class {\n\treactor;\n\treadModel;\n\tconstructor(args) {\n\t\tthis.reactor = args.reactor;\n\t\tthis.readModel = args.readModel;\n\t}\n\tasync create(input, signal) {\n\t\tconst driveDoc = reactorDriveCreateDocument({ global: {\n\t\t\tname: input.global.name,\n\t\t\ticon: input.global.icon ?? null\n\t\t} });\n\t\tif (input.local) {\n\t\t\tif (typeof input.local.sharingType === \"string\") driveDoc.state.local.sharingType = input.local.sharingType;\n\t\t\tif (typeof input.local.availableOffline === \"boolean\") driveDoc.state.local.availableOffline = input.local.availableOffline;\n\t\t}\n\t\tif (input.preferredEditor) driveDoc.header.meta = {\n\t\t\t...driveDoc.header.meta,\n\t\t\tpreferredEditor: input.preferredEditor\n\t\t};\n\t\tconst created = await this.reactor.create(driveDoc, void 0, signal);\n\t\treturn this.toLegacyDriveDocument(created, created.header.id);\n\t}\n\tasync addFile(driveIdentifier, document, parentFolder, signal) {\n\t\tconst documentId = document.header.id;\n\t\tconst createInput = {\n\t\t\tmodel: document.header.documentType,\n\t\t\tversion: 0,\n\t\t\tdocumentId,\n\t\t\tsigning: {\n\t\t\t\tsignature: documentId,\n\t\t\t\tpublicKey: document.header.sig.publicKey,\n\t\t\t\tnonce: document.header.sig.nonce,\n\t\t\t\tcreatedAtUtcIso: document.header.createdAtUtcIso,\n\t\t\t\tdocumentType: document.header.documentType\n\t\t\t},\n\t\t\tslug: document.header.slug,\n\t\t\tname: document.header.name,\n\t\t\tbranch: document.header.branch,\n\t\t\tmeta: document.header.meta,\n\t\t\tprotocolVersions: document.header.protocolVersions ?? { \"base-reducer\": 2 }\n\t\t};\n\t\tconst metadata = {\n\t\t\tkind: \"file\",\n\t\t\tparentFolderId: parentFolder ?? null,\n\t\t\tdocumentType: document.header.documentType\n\t\t};\n\t\tconst request = { jobs: [{\n\t\t\tkey: \"create\",\n\t\t\tdocumentId,\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\",\n\t\t\tactions: [createDocumentAction(createInput), upgradeDocumentAction({\n\t\t\t\tdocumentId,\n\t\t\t\tmodel: document.header.documentType,\n\t\t\t\tfromVersion: 0,\n\t\t\t\ttoVersion: document.state.document.version,\n\t\t\t\tinitialState: document.state\n\t\t\t})],\n\t\t\tdependsOn: []\n\t\t}, {\n\t\t\tkey: \"link\",\n\t\t\tdocumentId: driveIdentifier,\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\",\n\t\t\tactions: [addRelationshipAction(driveIdentifier, documentId, DRIVE_CHILD_RELATIONSHIP_TYPE, metadata)],\n\t\t\tdependsOn: [\"create\"]\n\t\t}] };\n\t\tawait this.reactor.executeBatch(request, signal);\n\t\treturn this.reactor.get(documentId, void 0, signal);\n\t}\n\tasync addFolder(driveIdentifier, name, parentFolder, signal) {\n\t\tconst folderId = generateId();\n\t\tawait this.reactor.execute(driveIdentifier, \"main\", [addFolderAction({\n\t\t\tfolderId,\n\t\t\tparentFolderId: parentFolder ?? null,\n\t\t\tname\n\t\t})], signal);\n\t\treturn {\n\t\t\tid: folderId,\n\t\t\tkind: \"folder\",\n\t\t\tname,\n\t\t\tparentFolder: parentFolder ?? null\n\t\t};\n\t}\n\tasync removeNode(driveIdentifier, nodeId, signal) {\n\t\tconst node = await this.readModel.getNode(driveIdentifier, nodeId, signal);\n\t\tif (!node) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);\n\t\tif (node.kind === \"folder\") {\n\t\t\tconst subtree = await this.readModel.getDescendants(driveIdentifier, nodeId, signal);\n\t\t\tconst fileDescendants = subtree.filter((n) => n.kind === \"file\");\n\t\t\tconst subFolders = subtree.filter((n) => n.kind === \"folder\").filter((f) => f.id !== nodeId);\n\t\t\tconst deepestFirstFolders = this.orderDeepestFirst(subFolders, nodeId);\n\t\t\tconst batch = [\n\t\t\t\t...fileDescendants.map((f) => removeRelationshipAction(driveIdentifier, f.id, DRIVE_CHILD_RELATIONSHIP_TYPE)),\n\t\t\t\t...deepestFirstFolders.map((f) => removeFolderAction({ folderId: f.id })),\n\t\t\t\tremoveFolderAction({ folderId: nodeId })\n\t\t\t];\n\t\t\tawait this.reactor.execute(driveIdentifier, \"main\", batch, signal);\n\t\t\tfor (const file of fileDescendants) await this.reactor.deleteDocument(file.id, \"cascade\", signal);\n\t\t\treturn;\n\t\t}\n\t\tawait this.reactor.execute(driveIdentifier, \"main\", [removeRelationshipAction(driveIdentifier, nodeId, DRIVE_CHILD_RELATIONSHIP_TYPE)], signal);\n\t\tawait this.reactor.deleteDocument(nodeId, void 0, signal);\n\t}\n\tasync renameNode(driveIdentifier, nodeId, name, signal) {\n\t\tconst node = await this.readModel.getNode(driveIdentifier, nodeId, signal);\n\t\tif (!node) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);\n\t\tif (node.kind === \"file\") await this.reactor.rename(nodeId, name, \"main\", signal);\n\t\telse await this.reactor.execute(driveIdentifier, \"main\", [updateFolderAction({\n\t\t\tfolderId: nodeId,\n\t\t\tname\n\t\t})], signal);\n\t\tconst updated = await this.readModel.getNode(driveIdentifier, nodeId, signal);\n\t\tif (!updated) throw new Error(\"Node missing from drive after rename\");\n\t\treturn this.toLegacyNode(updated);\n\t}\n\tasync setPreferredEditorOnNode(nodeId, preferredEditor, signal) {\n\t\treturn this.reactor.setPreferredEditor(nodeId, preferredEditor, \"main\", signal);\n\t}\n\tasync moveNode(driveIdentifier, srcNodeId, targetParentFolderId, signal) {\n\t\tconst node = await this.readModel.getNode(driveIdentifier, srcNodeId, signal);\n\t\tif (!node) throw new Error(`Node ${srcNodeId} not found in drive ${driveIdentifier}`);\n\t\tif (node.kind === \"folder\") await this.reactor.execute(driveIdentifier, \"main\", [updateFolderAction({\n\t\t\tfolderId: srcNodeId,\n\t\t\tparentFolderId: targetParentFolderId ?? null\n\t\t})], signal);\n\t\telse {\n\t\t\tconst metadata = {\n\t\t\t\tkind: \"file\",\n\t\t\t\tparentFolderId: targetParentFolderId ?? null,\n\t\t\t\tdocumentType: node.documentType\n\t\t\t};\n\t\t\tawait this.reactor.execute(driveIdentifier, \"main\", [removeRelationshipAction(driveIdentifier, srcNodeId, DRIVE_CHILD_RELATIONSHIP_TYPE), addRelationshipAction(driveIdentifier, srcNodeId, DRIVE_CHILD_RELATIONSHIP_TYPE, metadata)], signal);\n\t\t}\n\t\tconst drive = await this.reactor.get(driveIdentifier, void 0, signal);\n\t\treturn this.toLegacyDriveDocument(drive, driveIdentifier);\n\t}\n\tasync copyNode(driveIdentifier, srcNodeId, targetParentFolderId, signal) {\n\t\tif (!await this.readModel.getNode(driveIdentifier, srcNodeId, signal)) throw new Error(`Node ${srcNodeId} not found in drive ${driveIdentifier}`);\n\t\tconst subtree = await this.readModel.getDescendants(driveIdentifier, srcNodeId, signal);\n\t\tif (targetParentFolderId !== void 0 && subtree.some((n) => n.id === targetParentFolderId)) throw new Error(`Cannot copy node ${srcNodeId} into itself or one of its descendants (target: ${targetParentFolderId})`);\n\t\tconst idMap = /* @__PURE__ */ new Map();\n\t\tfor (const node of subtree) idMap.set(node.id, generateId());\n\t\tconst jobs = [];\n\t\tconst driveActions = [];\n\t\tconst fileCreateKeys = [];\n\t\tfor (const node of subtree) {\n\t\t\tconst newId = idMap.get(node.id);\n\t\t\tlet newParent;\n\t\t\tif (node.id === srcNodeId) newParent = targetParentFolderId ?? null;\n\t\t\telse {\n\t\t\t\tif (node.parentFolder == null) throw new Error(`copyNode: descendant ${node.id} has no parentFolder`);\n\t\t\t\tconst mapped = idMap.get(node.parentFolder);\n\t\t\t\tif (mapped === void 0) throw new Error(`copyNode: descendant ${node.id} parent ${node.parentFolder} missing from idMap`);\n\t\t\t\tnewParent = mapped;\n\t\t\t}\n\t\t\tif (node.kind === \"folder\") {\n\t\t\t\tdriveActions.push(addFolderAction({\n\t\t\t\t\tfolderId: newId,\n\t\t\t\t\tparentFolderId: newParent,\n\t\t\t\t\tname: node.name\n\t\t\t\t}));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst srcDoc = await this.reactor.get(node.id, void 0, signal);\n\t\t\tconst documentType = srcDoc.header.documentType;\n\t\t\tconst { results: allModules } = await this.reactor.getDocumentModelModules();\n\t\t\tconst modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);\n\t\t\tif (modulesForType.length === 0) throw new Error(`Document model module not found for type: ${documentType}`);\n\t\t\tconst reducers = {};\n\t\t\tfor (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;\n\t\t\tconst config = { reducers };\n\t\t\tconst duplicated = replayDocumentVersioned(srcDoc.initialState, srcDoc.operations, config, createPresignedHeader(newId, documentType));\n\t\t\tduplicated.header.name = node.name;\n\t\t\tconst createInput = {\n\t\t\t\tmodel: duplicated.header.documentType,\n\t\t\t\tversion: 0,\n\t\t\t\tdocumentId: newId,\n\t\t\t\tsigning: {\n\t\t\t\t\tsignature: newId,\n\t\t\t\t\tpublicKey: duplicated.header.sig.publicKey,\n\t\t\t\t\tnonce: duplicated.header.sig.nonce,\n\t\t\t\t\tcreatedAtUtcIso: duplicated.header.createdAtUtcIso,\n\t\t\t\t\tdocumentType: duplicated.header.documentType\n\t\t\t\t},\n\t\t\t\tslug: duplicated.header.slug,\n\t\t\t\tname: duplicated.header.name,\n\t\t\t\tbranch: duplicated.header.branch,\n\t\t\t\tmeta: duplicated.header.meta,\n\t\t\t\tprotocolVersions: duplicated.header.protocolVersions ?? { \"base-reducer\": 2 }\n\t\t\t};\n\t\t\tconst createKey = `create:${newId}`;\n\t\t\tjobs.push({\n\t\t\t\tkey: createKey,\n\t\t\t\tdocumentId: newId,\n\t\t\t\tscope: \"document\",\n\t\t\t\tbranch: \"main\",\n\t\t\t\tactions: [createDocumentAction(createInput), upgradeDocumentAction({\n\t\t\t\t\tdocumentId: newId,\n\t\t\t\t\tmodel: duplicated.header.documentType,\n\t\t\t\t\tfromVersion: 0,\n\t\t\t\t\ttoVersion: duplicated.state.document.version,\n\t\t\t\t\tinitialState: duplicated.state\n\t\t\t\t})],\n\t\t\t\tdependsOn: []\n\t\t\t});\n\t\t\tfileCreateKeys.push(createKey);\n\t\t\tconst metadata = {\n\t\t\t\tkind: \"file\",\n\t\t\t\tparentFolderId: newParent,\n\t\t\t\tdocumentType: duplicated.header.documentType\n\t\t\t};\n\t\t\tdriveActions.push(addRelationshipAction(driveIdentifier, newId, DRIVE_CHILD_RELATIONSHIP_TYPE, metadata));\n\t\t}\n\t\tif (driveActions.length > 0) jobs.push({\n\t\t\tkey: \"drive\",\n\t\t\tdocumentId: driveIdentifier,\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\",\n\t\t\tactions: driveActions,\n\t\t\tdependsOn: fileCreateKeys\n\t\t});\n\t\tif (jobs.length > 0) {\n\t\t\tconst request = { jobs };\n\t\t\tawait this.reactor.executeBatch(request, signal);\n\t\t}\n\t\tconst drive = await this.reactor.get(driveIdentifier, void 0, signal);\n\t\treturn this.toLegacyDriveDocument(drive, driveIdentifier);\n\t}\n\tasync getNode(driveIdentifier, nodeId, signal) {\n\t\tconst node = await this.readModel.getNode(driveIdentifier, nodeId, signal);\n\t\tif (!node) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);\n\t\treturn this.toLegacyNode(node);\n\t}\n\tasync listNodes(driveIdentifier, parentFolder, paging, signal) {\n\t\tconst page = await this.readModel.listChildren(driveIdentifier, parentFolder, paging, signal);\n\t\treturn {\n\t\t\tresults: page.results.map((node) => this.toLegacyNode(node)),\n\t\t\toptions: page.options,\n\t\t\t...page.nextCursor !== void 0 ? { nextCursor: page.nextCursor } : {},\n\t\t\t...page.totalCount !== void 0 ? { totalCount: page.totalCount } : {}\n\t\t};\n\t}\n\ttoLegacyNode(node) {\n\t\tif (node.kind === \"file\") {\n\t\t\tconst file = node;\n\t\t\treturn {\n\t\t\t\tid: file.id,\n\t\t\t\tkind: \"file\",\n\t\t\t\tname: file.name,\n\t\t\t\tparentFolder: file.parentFolder,\n\t\t\t\tdocumentType: file.documentType\n\t\t\t};\n\t\t}\n\t\tconst folder = node;\n\t\treturn {\n\t\t\tid: folder.id,\n\t\t\tkind: \"folder\",\n\t\t\tname: folder.name,\n\t\t\tparentFolder: folder.parentFolder\n\t\t};\n\t}\n\tasync toLegacyDriveDocument(doc, driveId) {\n\t\tif (doc.header.documentType !== \"powerhouse/reactor-drive\") throw new Error(`Document ${doc.header.id} is not a reactor-drive document`);\n\t\tconst allNodes = await this.readModel.listAll(driveId);\n\t\tconst legacy = structuredClone(doc);\n\t\tconst existingGlobal = legacy.state.global;\n\t\tlegacy.state.global = {\n\t\t\tname: existingGlobal.name ?? \"\",\n\t\t\ticon: existingGlobal.icon ?? null,\n\t\t\tnodes: allNodes.map((n) => this.toLegacyNode(n))\n\t\t};\n\t\treturn legacy;\n\t}\n\torderDeepestFirst(folders, rootId) {\n\t\tconst depthById = /* @__PURE__ */ new Map();\n\t\tconst compute = (id) => {\n\t\t\tif (id === rootId) return 0;\n\t\t\tconst cached = depthById.get(id);\n\t\t\tif (cached !== void 0) return cached;\n\t\t\tconst folder = folders.find((f) => f.id === id);\n\t\t\tif (!folder) return 0;\n\t\t\tconst depth = compute(folder.parentFolder ?? rootId) + 1;\n\t\t\tdepthById.set(id, depth);\n\t\t\treturn depth;\n\t\t};\n\t\treturn folders.slice().sort((a, b) => compute(b.id) - compute(a.id));\n\t}\n};\n//#endregion\n//#region src/subgraph/schema.ts\nconst typeDefs = gql`\n enum ReactorDriveNodeKind {\n FILE\n FOLDER\n }\n\n input ReactorDrivePagingInput {\n cursor: String\n limit: Int\n }\n\n type ReactorDriveFileNode {\n id: ID!\n driveId: ID!\n name: String!\n parentFolder: ID\n documentType: String!\n }\n\n type ReactorDriveFolderNode {\n id: ID!\n driveId: ID!\n name: String!\n parentFolder: ID\n children(\n paging: ReactorDrivePagingInput\n kind: ReactorDriveNodeKind\n ): ReactorDriveNodePage!\n }\n\n union ReactorDriveNode = ReactorDriveFileNode | ReactorDriveFolderNode\n\n type ReactorDriveNodePage {\n results: [ReactorDriveNode!]!\n nextCursor: String\n hasMore: Boolean!\n totalCount: Int\n }\n\n type ReactorDrive {\n id: ID!\n name: String!\n icon: String\n sharingType: String!\n availableOffline: Boolean!\n rootNodes(\n paging: ReactorDrivePagingInput\n kind: ReactorDriveNodeKind\n ): ReactorDriveNodePage!\n }\n\n type Query {\n reactorDrive(id: ID!): ReactorDrive\n reactorDriveNode(driveId: ID!, id: ID!): ReactorDriveNode\n reactorDriveDescendants(driveId: ID!, root: ID!): [ReactorDriveNode!]!\n }\n`;\n//#endregion\n//#region src/subgraph/resolvers.ts\nconst DEFAULT_LIMIT = 100;\nfunction toPaging(input) {\n\tif (!input) return void 0;\n\treturn {\n\t\tcursor: input.cursor ?? \"\",\n\t\tlimit: input.limit ?? DEFAULT_LIMIT\n\t};\n}\nfunction filterByKind(page, kind) {\n\tif (!kind) return page;\n\tconst wanted = kind === \"FILE\" ? \"file\" : \"folder\";\n\treturn {\n\t\t...page,\n\t\tresults: page.results.filter((node) => node.kind === wanted)\n\t};\n}\nfunction shapePage(page) {\n\treturn {\n\t\tresults: page.results,\n\t\tnextCursor: page.nextCursor,\n\t\thasMore: page.nextCursor !== void 0,\n\t\ttotalCount: page.totalCount\n\t};\n}\n/**\n* Builds GraphQL resolvers backed by the drive read model. The resolvers are\n* pure — every external dependency is read off the GraphQL context. Wiring\n* the resolvers into a subgraph (e.g. `reactor-api`'s `ISubgraph`) is the\n* caller's responsibility.\n*/\nfunction createReactorDriveResolvers() {\n\treturn {\n\t\tQuery: {\n\t\t\tasync reactorDrive(_root, args, ctx) {\n\t\t\t\tconst document = await ctx.reactorClient.get(args.id);\n\t\t\t\tif (document.header.documentType !== \"powerhouse/reactor-drive\") return null;\n\t\t\t\treturn {\n\t\t\t\t\tid: document.header.id,\n\t\t\t\t\tname: document.state.global.name,\n\t\t\t\t\ticon: document.state.global.icon,\n\t\t\t\t\tsharingType: document.state.local.sharingType,\n\t\t\t\t\tavailableOffline: document.state.local.availableOffline\n\t\t\t\t};\n\t\t\t},\n\t\t\tasync reactorDriveNode(_root, args, ctx) {\n\t\t\t\treturn ctx.readModel.getNode(args.driveId, args.id);\n\t\t\t},\n\t\t\tasync reactorDriveDescendants(_root, args, ctx) {\n\t\t\t\treturn ctx.readModel.getDescendants(args.driveId, args.root);\n\t\t\t}\n\t\t},\n\t\tReactorDrive: { async rootNodes(parent, args, ctx) {\n\t\t\treturn shapePage(filterByKind(await ctx.readModel.listChildren(parent.id, null, toPaging(args.paging)), args.kind));\n\t\t} },\n\t\tReactorDriveFolderNode: { async children(parent, args, ctx) {\n\t\t\treturn shapePage(filterByKind(await ctx.readModel.listChildren(parent.driveId, parent.id, toPaging(args.paging)), args.kind));\n\t\t} },\n\t\tReactorDriveNode: { __resolveType(node) {\n\t\t\treturn node.kind === \"file\" ? \"ReactorDriveFileNode\" : \"ReactorDriveFolderNode\";\n\t\t} }\n\t};\n}\n//#endregion\n//#region src/migration/migrate-legacy-state.ts\n/**\n* Translates a legacy `document-drive` `state.global.nodes` array into the\n* action vocabulary used by the new reactor-drive module.\n*\n* Folder nodes are emitted as `ADD_FOLDER` actions targeting the drive\n* document. File nodes are emitted as `ADD_RELATIONSHIP` actions on the drive\n* with `drive/child` metadata carrying the parent folder id. File nodes\n* assume the underlying PHDocument still exists under the same id — the\n* migration only re-links it into the new drive, it does not recreate\n* documents.\n*\n* Re-running the migration is safe: existing `DriveNode` rows are skipped\n* so already-migrated nodes are left untouched.\n*/\nasync function migrateLegacyDriveState(args) {\n\tconst { reactor, readModel, driveId, nodes, signal } = args;\n\tconst branch = args.branch ?? \"main\";\n\tconst ordered = orderLegacyNodes(nodes);\n\tconst actions = [];\n\tlet skippedExisting = 0;\n\tfor (const node of ordered) {\n\t\tif (await readModel.getNode(driveId, node.id, signal)) {\n\t\t\tskippedExisting += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tactions.push(toAction(driveId, node));\n\t}\n\tif (actions.length === 0) return {\n\t\temittedActions: 0,\n\t\tskippedExisting\n\t};\n\tawait reactor.execute(driveId, branch, actions, signal);\n\treturn {\n\t\temittedActions: actions.length,\n\t\tskippedExisting\n\t};\n}\nfunction toAction(driveId, node) {\n\tif (node.kind === \"folder\") return addFolderAction({\n\t\tfolderId: node.id,\n\t\tparentFolderId: node.parentFolder ?? null,\n\t\tname: node.name\n\t});\n\tconst fileNode = node;\n\tconst metadata = {\n\t\tkind: \"file\",\n\t\tparentFolderId: fileNode.parentFolder ?? null,\n\t\tdocumentType: fileNode.documentType\n\t};\n\treturn addRelationshipAction(driveId, fileNode.id, DRIVE_CHILD_RELATIONSHIP_TYPE, metadata);\n}\n/**\n* Sorts legacy nodes so that any folder appears before its children. The\n* legacy state stores nodes in insertion order, which usually already\n* satisfies that property, but defensive sorting keeps replay deterministic\n* if the input was constructed out of order.\n*/\nfunction orderLegacyNodes(nodes) {\n\tconst byId = /* @__PURE__ */ new Map();\n\tfor (const node of nodes) byId.set(node.id, node);\n\tconst visited = /* @__PURE__ */ new Set();\n\tconst ordered = [];\n\tfor (const start of nodes) {\n\t\tif (visited.has(start.id)) continue;\n\t\tconst chain = [];\n\t\tconst seenInWalk = /* @__PURE__ */ new Set();\n\t\tlet current = start;\n\t\twhile (current && !visited.has(current.id) && !seenInWalk.has(current.id)) {\n\t\t\tseenInWalk.add(current.id);\n\t\t\tchain.push(current);\n\t\t\tconst parentId = current.parentFolder;\n\t\t\tcurrent = parentId ? byId.get(parentId) : void 0;\n\t\t}\n\t\twhile (chain.length > 0) {\n\t\t\tconst node = chain.pop();\n\t\t\tif (visited.has(node.id)) continue;\n\t\t\tvisited.add(node.id);\n\t\t\tordered.push(node);\n\t\t}\n\t}\n\treturn ordered;\n}\n//#endregion\nexport { DRIVE_CHILD_RELATIONSHIP_TYPE, DriveNodeView, NodeProcessor, REACTOR_DRIVE_DOCUMENT_TYPE, REACTOR_DRIVE_FILE_EXTENSION, ReactorDriveClient, addFolderAction, createReactorDriveResolvers, getReactorDriveMigrationStatus, migrateLegacyDriveState, reactorDriveActions, reactorDriveCreateDocument, reactorDriveCreateState, reactorDriveDocumentModelModule, reactorDriveDocumentReducer, reactorDriveStateReducer, typeDefs as reactorDriveSubgraphTypeDefs, removeFolderAction, resolveCollision, runReactorDriveMigrations, setAvailableOfflineAction, setDriveIconAction, setDriveNameAction, setSharingTypeAction, updateFolderAction };\n\n//# sourceMappingURL=index.js.map","/* global btoa */\nlet base64\n\nif (typeof window !== 'undefined') {\n if (window.btoa) {\n base64 = function (input) {\n return btoa(unescape(encodeURIComponent(input)))\n }\n } else {\n // Polyfill for environments that don't have btoa or Buffer class (notably, React Native).\n // Based on https://github.com/davidchambers/Base64.js/blob/a121f75bb10c8dd5d557886c4b1069b31258d230/base64.js\n base64 = function (input) {\n const str = unescape(encodeURIComponent(input + ''))\n let output = ''\n for (\n let block, charCode, idx = 0, map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n str.charAt(idx | 0) || (map = '=', idx % 1);\n output += map.charAt(63 & block >> 8 - idx % 1 * 8)\n ) {\n charCode = str.charCodeAt(idx += 3 / 4)\n // This is a coherence check. The result of unescape(encodeURIComponent()) should always be\n // characters with code points that fit into two bytes.\n /* c8 ignore next 3 */\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\")\n }\n block = block << 8 | charCode\n }\n return output\n }\n }\n} else {\n base64 = function (input) {\n return Buffer.from(input).toString('base64')\n }\n}\n\nfunction slug (string, opts) {\n let result = slugify(string, opts)\n const fallback = opts && opts.fallback !== undefined ? opts.fallback : slug.defaults.fallback\n // If output is an empty string, try slug for base64 of string.\n if (fallback === true && result === '') {\n result = slugify(base64(string), opts)\n }\n return result\n}\n\nconst locales = {\n // http://www.eki.ee/wgrs/rom1_bg.pdf\n bg: { Й: 'Y', й: 'y', X: 'H', x: 'h', Ц: 'Ts', ц: 'ts', Щ: 'Sht', щ: 'sht', Ъ: 'A', ъ: 'a', Ь: 'Y', ь: 'y' },\n // Need a reference URL for German, although this is pretty well-known.\n de: { Ä: 'AE', ä: 'ae', Ö: 'OE', ö: 'oe', Ü: 'UE', ü: 'ue' },\n // Need a reference URL for Serbian.\n sr: { đ: 'dj', Đ: 'DJ' },\n // https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/864314/ROMANIZATION_OF_UKRAINIAN.pdf\n uk: { И: 'Y', и: 'y', Й: 'Y', й: 'y', Ц: 'Ts', ц: 'ts', Х: 'Kh', х: 'kh', Щ: 'Shch', щ: 'shch', Г: 'H', г: 'h' }\n}\n\nlet defaultLocale = {}\n\nfunction slugify (string, opts) {\n if (typeof string !== 'string') {\n throw new Error('slug() requires a string argument, received ' + typeof string)\n }\n if (!string.isWellFormed()) {\n throw new Error('slug() received a malformed string with lone surrogates')\n }\n if (typeof opts === 'string') { opts = { replacement: opts } }\n opts = opts ? Object.assign({}, opts) : {}\n opts.mode = opts.mode || slug.defaults.mode\n const defaults = slug.defaults.modes[opts.mode]\n const keys = ['replacement', 'multicharmap', 'charmap', 'remove', 'lower', 'trim']\n for (let key, i = 0, l = keys.length; i < l; i++) {\n key = keys[i]\n opts[key] = (key in opts) ? opts[key] : defaults[key]\n }\n const localeMap = locales[opts.locale] || defaultLocale\n\n let lengths = []\n for (const key in opts.multicharmap) {\n if (!Object.prototype.hasOwnProperty.call(opts.multicharmap, key)) { continue }\n\n const len = key.length\n if (lengths.indexOf(len) === -1) { lengths.push(len) }\n }\n\n // We want to match the longest string if there are multiple matches, so\n // sort lengths in descending order.\n lengths = lengths.sort(function (a, b) { return b - a })\n\n const disallowedChars = opts.mode === 'rfc3986' ? /[^\\w\\s\\-.~]/ : /[^A-Za-z0-9\\s]/\n\n let result = ''\n for (let char, i = 0, l = string.length; i < l; i++) {\n char = string[i]\n let matchedMultichar = false\n for (let j = 0; j < lengths.length; j++) {\n const len = lengths[j]\n const str = string.substr(i, len)\n if (opts.multicharmap[str]) {\n i += len - 1\n char = opts.multicharmap[str]\n matchedMultichar = true\n break\n }\n }\n if (!matchedMultichar) {\n if (localeMap[char]) {\n char = localeMap[char]\n } else if (opts.charmap[char]) {\n char = opts.charmap[char].replace(opts.replacement, ' ')\n } else if (char.includes(opts.replacement)) {\n // preserve the replacement character in case it is excluded by disallowedChars\n char = char.replace(opts.replacement, ' ')\n } else {\n char = char.replace(disallowedChars, '')\n }\n }\n result += char\n }\n\n if (opts.remove) {\n result = result.replace(opts.remove, '')\n }\n if (opts.trim) {\n result = result.trim()\n }\n result = result.replace(/\\s+/g, opts.replacement) // convert spaces\n if (opts.lower) {\n result = result.toLowerCase()\n }\n return result\n}\n\nconst initialMulticharmap = {\n // multibyte devanagari characters (hindi, sanskrit, etc.)\n फ़: 'Fi',\n ग़: 'Ghi',\n ख़: 'Khi',\n क़: 'Qi',\n ड़: 'ugDha',\n ढ़: 'ugDhha',\n य़: 'Yi',\n ज़: 'Za',\n // hebrew\n // Refs: http://www.eki.ee/wgrs/rom1_he.pdf\n // Refs: https://en.wikipedia.org/wiki/Niqqud\n בִי: 'i',\n בֵ: 'e',\n בֵי: 'e',\n בֶ: 'e',\n בַ: 'a',\n בָ: 'a',\n בֹ: 'o',\n וֹ: 'o',\n בֻ: 'u',\n וּ: 'u',\n בּ: 'b',\n כּ: 'k',\n ךּ: 'k',\n פּ: 'p',\n שׁ: 'sh',\n שׂ: 's',\n בְ: 'e',\n חֱ: 'e',\n חֲ: 'a',\n חֳ: 'o',\n בִ: 'i'\n}\n\n// https://github.com/django/django/blob/master/django/contrib/admin/static/admin/js/urlify.js\nconst initialCharmap = {\n // latin\n À: 'A',\n Á: 'A',\n Â: 'A',\n Ã: 'A',\n Ä: 'A',\n Å: 'A',\n Æ: 'AE',\n Ç: 'C',\n È: 'E',\n É: 'E',\n Ê: 'E',\n Ë: 'E',\n Ì: 'I',\n Í: 'I',\n Î: 'I',\n Ï: 'I',\n Ð: 'D',\n Ñ: 'N',\n Ò: 'O',\n Ó: 'O',\n Ô: 'O',\n Õ: 'O',\n Ö: 'O',\n Ő: 'O',\n Ø: 'O',\n Ō: 'O',\n Ù: 'U',\n Ú: 'U',\n Û: 'U',\n Ü: 'U',\n Ű: 'U',\n Ý: 'Y',\n Þ: 'TH',\n ß: 'ss',\n à: 'a',\n á: 'a',\n â: 'a',\n ã: 'a',\n ä: 'a',\n å: 'a',\n æ: 'ae',\n ç: 'c',\n è: 'e',\n é: 'e',\n ê: 'e',\n ë: 'e',\n ì: 'i',\n í: 'i',\n î: 'i',\n ï: 'i',\n ð: 'd',\n ñ: 'n',\n ò: 'o',\n ó: 'o',\n ô: 'o',\n õ: 'o',\n ö: 'o',\n ő: 'o',\n ø: 'o',\n ō: 'o',\n Œ: 'OE',\n œ: 'oe',\n ù: 'u',\n ú: 'u',\n û: 'u',\n ü: 'u',\n ű: 'u',\n ý: 'y',\n þ: 'th',\n ÿ: 'y',\n ẞ: 'SS',\n // greek\n α: 'a',\n β: 'b',\n γ: 'g',\n δ: 'd',\n ε: 'e',\n ζ: 'z',\n η: 'h',\n θ: 'th',\n ι: 'i',\n κ: 'k',\n λ: 'l',\n μ: 'm',\n ν: 'n',\n ξ: '3',\n ο: 'o',\n π: 'p',\n ρ: 'r',\n σ: 's',\n τ: 't',\n υ: 'y',\n φ: 'f',\n χ: 'x',\n ψ: 'ps',\n ω: 'w',\n ά: 'a',\n έ: 'e',\n ί: 'i',\n ό: 'o',\n ύ: 'y',\n ή: 'h',\n ώ: 'w',\n ς: 's',\n ϊ: 'i',\n ΰ: 'y',\n ϋ: 'y',\n ΐ: 'i',\n Α: 'A',\n Β: 'B',\n Γ: 'G',\n Δ: 'D',\n Ε: 'E',\n Ζ: 'Z',\n Η: 'H',\n Θ: 'Th',\n Ι: 'I',\n Κ: 'K',\n Λ: 'L',\n Μ: 'M',\n Ν: 'N',\n Ξ: '3',\n Ο: 'O',\n Π: 'P',\n Ρ: 'R',\n Σ: 'S',\n Τ: 'T',\n Υ: 'Y',\n Φ: 'F',\n Χ: 'X',\n Ψ: 'PS',\n Ω: 'W',\n Ά: 'A',\n Έ: 'E',\n Ί: 'I',\n Ό: 'O',\n Ύ: 'Y',\n Ή: 'H',\n Ώ: 'W',\n Ϊ: 'I',\n Ϋ: 'Y',\n // turkish\n ş: 's',\n Ş: 'S',\n ı: 'i',\n İ: 'I',\n ğ: 'g',\n Ğ: 'G',\n // russian\n а: 'a',\n б: 'b',\n в: 'v',\n г: 'g',\n д: 'd',\n е: 'e',\n ё: 'yo',\n ж: 'zh',\n з: 'z',\n и: 'i',\n й: 'j',\n к: 'k',\n л: 'l',\n м: 'm',\n н: 'n',\n о: 'o',\n п: 'p',\n р: 'r',\n с: 's',\n т: 't',\n у: 'u',\n ф: 'f',\n х: 'h',\n ц: 'c',\n ч: 'ch',\n ш: 'sh',\n щ: 'sh',\n ъ: 'u',\n ы: 'y',\n ь: '',\n э: 'e',\n ю: 'yu',\n я: 'ya',\n А: 'A',\n Б: 'B',\n В: 'V',\n Г: 'G',\n Д: 'D',\n Е: 'E',\n Ё: 'Yo',\n Ж: 'Zh',\n З: 'Z',\n И: 'I',\n Й: 'J',\n К: 'K',\n Л: 'L',\n М: 'M',\n Н: 'N',\n О: 'O',\n П: 'P',\n Р: 'R',\n С: 'S',\n Т: 'T',\n У: 'U',\n Ф: 'F',\n Х: 'H',\n Ц: 'C',\n Ч: 'Ch',\n Ш: 'Sh',\n Щ: 'Sh',\n Ъ: 'U',\n Ы: 'Y',\n Ь: '',\n Э: 'E',\n Ю: 'Yu',\n Я: 'Ya',\n // ukranian\n Є: 'Ye',\n І: 'I',\n Ї: 'Yi',\n Ґ: 'G',\n є: 'ye',\n і: 'i',\n ї: 'yi',\n ґ: 'g',\n // czech\n č: 'c',\n ď: 'd',\n ě: 'e',\n ň: 'n',\n ř: 'r',\n š: 's',\n ť: 't',\n ů: 'u',\n ž: 'z',\n Č: 'C',\n Ď: 'D',\n Ě: 'E',\n Ň: 'N',\n Ř: 'R',\n Š: 'S',\n Ť: 'T',\n Ů: 'U',\n Ž: 'Z',\n // slovak\n ľ: 'l',\n ĺ: 'l',\n ŕ: 'r',\n Ľ: 'L',\n Ĺ: 'L',\n Ŕ: 'R',\n // polish\n ą: 'a',\n ć: 'c',\n ę: 'e',\n ł: 'l',\n ń: 'n',\n ś: 's',\n ź: 'z',\n ż: 'z',\n Ą: 'A',\n Ć: 'C',\n Ę: 'E',\n Ł: 'L',\n Ń: 'N',\n Ś: 'S',\n Ź: 'Z',\n Ż: 'Z',\n // latvian\n ā: 'a',\n ē: 'e',\n ģ: 'g',\n ī: 'i',\n ķ: 'k',\n ļ: 'l',\n ņ: 'n',\n ū: 'u',\n Ā: 'A',\n Ē: 'E',\n Ģ: 'G',\n Ī: 'I',\n Ķ: 'K',\n Ļ: 'L',\n Ņ: 'N',\n Ū: 'U',\n // arabic\n أ: 'a',\n إ: 'i',\n ب: 'b',\n ت: 't',\n ث: 'th',\n ج: 'g',\n ح: 'h',\n خ: 'kh',\n د: 'd',\n ذ: 'th',\n ر: 'r',\n ز: 'z',\n س: 's',\n ش: 'sh',\n ص: 's',\n ض: 'd',\n ط: 't',\n ظ: 'th',\n ع: 'aa',\n غ: 'gh',\n ف: 'f',\n ق: 'k',\n ك: 'k',\n ل: 'l',\n م: 'm',\n ن: 'n',\n ه: 'h',\n و: 'o',\n ي: 'y',\n ء: 'aa',\n ة: 'a',\n // farsi\n آ: 'a',\n ا: 'a',\n پ: 'p',\n ژ: 'zh',\n گ: 'g',\n چ: 'ch',\n ک: 'k',\n ی: 'i',\n // lithuanian\n ė: 'e',\n į: 'i',\n ų: 'u',\n Ė: 'E',\n Į: 'I',\n Ų: 'U',\n // romanian\n ț: 't',\n Ț: 'T',\n ţ: 't',\n Ţ: 'T',\n ș: 's',\n Ș: 'S',\n ă: 'a',\n Ă: 'A',\n // vietnamese\n Ạ: 'A',\n Ả: 'A',\n Ầ: 'A',\n Ấ: 'A',\n Ậ: 'A',\n Ẩ: 'A',\n Ẫ: 'A',\n Ằ: 'A',\n Ắ: 'A',\n Ặ: 'A',\n Ẳ: 'A',\n Ẵ: 'A',\n Ẹ: 'E',\n Ẻ: 'E',\n Ẽ: 'E',\n Ề: 'E',\n Ế: 'E',\n Ệ: 'E',\n Ể: 'E',\n Ễ: 'E',\n Ị: 'I',\n Ỉ: 'I',\n Ĩ: 'I',\n Ọ: 'O',\n Ỏ: 'O',\n Ồ: 'O',\n Ố: 'O',\n Ộ: 'O',\n Ổ: 'O',\n Ỗ: 'O',\n Ơ: 'O',\n Ờ: 'O',\n Ớ: 'O',\n Ợ: 'O',\n Ở: 'O',\n Ỡ: 'O',\n Ụ: 'U',\n Ủ: 'U',\n Ũ: 'U',\n Ư: 'U',\n Ừ: 'U',\n Ứ: 'U',\n Ự: 'U',\n Ử: 'U',\n Ữ: 'U',\n Ỳ: 'Y',\n Ỵ: 'Y',\n Ỷ: 'Y',\n Ỹ: 'Y',\n Đ: 'D',\n ạ: 'a',\n ả: 'a',\n ầ: 'a',\n ấ: 'a',\n ậ: 'a',\n ẩ: 'a',\n ẫ: 'a',\n ằ: 'a',\n ắ: 'a',\n ặ: 'a',\n ẳ: 'a',\n ẵ: 'a',\n ẹ: 'e',\n ẻ: 'e',\n ẽ: 'e',\n ề: 'e',\n ế: 'e',\n ệ: 'e',\n ể: 'e',\n ễ: 'e',\n ị: 'i',\n ỉ: 'i',\n ĩ: 'i',\n ọ: 'o',\n ỏ: 'o',\n ồ: 'o',\n ố: 'o',\n ộ: 'o',\n ổ: 'o',\n ỗ: 'o',\n ơ: 'o',\n ờ: 'o',\n ớ: 'o',\n ợ: 'o',\n ở: 'o',\n ỡ: 'o',\n ụ: 'u',\n ủ: 'u',\n ũ: 'u',\n ư: 'u',\n ừ: 'u',\n ứ: 'u',\n ự: 'u',\n ử: 'u',\n ữ: 'u',\n ỳ: 'y',\n ỵ: 'y',\n ỷ: 'y',\n ỹ: 'y',\n đ: 'd',\n // kazakh\n Ә: 'AE',\n ә: 'ae',\n Ғ: 'GH',\n ғ: 'gh',\n Қ: 'KH',\n қ: 'kh',\n Ң: 'NG',\n ң: 'ng',\n Ү: 'UE',\n ү: 'ue',\n Ұ: 'U',\n ұ: 'u',\n Һ: 'H',\n һ: 'h',\n Ө: 'OE',\n ө: 'oe',\n // serbian\n ђ: 'dj',\n ј: 'j',\n љ: 'lj',\n њ: 'nj',\n ћ: 'c',\n џ: 'dz',\n Ђ: 'Dj',\n Ј: 'j',\n Љ: 'Lj',\n Њ: 'Nj',\n Ћ: 'C',\n Џ: 'Dz',\n nj: 'nj',\n lj: 'lj',\n Nj: 'NJ',\n Lj: 'LJ',\n // hindi\n अ: 'a',\n आ: 'aa',\n ए: 'e',\n ई: 'ii',\n ऍ: 'ei',\n ऎ: 'ae',\n ऐ: 'ai',\n इ: 'i',\n ओ: 'o',\n ऑ: 'oi',\n ऒ: 'oii',\n ऊ: 'uu',\n औ: 'ou',\n उ: 'u',\n ब: 'B',\n भ: 'Bha',\n च: 'Ca',\n छ: 'Chha',\n ड: 'Da',\n ढ: 'Dha',\n फ: 'Fa',\n ग: 'Ga',\n घ: 'Gha',\n ग़: 'Ghi',\n ह: 'Ha',\n ज: 'Ja',\n झ: 'Jha',\n क: 'Ka',\n ख: 'Kha',\n ख़: 'Khi',\n ल: 'L',\n ळ: 'Li',\n ऌ: 'Li',\n ऴ: 'Lii',\n ॡ: 'Lii',\n म: 'Ma',\n न: 'Na',\n ङ: 'Na',\n ञ: 'Nia',\n ण: 'Nae',\n ऩ: 'Ni',\n ॐ: 'oms',\n प: 'Pa',\n क़: 'Qi',\n र: 'Ra',\n ऋ: 'Ri',\n ॠ: 'Ri',\n ऱ: 'Ri',\n स: 'Sa',\n श: 'Sha',\n ष: 'Shha',\n ट: 'Ta',\n त: 'Ta',\n ठ: 'Tha',\n द: 'Tha',\n थ: 'Tha',\n ध: 'Thha',\n ड़: 'ugDha',\n ढ़: 'ugDhha',\n व: 'Va',\n य: 'Ya',\n य़: 'Yi',\n ज़: 'Za',\n // azerbaijani\n ə: 'e',\n Ə: 'E',\n // georgian\n ა: 'a',\n ბ: 'b',\n გ: 'g',\n დ: 'd',\n ე: 'e',\n ვ: 'v',\n ზ: 'z',\n თ: 't',\n ი: 'i',\n კ: 'k',\n ლ: 'l',\n მ: 'm',\n ნ: 'n',\n ო: 'o',\n პ: 'p',\n ჟ: 'zh',\n რ: 'r',\n ს: 's',\n ტ: 't',\n უ: 'u',\n ფ: 'p',\n ქ: 'k',\n ღ: 'gh',\n ყ: 'q',\n შ: 'sh',\n ჩ: 'ch',\n ც: 'ts',\n ძ: 'dz',\n წ: 'ts',\n ჭ: 'ch',\n ხ: 'kh',\n ჯ: 'j',\n ჰ: 'h',\n // hebrew\n ב: 'v',\n גּ: 'g',\n ג: 'g',\n ד: 'd',\n דּ: 'd',\n ה: 'h',\n ו: 'v',\n ז: 'z',\n ח: 'h',\n ט: 't',\n י: 'y',\n כ: 'kh',\n ך: 'kh',\n ל: 'l',\n מ: 'm',\n ם: 'm',\n נ: 'n',\n ן: 'n',\n ס: 's',\n פ: 'f',\n ף: 'f',\n ץ: 'ts',\n צ: 'ts',\n ק: 'k',\n ר: 'r',\n תּ: 't',\n ת: 't'\n}\n\nslug.charmap = Object.assign({}, initialCharmap)\nslug.multicharmap = Object.assign({}, initialMulticharmap)\nslug.defaults = {\n charmap: slug.charmap,\n mode: 'pretty',\n modes: {\n rfc3986: {\n replacement: '-',\n remove: null,\n lower: true,\n charmap: slug.charmap,\n multicharmap: slug.multicharmap,\n trim: true\n },\n pretty: {\n replacement: '-',\n remove: null,\n lower: true,\n charmap: slug.charmap,\n multicharmap: slug.multicharmap,\n trim: true\n }\n },\n multicharmap: slug.multicharmap,\n fallback: true\n}\n\nslug.reset = function () {\n slug.defaults.modes.rfc3986.charmap = slug.defaults.modes.pretty.charmap = slug.charmap = slug.defaults.charmap = Object.assign({}, initialCharmap)\n slug.defaults.modes.rfc3986.multicharmap = slug.defaults.modes.pretty.multicharmap = slug.multicharmap = slug.defaults.multicharmap = Object.assign({}, initialMulticharmap)\n defaultLocale = ''\n}\n\nslug.extend = function (customMap) {\n const keys = Object.keys(customMap)\n const multi = {}\n const single = {}\n for (let i = 0; i < keys.length; i++) {\n if (keys[i].length > 1) {\n multi[keys[i]] = customMap[keys[i]]\n } else {\n single[keys[i]] = customMap[keys[i]]\n }\n }\n Object.assign(slug.charmap, single)\n Object.assign(slug.multicharmap, multi)\n}\n\nslug.setLocale = function (locale) {\n defaultLocale = locales[locale] || {}\n}\n\nexport default slug\n","\nexport const normalizeDescriptors=(error)=>{\nCORE_ERROR_PROPS.forEach((propName)=>{\nnormalizeDescriptor(error,propName)\n})\n};\n\nexport const CORE_ERROR_PROPS=[\"name\",\"message\",\"stack\",\"cause\",\"errors\"];\n\nconst normalizeDescriptor=(error,propName)=>{\nconst descriptor=getDescriptor(error,propName);\n\nif(descriptor===undefined){\nreturn\n}\n\nif(isReadonlyGetter(descriptor)){\nsetErrorProperty(error,propName,error[propName]);\nreturn\n}\n\nif(isInvalidDescriptor(descriptor)){\nsetErrorDescriptor(error,propName,descriptor)\n}\n};\n\n\nexport const getDescriptor=(value,propName)=>{\nconst descriptor=Object.getOwnPropertyDescriptor(value,propName);\n\nif(descriptor!==undefined){\nreturn descriptor\n}\n\nconst prototype=Object.getPrototypeOf(value);\nreturn prototype===null?undefined:getDescriptor(prototype,propName)\n};\n\n\nconst isReadonlyGetter=({get,set})=>\nget!==undefined&&set===undefined;\n\nconst isInvalidDescriptor=({enumerable,writable})=>\nenumerable||!writable;\n\n\nexport const setErrorProperty=(error,propName,value)=>{\nsetErrorDescriptor(error,propName,{value})\n};\n\n\nconst setErrorDescriptor=(error,propName,descriptor)=>{\n\nObject.defineProperty(error,propName,{\n...descriptor,\n...(\"get\"in descriptor||\"set\"in descriptor?{}:{writable:true}),\nenumerable:false,\nconfigurable:true\n})\n};","import{setErrorProperty}from\"./descriptors.js\";\n\n\n\n\n\n\nexport const normalizeAggregate=(error,recurse)=>{\nif(Array.isArray(error.errors)){\nconst aggregateErrors=error.errors.\nfilter(isDefined).\nmap(recurse).\nfilter(Boolean);\nsetErrorProperty(error,\"errors\",aggregateErrors)\n}else if(isAggregateError(error)){\nsetErrorProperty(error,\"errors\",[])\n}else if(error.errors!==undefined){\ndeleteAggregateErrors(error)\n}\n};\n\nconst isDefined=(error)=>error!==undefined;\n\nconst isAggregateError=(error)=>\n\"AggregateError\"in globalThis&&(\nerror.name===\"AggregateError\"||error instanceof AggregateError);\n\nconst deleteAggregateErrors=(error)=>{\n\ndelete error.errors;\n\nif(error.errors!==undefined){\nsetErrorProperty(error,\"errors\",[])\n}\n};","import{setErrorProperty}from\"./descriptors.js\";\n\n\n\n\n\n\n\n\n\n\n\n\nexport const normalizeCause=(error,recurse)=>{\nif(!(\"cause\"in error)){\nreturn\n}\n\nconst cause=error.cause===undefined?error.cause:recurse(error.cause);\n\nif(cause===undefined){\n\ndelete error.cause\n}else{\nsetErrorProperty(error,\"cause\",cause)\n}\n};","\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst isErrorInstance=(value)=>\nisInstanceOfError(value)||hasErrorTag(value);\n\nexport default isErrorInstance;\n\n\n\nconst isInstanceOfError=(value)=>{\ntry{\nreturn value instanceof Error\n}catch{\nreturn false\n}\n};\n\nconst hasErrorTag=(value)=>{\ntry{\nreturn ERROR_TAGS.has(Object.prototype.toString.call(value))\n}catch{\nreturn false\n}\n};\n\nconst ERROR_TAGS=new Set([\n\n\"[object Error]\",\n\n\"[object DOMException]\",\n\n\"[object DOMError]\",\n\n\"[object Exception]\"]\n);","export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n","import{CORE_ERROR_PROPS}from\"../descriptors.js\";\n\n\nexport const isNonModifiableError=(error)=>\n!Object.isExtensible(error)||\nCORE_ERROR_PROPS.some(\n(propName)=>\nisNonConfigurableProp(error,propName)||isThrowingProp(error,propName)\n);\n\n\n\nconst isNonConfigurableProp=(error,propName)=>{\nconst descriptor=Object.getOwnPropertyDescriptor(error,propName);\nreturn descriptor!==undefined&&!descriptor.configurable\n};\n\n\nconst isThrowingProp=(error,propName)=>{\ntry{\n\nerror[propName];\nreturn false\n}catch{\nreturn true\n}\n};","import{setErrorProperty}from\"./descriptors.js\";\n\n\n\n\n\n\n\n\n\n\nexport const setStack=(error)=>{\nconst stack=getStack(error.message,error.name);\nsetErrorProperty(error,\"stack\",stack)\n};\n\n\n\n\n\n\n\nconst getStack=(message=\"\",name=\"Error\")=>{\nconst StackError=getErrorClass(name);\nconst{stack}=new StackError(message);\nreturn typeof stack===\"string\"&&stack!==\"\"?\nstack:\n`${name}: ${message}`\n};\n\n\n\n\n\nconst getErrorClass=(name)=>{\nconst descriptor={\nvalue:name,\nenumerable:false,\nwritable:true,\nconfigurable:true\n};\n\nconst StackError=Object.defineProperty(\nclass extends Error{},\n\"name\",\ndescriptor\n);\n\nObject.defineProperty(StackError.prototype,\"name\",descriptor);\nreturn StackError\n};","import{CORE_ERROR_PROPS,getDescriptor}from\"../descriptors.js\";\n\n\n\n\nexport const copyObject=(object)=>{\nconst objectCopy={};\n\n\nfor(const propName of getPropsToCopy(object)){\n\ntry{\nconst value=object[propName];\nconst{\nenumerable,\nconfigurable,\nwritable=true\n}=getDescriptor(object,propName);\n\nObject.defineProperty(objectCopy,propName,{\nvalue,\nenumerable,\nconfigurable,\nwritable\n})\n}catch{}\n}\n\nreturn objectCopy\n};\n\n\n\n\n\nconst getPropsToCopy=(object)=>{\nconst propNames=getOwnKeys(object);\n\n\nfor(const propName of CORE_ERROR_PROPS){\n\nif(isInheritedProp(object,propName)){\n\npropNames.push(propName)\n}\n}\n\nreturn propNames\n};\n\n\nconst getOwnKeys=(object)=>{\ntry{\nreturn Reflect.ownKeys(object)\n}catch{\nreturn[]\n}\n};\n\n\nconst isInheritedProp=(object,propName)=>{\ntry{\nreturn propName in object&&!Object.hasOwn(object,propName)\n}catch{\nreturn false\n}\n};","import{setErrorProperty}from\"../descriptors.js\";\nimport{setStack}from\"../stack.js\";\n\nimport{copyObject}from\"./copy.js\";\n\n\nexport const objectifyError=(object)=>{\nconst{name,message,stack,cause,errors,...objectA}=copyObject(object);\nconst messageA=getMessage(message,objectA);\nconst error=newError(name,messageA);\n\nif(message===messageA){\nassignObjectProps(error,objectA)\n}\n\nObject.entries({name,stack,cause,errors}).forEach(\n([propName,propValue])=>{\nsetNewErrorProperty(error,propName,propValue)\n}\n);\n\nif(stack===undefined){\nsetStack(error)\n}\n\nreturn error\n};\n\n\nconst getMessage=(message,object)=>\ntypeof message===\"string\"&&message!==\"\"?\nmessage:\ntruncateMessage(safeJsonStringify(object));\n\nconst safeJsonStringify=(object)=>{\ntry{\nreturn JSON.stringify(object)\n}catch{\nreturn safeStringify(object)\n}\n};\n\nconst safeStringify=(object)=>{\ntry{\nreturn String(object)\n}catch{\nreturn\"Invalid error\"\n}\n};\n\nconst truncateMessage=(message)=>\nmessage.length<MESSAGE_MAX_SIZE?\nmessage:\n`${message.slice(0,MESSAGE_MAX_SIZE)}...`;\n\nconst MESSAGE_MAX_SIZE=1e3;\n\nconst newError=(name,message)=>{\nif(name===\"AggregateError\"&&\"AggregateError\"in globalThis){\nreturn new AggregateError([],message)\n}\n\nif(name in NATIVE_ERRORS){\nreturn new NATIVE_ERRORS[name](message)\n}\n\nreturn new Error(message)\n};\n\nconst NATIVE_ERRORS={\nError,\nReferenceError,\nTypeError,\nSyntaxError,\nRangeError,\nURIError,\nEvalError\n};\n\n\nconst assignObjectProps=(error,object)=>{\n\nfor(const propName in object){\n\nif(!(propName in error)){\nerror[propName]=object[propName]\n}\n}\n};\n\nconst setNewErrorProperty=(error,propName,propValue)=>{\nif(propValue!==undefined){\nsetErrorProperty(error,propName,propValue)\n}\n};","import{setStack}from\"../stack.js\";\n\n\nexport const stringifyError=(value)=>{\ntry{\nconst error=new Error(String(value));\nsetStack(error);\nreturn error\n}catch(error_){\nreturn error_\n}\n};","import isErrorInstance from\"is-error-instance\";\nimport isPlainObj from\"is-plain-obj\";\n\nimport{isNonModifiableError}from\"./modifiable.js\";\nimport{objectifyError}from\"./object.js\";\nimport{stringifyError}from\"./string.js\";\n\nconst{toString:objectToString}=Object.prototype;\n\n\nexport const createError=(value)=>{\nif(isErrorPlainObj(value)){\nreturn objectifyError(value)\n}\n\nif(!isErrorInstance(value)){\nreturn stringifyError(value)\n}\n\nif(isInvalidError(value)){\nreturn objectifyError(value)\n}\n\nreturn value\n};\n\n\nconst isErrorPlainObj=(value)=>{\ntry{\nreturn isPlainObj(value)\n}catch{\nreturn false\n}\n};\n\nconst isInvalidError=(value)=>\nisProxy(value)||isNonModifiableError(value)||hasInvalidConstructor(value);\n\n\n\n\nconst isProxy=(value)=>{\ntry{\nreturn objectToString.call(value)===\"[object Object]\"\n}catch{\nreturn true\n}\n};\n\n\n\nconst hasInvalidConstructor=(error)=>\ntypeof error.constructor!==\"function\"||\ntypeof error.constructor.name!==\"string\"||\nerror.constructor.name===\"\"||\nerror.constructor.prototype!==Object.getPrototypeOf(error);","import{normalizeAggregate}from\"./aggregate.js\";\nimport{normalizeCause}from\"./cause.js\";\nimport{createError}from\"./create/main.js\";\nimport{normalizeDescriptors,setErrorProperty}from\"./descriptors.js\";\nimport{setStack}from\"./stack.js\";\n\n\nconst normalizeException=(error,{shallow=false}={})=>\nrecurseException(error,[],shallow);\n\nexport default normalizeException;\n\nconst recurseException=(error,parents,shallow)=>{\nif(parents.includes(error)){\nreturn\n}\n\nconst recurse=shallow?\nidentity:\n(innerError)=>recurseException(innerError,[...parents,error],shallow);\n\nconst errorA=createError(error);\nnormalizeProps(errorA,recurse);\nreturn errorA\n};\n\nconst identity=(error)=>error;\n\nconst normalizeProps=(error,recurse)=>{\nnormalizeName(error);\nnormalizeMessage(error);\nnormalizeStack(error);\nnormalizeCause(error,recurse);\nnormalizeAggregate(error,recurse);\nnormalizeDescriptors(error)\n};\n\n\n\n\n\n\nconst normalizeName=(error)=>{\nif(isDefinedString(error.name)){\nreturn\n}\n\nconst prototypeName=Object.getPrototypeOf(error).name;\nconst name=isDefinedString(prototypeName)?\nprototypeName:\nerror.constructor.name;\nsetErrorProperty(error,\"name\",name)\n};\n\n\nconst normalizeMessage=(error)=>{\nif(!isDefinedString(error.message)){\nsetErrorProperty(error,\"message\",\"\")\n}\n};\n\n\nconst normalizeStack=(error)=>{\nif(!isDefinedString(error.stack)){\nsetStack(error)\n}\n};\n\nconst isDefinedString=(value)=>typeof value===\"string\"&&value!==\"\";","// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>\n// This work is free. You can redistribute it and/or modify it\n// under the terms of the WTFPL, Version 2\n// For more information see LICENSE.txt or http://www.wtfpl.net/\n//\n// For more information, the home page:\n// http://pieroxy.net/blog/pages/lz-string/testing.html\n//\n// LZ-based compression algorithm, version 1.4.5\nvar LZString = (function() {\n\n// private property\nvar f = String.fromCharCode;\nvar keyStrBase64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\nvar keyStrUriSafe = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$\";\nvar baseReverseDic = {};\n\nfunction getBaseValue(alphabet, character) {\n if (!baseReverseDic[alphabet]) {\n baseReverseDic[alphabet] = {};\n for (var i=0 ; i<alphabet.length ; i++) {\n baseReverseDic[alphabet][alphabet.charAt(i)] = i;\n }\n }\n return baseReverseDic[alphabet][character];\n}\n\nvar LZString = {\n compressToBase64 : function (input) {\n if (input == null) return \"\";\n var res = LZString._compress(input, 6, function(a){return keyStrBase64.charAt(a);});\n switch (res.length % 4) { // To produce valid Base64\n default: // When could this happen ?\n case 0 : return res;\n case 1 : return res+\"===\";\n case 2 : return res+\"==\";\n case 3 : return res+\"=\";\n }\n },\n\n decompressFromBase64 : function (input) {\n if (input == null) return \"\";\n if (input == \"\") return null;\n return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrBase64, input.charAt(index)); });\n },\n\n compressToUTF16 : function (input) {\n if (input == null) return \"\";\n return LZString._compress(input, 15, function(a){return f(a+32);}) + \" \";\n },\n\n decompressFromUTF16: function (compressed) {\n if (compressed == null) return \"\";\n if (compressed == \"\") return null;\n return LZString._decompress(compressed.length, 16384, function(index) { return compressed.charCodeAt(index) - 32; });\n },\n\n //compress into uint8array (UCS-2 big endian format)\n compressToUint8Array: function (uncompressed) {\n var compressed = LZString.compress(uncompressed);\n var buf=new Uint8Array(compressed.length*2); // 2 bytes per character\n\n for (var i=0, TotalLen=compressed.length; i<TotalLen; i++) {\n var current_value = compressed.charCodeAt(i);\n buf[i*2] = current_value >>> 8;\n buf[i*2+1] = current_value % 256;\n }\n return buf;\n },\n\n //decompress from uint8array (UCS-2 big endian format)\n decompressFromUint8Array:function (compressed) {\n if (compressed===null || compressed===undefined){\n return LZString.decompress(compressed);\n } else {\n var buf=new Array(compressed.length/2); // 2 bytes per character\n for (var i=0, TotalLen=buf.length; i<TotalLen; i++) {\n buf[i]=compressed[i*2]*256+compressed[i*2+1];\n }\n\n var result = [];\n buf.forEach(function (c) {\n result.push(f(c));\n });\n return LZString.decompress(result.join(''));\n\n }\n\n },\n\n\n //compress into a string that is already URI encoded\n compressToEncodedURIComponent: function (input) {\n if (input == null) return \"\";\n return LZString._compress(input, 6, function(a){return keyStrUriSafe.charAt(a);});\n },\n\n //decompress from an output of compressToEncodedURIComponent\n decompressFromEncodedURIComponent:function (input) {\n if (input == null) return \"\";\n if (input == \"\") return null;\n input = input.replace(/ /g, \"+\");\n return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrUriSafe, input.charAt(index)); });\n },\n\n compress: function (uncompressed) {\n return LZString._compress(uncompressed, 16, function(a){return f(a);});\n },\n _compress: function (uncompressed, bitsPerChar, getCharFromInt) {\n if (uncompressed == null) return \"\";\n var i, value,\n context_dictionary= {},\n context_dictionaryToCreate= {},\n context_c=\"\",\n context_wc=\"\",\n context_w=\"\",\n context_enlargeIn= 2, // Compensate for the first entry which should not count\n context_dictSize= 3,\n context_numBits= 2,\n context_data=[],\n context_data_val=0,\n context_data_position=0,\n ii;\n\n for (ii = 0; ii < uncompressed.length; ii += 1) {\n context_c = uncompressed.charAt(ii);\n if (!Object.prototype.hasOwnProperty.call(context_dictionary,context_c)) {\n context_dictionary[context_c] = context_dictSize++;\n context_dictionaryToCreate[context_c] = true;\n }\n\n context_wc = context_w + context_c;\n if (Object.prototype.hasOwnProperty.call(context_dictionary,context_wc)) {\n context_w = context_wc;\n } else {\n if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {\n if (context_w.charCodeAt(0)<256) {\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<8 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n } else {\n value = 1;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | value;\n if (context_data_position ==bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = 0;\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<16 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n delete context_dictionaryToCreate[context_w];\n } else {\n value = context_dictionary[context_w];\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n // Add wc to the dictionary.\n context_dictionary[context_wc] = context_dictSize++;\n context_w = String(context_c);\n }\n }\n\n // Output the code for w.\n if (context_w !== \"\") {\n if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {\n if (context_w.charCodeAt(0)<256) {\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<8 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n } else {\n value = 1;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | value;\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = 0;\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<16 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n delete context_dictionaryToCreate[context_w];\n } else {\n value = context_dictionary[context_w];\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n }\n\n // Mark the end of the stream\n value = 2;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n // Flush the last char\n while (true) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data.push(getCharFromInt(context_data_val));\n break;\n }\n else context_data_position++;\n }\n return context_data.join('');\n },\n\n decompress: function (compressed) {\n if (compressed == null) return \"\";\n if (compressed == \"\") return null;\n return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); });\n },\n\n _decompress: function (length, resetValue, getNextValue) {\n var dictionary = [],\n next,\n enlargeIn = 4,\n dictSize = 4,\n numBits = 3,\n entry = \"\",\n result = [],\n i,\n w,\n bits, resb, maxpower, power,\n c,\n data = {val:getNextValue(0), position:resetValue, index:1};\n\n for (i = 0; i < 3; i += 1) {\n dictionary[i] = i;\n }\n\n bits = 0;\n maxpower = Math.pow(2,2);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n switch (next = bits) {\n case 0:\n bits = 0;\n maxpower = Math.pow(2,8);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n c = f(bits);\n break;\n case 1:\n bits = 0;\n maxpower = Math.pow(2,16);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n c = f(bits);\n break;\n case 2:\n return \"\";\n }\n dictionary[3] = c;\n w = c;\n result.push(c);\n while (true) {\n if (data.index > length) {\n return \"\";\n }\n\n bits = 0;\n maxpower = Math.pow(2,numBits);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n switch (c = bits) {\n case 0:\n bits = 0;\n maxpower = Math.pow(2,8);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n dictionary[dictSize++] = f(bits);\n c = dictSize-1;\n enlargeIn--;\n break;\n case 1:\n bits = 0;\n maxpower = Math.pow(2,16);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n dictionary[dictSize++] = f(bits);\n c = dictSize-1;\n enlargeIn--;\n break;\n case 2:\n return result.join('');\n }\n\n if (enlargeIn == 0) {\n enlargeIn = Math.pow(2, numBits);\n numBits++;\n }\n\n if (dictionary[c]) {\n entry = dictionary[c];\n } else {\n if (c === dictSize) {\n entry = w + w.charAt(0);\n } else {\n return null;\n }\n }\n result.push(entry);\n\n // Add w+entry[0] to the dictionary.\n dictionary[dictSize++] = w + entry.charAt(0);\n enlargeIn--;\n\n w = entry;\n\n if (enlargeIn == 0) {\n enlargeIn = Math.pow(2, numBits);\n numBits++;\n }\n\n }\n }\n};\n return LZString;\n})();\n\nif (typeof define === 'function' && define.amd) {\n define(function () { return LZString; });\n} else if( typeof module !== 'undefined' && module != null ) {\n module.exports = LZString\n} else if( typeof angular !== 'undefined' && angular != null ) {\n angular.module('LZString', [])\n .factory('LZString', function () {\n return LZString;\n });\n}\n","import { C as queueOperations, S as queueActions, _ as getAnalyticsStore, a as setDocumentCache, b as setGlobal, c as useDocumentSafe, d as useGetDocumentAsync, f as useGetDocuments, g as createAnalyticsStore, h as readPromiseState, i as addDocumentCacheEventHandler, l as useDocuments, m as addPromiseState, n as useDocumentsByIds, o as useDocument, p as DocumentCache, r as useDispatch, s as useDocumentCache, t as useDocumentById, u as useGetDocument, v as clearGlobal, w as uploadOperations, x as dispatchActions, y as getGlobal } from \"./document-by-id-dLYFX-xz.js\";\nimport { t as makePHEventFunctions } from \"./make-ph-event-functions-BHoLPif5.js\";\nimport { n as GetDocumentWithOperationsDocument, r as PropagationMode, t as createClient } from \"./client-_Gh2Uf0E.js\";\nimport { A as useLoginStatus, C as RENOWN_CHAIN_ID, D as addRenownEventHandler, E as VERIFIABLE_CREDENTIAL_EIP712_TYPE, F as setLoading, I as useLoading, M as useUser, N as addLoadingEventHandler, O as setRenown, P as loading, S as ISSUER_TYPE, T as RENOWN_URL, _ as openRenown, a as RenownAuthButton, b as CREDENTIAL_TYPES, c as ChevronDownIcon, d as RenownLogo, f as SpinnerIcon, g as logout, h as login, i as initRenownCrypto, j as useRenown, k as useDid, l as CopyIcon, m as useRenownAuth, n as useRenownInit, o as RenownUserButton, p as UserIcon, r as initConnectCrypto, s as RenownLoginButton, t as Renown, u as DisconnectIcon, v as CREDENTIAL_SCHEMA_EIP712_TYPE, w as RENOWN_NETWORK_ID, x as DOMAIN_TYPE, y as CREDENTIAL_SUBJECT_TYPE } from \"./renown-D-1c_Bvx.js\";\nimport { n as useRelationalQuery, r as useRelationalDb, t as createProcessorQuery } from \"./relational-4_LVwp8p.js\";\nimport { documentModelDocumentModelModule, logger } from \"document-model\";\nimport { baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, createPresignedHeader, createZip, documentModelDocumentType, generateId, replayDocumentVersioned, setName, validateInitialState, validateModules, validateStateSchemaName } from \"@powerhousedao/shared/document-model\";\nimport { DriveDocumentSchema, addFolder as addFolder$1, copyNode, driveCreateDocument, driveDocumentModelModule, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, setAvailableOffline, setDriveIcon, setDriveName, setSharingType, updateNode } from \"@powerhousedao/shared/document-drive\";\nimport { allPass, conditional, constant, filter, find, forEach, forEachObj, funnel, hasAtLeast, isArray, isDefined, isIncludedIn, isNot, isStrictEqual, isString, isTruthy, last, map, mapToObj, once, pipe, prop, split, unique } from \"remeda\";\nimport { ChannelScheme, DocumentChangeType, DocumentChangeType as DocumentChangeType$1, DocumentIntegrityService, DriveCollectionId, DriveCollectionId as DriveCollectionId$1, DuplicateManifestError, DuplicateModuleError, GqlRequestChannel, InMemoryQueue, IntervalPollTimer, ModuleNotFoundError, PollBehavior, PropagationMode as PropagationMode$1, REACTOR_SCHEMA, REACTOR_SCHEMA as REACTOR_SCHEMA$1, ReactorBuilder, ReactorClientBuilder, RelationalDbProcessor, SyncOperationStatus, SyncStatus, driveIdFromUrl, parseDriveUrl } from \"@powerhousedao/reactor\";\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { reactorDriveDocumentModelModule } from \"@powerhousedao/reactor-drive\";\nimport { z } from \"zod\";\nimport slug from \"slug\";\nimport normalizeException from \"normalize-exception\";\nimport * as lzString from \"lz-string\";\nimport { createAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\n//#region src/errors.ts\nvar UnsupportedDocumentTypeError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Document type ${documentType} is not supported`);\n\t\tthis.name = \"UnsupportedDocumentTypeError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UnsupportedDocumentTypeError\";\n\t}\n};\nvar DocumentModelNotFoundError = class extends Error {\n\tdocumentType;\n\tname = \"DocumentModelNotFoundError\";\n\tconstructor(documentType) {\n\t\tsuper(`Document model module for type ${documentType} not found`);\n\t\tthis.documentType = documentType;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentModelNotFoundError\";\n\t}\n};\nvar DocumentTypeMismatchError = class extends Error {\n\tconstructor(documentId, expectedType, actualType) {\n\t\tsuper(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);\n\t}\n};\nvar NoSelectedDocumentError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?\");\n\t}\n};\n//#endregion\n//#region src/utils/documents.ts\nfunction isDocumentTypeSupported(documentType, supportedDocuments) {\n\tif (!supportedDocuments?.length) return true;\n\treturn supportedDocuments.some((pattern) => {\n\t\tif (pattern.endsWith(\"/*\")) {\n\t\t\tconst prefix = pattern.slice(0, -2);\n\t\t\treturn documentType.startsWith(prefix + \"/\");\n\t\t}\n\t\tif (pattern.endsWith(\"*\") && !pattern.endsWith(\"/*\")) {\n\t\t\tconst prefix = pattern.slice(0, -1);\n\t\t\treturn documentType.startsWith(prefix);\n\t\t}\n\t\treturn pattern === documentType;\n\t});\n}\n//#endregion\n//#region src/utils/user.ts\nfunction getUserPermissions() {\n\tconst user = window.ph?.renown?.user;\n\tconst allowList = window.ph?.allowList;\n\tif (!allowList) return {\n\t\tisAllowedToCreateDocuments: true,\n\t\tisAllowedToEditDocuments: true\n\t};\n\treturn {\n\t\tisAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n\t\tisAllowedToEditDocuments: allowList.includes(user?.address ?? \"\")\n\t};\n}\n//#endregion\n//#region src/actions/document.ts\nconst BASE_STATE_KEYS = new Set([\"auth\"]);\nconst NON_DOMAIN_SCOPES = new Set([\"auth\", \"document\"]);\nasync function isDocumentInLocation(document, driveId, parentFolder) {\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) return { isDuplicate: false };\n\tlet drive;\n\ttry {\n\t\tdrive = await reactorClient.get(driveId);\n\t} catch {\n\t\treturn { isDuplicate: false };\n\t}\n\tconst nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);\n\tif (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {\n\t\tisDuplicate: true,\n\t\tduplicateType: \"id\",\n\t\tnodeId: nodeById.id\n\t};\n\tconst nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));\n\tif (nodeByNameAndType) return {\n\t\tisDuplicate: true,\n\t\tduplicateType: \"name\",\n\t\tnodeId: nodeByNameAndType.id\n\t};\n\treturn { isDuplicate: false };\n}\nfunction getDocumentTypeIcon(document) {\n\tswitch (document.header.documentType) {\n\t\tcase \"powerhouse/document-model\": return \"document-model\";\n\t\tcase \"powerhouse/app\": return \"app\";\n\t\tcase \"powerhouse/document-editor\": return \"editor\";\n\t\tcase \"powerhouse/subgraph\": return \"subgraph\";\n\t\tcase \"powerhouse/package\": return \"package\";\n\t\tcase \"powerhouse/processor\": {\n\t\t\tconst processorType = document.state.global?.type;\n\t\t\tif (processorType === \"analytics\") return \"analytics-processor\";\n\t\t\tif (processorType === \"relational\") return \"relational-processor\";\n\t\t\tif (processorType === \"codegen\") return \"codegen-processor\";\n\t\t\treturn;\n\t\t}\n\t\tdefault: return;\n\t}\n}\nasync function downloadFile(document, fileName) {\n\ttry {\n\t\tconst data = await createZip(document);\n\t\tconst blob = new Blob([new Uint8Array(data)], { type: \"application/zip\" });\n\t\tconst link = window.document.createElement(\"a\");\n\t\tlink.style.display = \"none\";\n\t\tlink.href = URL.createObjectURL(blob);\n\t\tlink.download = fileName;\n\t\twindow.document.body.appendChild(link);\n\t\tlink.click();\n\t\twindow.document.body.removeChild(link);\n\t} catch (e) {\n\t\tlogger.error(e instanceof Error ? e.message : String(e));\n\t}\n}\nasync function getDocumentExtension(document) {\n\tconst documentType = document.header.documentType;\n\tlet rawExtension;\n\tif (documentType === documentModelDocumentType) rawExtension = document.state.global?.extension;\n\telse {\n\t\tconst reactorClient = window.ph?.reactorClient;\n\t\tif (reactorClient) {\n\t\t\tconst { results: documentModelModules } = await reactorClient.getDocumentModelModules();\n\t\t\trawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;\n\t\t}\n\t}\n\treturn (rawExtension ?? \"\").replace(/^\\.+|\\.+$/g, \"\");\n}\n/**\n* Fetches all operations for a document using cursor-based pagination.\n* The reactor client handles multi-scope cursors transparently via\n* composite cursors, so all scopes are fetched in a single paginated stream.\n*/\nasync function fetchDocumentOperations(reactorClient, document, pageSize = 100) {\n\tconst scopes = Object.keys(document.state).filter((k) => !BASE_STATE_KEYS.has(k));\n\tconst operations = {};\n\tfor (const scope of scopes) operations[scope] = [];\n\tlet cursor = \"\";\n\tdo {\n\t\tconst page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {\n\t\t\tcursor,\n\t\t\tlimit: pageSize\n\t\t});\n\t\tfor (const op of page.results) {\n\t\t\tconst scope = op.action.scope ?? \"global\";\n\t\t\tif (operations[scope]) operations[scope].push(op);\n\t\t}\n\t\tcursor = page.nextCursor ?? \"\";\n\t} while (cursor);\n\treturn operations;\n}\nfunction extractInitialState(documentScopeOps) {\n\tconst upgradeOp = documentScopeOps.find((op) => op.action.type === \"UPGRADE_DOCUMENT\");\n\tif (!upgradeOp) throw new Error(\"No UPGRADE_DOCUMENT operation found — document is invalid\");\n\tconst input = upgradeOp.action.input;\n\tconst initialState = input.initialState ?? input.state;\n\tif (!initialState) throw new Error(\"UPGRADE_DOCUMENT operation has no initialState — document is invalid\");\n\treturn initialState;\n}\nfunction filterDomainOperations(operations) {\n\treturn Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));\n}\nasync function exportFile(document, suggestedName) {\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst operations = await fetchDocumentOperations(reactorClient, document);\n\tconst initialState = extractInitialState(operations[\"document\"] ?? []);\n\tconst documentWithOps = {\n\t\t...document,\n\t\toperations,\n\t\tinitialState\n\t};\n\tconst extension = await getDocumentExtension(documentWithOps);\n\tconst baseName = suggestedName || documentWithOps.header.name || \"Untitled\";\n\tconst name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;\n\tif (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);\n\ttry {\n\t\tconst fileHandle = await window.showSaveFilePicker({ suggestedName: name });\n\t\tawait baseSaveToFileHandle(documentWithOps, fileHandle);\n\t\treturn fileHandle;\n\t} catch (e) {\n\t\tif (!(e instanceof DOMException && e.name === \"AbortError\")) throw e;\n\t}\n}\n/**\n* Loads a document file and replays it with version-aware reducers from the registry.\n* Falls back to single-version legacy replay when no upgrade manifest is registered for\n* the document type.\n*/\nasync function loadFile(path) {\n\tconst baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst documentType = baseDocument.header.documentType;\n\tconst { results: documentModelModules } = await reactorClient.getDocumentModelModules();\n\tconst modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);\n\tif (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);\n\tconst reducers = {};\n\tfor (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tlet upgradeManifest;\n\tif (registry) try {\n\t\tupgradeManifest = registry.getUpgradeManifest(documentType);\n\t} catch {}\n\treturn baseLoadFromInputVersioned(path, {\n\t\treducers,\n\t\tupgradeManifest\n\t});\n}\nasync function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst documentModelModule = await reactorClient.getDocumentModelModule(documentType);\n\tconst newDocument = document ?? documentModelModule.utils.createDocument();\n\tnewDocument.header.name = name;\n\tif (preferredEditor) newDocument.header.meta = {\n\t\t...newDocument.header.meta,\n\t\tpreferredEditor\n\t};\n\tlet newDoc;\n\ttry {\n\t\tnewDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);\n\t} catch (e) {\n\t\tlogger.error(\"Error adding document: @error\", e);\n\t\tthrow new Error(\"There was an error adding document\", { cause: e });\n\t}\n\treturn {\n\t\tid: newDoc.header.id,\n\t\tname: newDoc.header.name,\n\t\tdocumentType,\n\t\tparentFolder: parentFolder ?? null,\n\t\tkind: \"file\"\n\t};\n}\nasync function addFile(file, driveId, name, parentFolder) {\n\tlogger.verbose(`addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create files\");\n\tconst document = await loadFile(file);\n\tlet duplicateId = false;\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\ttry {\n\t\tawait reactorClient.get(document.header.id);\n\t\tduplicateId = true;\n\t} catch {}\n\tconst documentId = duplicateId ? generateId() : document.header.id;\n\tconst header = createPresignedHeader(documentId, document.header.documentType);\n\theader.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n\theader.meta = document.header.meta;\n\theader.name = name || document.header.name;\n\tconst initialDocument = {\n\t\t...document,\n\t\theader,\n\t\tstate: document.initialState,\n\t\toperations: Object.keys(document.operations).reduce((acc, key) => {\n\t\t\tacc[key] = [];\n\t\t\treturn acc;\n\t\t}, {})\n\t};\n\tawait addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);\n\tawait uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations);\n}\nasync function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {\n\tlogger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);\n\tconst reactor = window.ph?.reactorClient;\n\tif (!reactor) return;\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create files\");\n\ttry {\n\t\tonProgress?.({\n\t\t\tstage: \"loading\",\n\t\t\tprogress: 0\n\t\t});\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await loadFile(file);\n\t\t} catch (loadError) {\n\t\t\tconst discoveryService = window.ph?.packageDiscoveryService;\n\t\t\tif (discoveryService && DocumentModelNotFoundError.isError(loadError)) {\n\t\t\t\tretryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow loadError;\n\t\t}\n\t\tconst duplicateCheck = await isDocumentInLocation(document, driveId, parentFolder);\n\t\tif (duplicateCheck.isDuplicate && !resolveConflict) {\n\t\t\tonProgress?.({\n\t\t\t\tstage: \"conflict\",\n\t\t\t\tprogress: 0,\n\t\t\t\tduplicateType: duplicateCheck.duplicateType\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst documentType = getDocumentTypeIcon(document);\n\t\tif (documentType) onProgress?.({\n\t\t\tstage: \"loading\",\n\t\t\tprogress: 10,\n\t\t\tdocumentType\n\t\t});\n\t\telse onProgress?.({\n\t\t\tstage: \"loading\",\n\t\t\tprogress: 10\n\t\t});\n\t\tif (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {\n\t\t\tonProgress?.({\n\t\t\t\tstage: \"unsupported-document-type\",\n\t\t\t\tprogress: 100,\n\t\t\t\terror: `Document type ${document.header.documentType} is not supported`\n\t\t\t});\n\t\t\tthrow new UnsupportedDocumentTypeError(document.header.documentType);\n\t\t}\n\t\tawait reactor.getDocumentModelModule(document.header.documentType);\n\t\tonProgress?.({\n\t\t\tstage: \"initializing\",\n\t\t\tprogress: 10\n\t\t});\n\t\tlet duplicateId = false;\n\t\ttry {\n\t\t\tawait reactor.get(document.header.id);\n\t\t\tduplicateId = true;\n\t\t} catch {}\n\t\tconst documentId = duplicateId ? generateId() : document.header.id;\n\t\tconst header = createPresignedHeader(documentId, document.header.documentType);\n\t\theader.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n\t\theader.meta = document.header.meta;\n\t\theader.name = name || document.header.name;\n\t\tconst initialDocument = {\n\t\t\t...document,\n\t\t\theader,\n\t\t\tstate: document.initialState,\n\t\t\toperations: Object.keys(document.operations).reduce((acc, key) => {\n\t\t\t\tacc[key] = [];\n\t\t\t\treturn acc;\n\t\t\t}, {})\n\t\t};\n\t\tconst fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);\n\t\tif (!fileNode) throw new Error(\"There was an error adding file\");\n\t\tonProgress?.({\n\t\t\tstage: \"initializing\",\n\t\t\tprogress: 20\n\t\t});\n\t\tawait reactor.get(documentId);\n\t\tconsole.log(\"Document created, starting upload of operations\");\n\t\tawait uploadOperations(documentId, filterDomainOperations(document.operations), queueOperations, { onProgress: (uploadProgress) => {\n\t\t\tif (uploadProgress.totalOperations && uploadProgress.uploadedOperations !== void 0) {\n\t\t\t\tconst uploadPercent = uploadProgress.totalOperations > 0 ? uploadProgress.uploadedOperations / uploadProgress.totalOperations : 0;\n\t\t\t\tconst overallProgress = 20 + Math.round(uploadPercent * 80);\n\t\t\t\tonProgress?.({\n\t\t\t\t\tstage: \"uploading\",\n\t\t\t\t\tprogress: overallProgress,\n\t\t\t\t\ttotalOperations: uploadProgress.totalOperations,\n\t\t\t\t\tuploadedOperations: uploadProgress.uploadedOperations\n\t\t\t\t});\n\t\t\t}\n\t\t} });\n\t\tonProgress?.({\n\t\t\tstage: \"complete\",\n\t\t\tprogress: 100,\n\t\t\tfileNode\n\t\t});\n\t\treturn fileNode;\n\t} catch (error) {\n\t\tif (!UnsupportedDocumentTypeError.isError(error)) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tonProgress?.({\n\t\t\t\tstage: \"failed\",\n\t\t\t\tprogress: 100,\n\t\t\t\terror: errorMessage\n\t\t\t});\n\t\t}\n\t\tthrow error;\n\t}\n}\nasync function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {\n\tif (!discoveryService) return;\n\ttry {\n\t\tawait discoveryService.load(documentType);\n\t} catch {\n\t\tonProgress?.({\n\t\t\tstage: \"unsupported-document-type\",\n\t\t\tprogress: 100,\n\t\t\terror: `Document type ${documentType} is not supported`\n\t\t});\n\t\treturn;\n\t}\n\tawait addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);\n}\nasync function addFolder(driveId, name, parentFolder) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create folders\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tawait reactorClient.get(driveId);\n\tconst folderId = generateId();\n\tconst node = (await reactorClient.execute(driveId, \"main\", [addFolder$1({\n\t\tid: folderId,\n\t\tname,\n\t\tparentFolder\n\t})])).state.global.nodes.find((node) => node.id === folderId);\n\tif (!node || !isFolderNode(node)) throw new Error(\"There was an error adding folder\");\n\treturn node;\n}\nasync function deleteNode(driveId, nodeId) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to delete documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tawait reactorClient.drives.removeNode(driveId, nodeId);\n}\nasync function renameNode(driveId, nodeId, name) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to rename documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tif ((await reactorClient.execute(nodeId, \"main\", [setName({ name })])).header.name !== name) throw new Error(\"There was an error renaming the node\");\n\tconst node = (await reactorClient.execute(driveId, \"main\", [updateNode({\n\t\tid: nodeId,\n\t\tname\n\t})])).state.global.nodes.find((n) => n.id === nodeId);\n\tif (!node) throw new Error(\"There was an error renaming node in the drive\");\n\treturn node;\n}\nasync function renameDriveNode(driveId, nodeId, name) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to rename documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tif ((await reactorClient.execute(nodeId, \"main\", [setName({ name })])).header.name !== name) throw new Error(\"There was an error renaming the node\");\n\tawait reactorClient.execute(driveId, \"main\", [updateNode({\n\t\tid: nodeId,\n\t\tname\n\t})]);\n\treturn (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);\n}\nasync function moveNodeById(args) {\n\tconst { driveId, srcId, targetId } = args;\n\tif (!driveId || !srcId) return;\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to move documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst targetParentFolder = conditional(targetId, [isNot(isDefined), constant(void 0)], [isStrictEqual(driveId), constant(void 0)], constant(targetId));\n\tif (isStrictEqual(targetParentFolder, srcId)) return;\n\treturn await reactorClient.execute(driveId, \"main\", [moveNode({\n\t\tsrcFolder: srcId,\n\t\ttargetParentFolder\n\t})]);\n}\nasync function moveNode$1(driveId, src, target) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to move documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(driveId, \"main\", [moveNode({\n\t\tsrcFolder: src.id,\n\t\ttargetParentFolder: target?.id\n\t})]);\n}\n/**\n* Duplicates a document under a new id using version-aware replay.\n* Falls back gracefully when no upgrade manifest is registered for the document type.\n*/\nasync function _duplicateDocument(reactor, document, newId = generateId()) {\n\tconst documentType = document.header.documentType;\n\tconst { results: allModules } = await reactor.getDocumentModelModules();\n\tconst modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);\n\tconst reducers = {};\n\tfor (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;\n\tif (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tlet upgradeManifest;\n\tif (registry) try {\n\t\tupgradeManifest = registry.getUpgradeManifest(documentType);\n\t} catch {}\n\tconst config = {\n\t\treducers,\n\t\tupgradeManifest\n\t};\n\tconst header = createPresignedHeader(newId, documentType);\n\treturn replayDocumentVersioned(document.initialState, document.operations, config, header);\n}\nasync function copyNode$1(driveId, src, target) {\n\tconst reactor = window.ph?.reactorClient;\n\tif (!reactor) return;\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to copy documents\");\n\tconst drive = await reactor.get(driveId);\n\tconst copyNodesInput = generateNodesCopy({\n\t\tsrcId: src.id,\n\t\ttargetParentFolder: target?.id,\n\t\ttargetName: src.name\n\t}, () => generateId(), drive.state.global.nodes);\n\tconst resolvedNamesMap = /* @__PURE__ */ new Map();\n\tfor (const copyNodeInput of copyNodesInput) {\n\t\tconst node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);\n\t\tif (node) {\n\t\t\tconst resolvedName = handleTargetNameCollisions({\n\t\t\t\tnodes: drive.state.global.nodes,\n\t\t\t\tsrcName: copyNodeInput.targetName || node.name,\n\t\t\t\tsrcKind: isFileNode(node) ? \"file\" : \"folder\",\n\t\t\t\ttargetParentFolder: copyNodeInput.targetParentFolder || null\n\t\t\t});\n\t\t\tresolvedNamesMap.set(copyNodeInput.targetId, resolvedName);\n\t\t}\n\t}\n\tconst fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {\n\t\tconst node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);\n\t\treturn node !== void 0 && isFileNode(node);\n\t});\n\tfor (const fileNodeToCopy of fileNodesToCopy) try {\n\t\tconst duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);\n\t\tconst resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);\n\t\tif (resolvedName) duplicatedDocument.header.name = resolvedName;\n\t\tawait reactor.drives.addFile(driveId, duplicatedDocument, target?.id);\n\t} catch (e) {\n\t\tlogger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);\n\t}\n\treturn await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));\n}\n//#endregion\n//#region src/hooks/modals.ts\nconst modalEventFunctions = makePHEventFunctions(\"modal\");\n/** Returns the current modal */\nconst usePHModal = modalEventFunctions.useValue;\n/** Sets the current modal */\nconst setPHModal = modalEventFunctions.setValue;\n/** Adds an event handler for the modal */\nconst addModalEventHandler = modalEventFunctions.addEventHandler;\n/** Shows a modal */\nfunction showPHModal(modal) {\n\tsetPHModal(modal);\n}\n/** Closes the current modal */\nfunction closePHModal() {\n\tsetPHModal(void 0);\n}\n/** Shows the create document modal */\nfunction showCreateDocumentModal(documentType) {\n\tsetPHModal({\n\t\ttype: \"createDocument\",\n\t\tdocumentType\n\t});\n}\n/** Shows the delete node modal */\nfunction showDeleteNodeModal(nodeOrId) {\n\tsetPHModal({\n\t\ttype: \"deleteItem\",\n\t\tid: typeof nodeOrId === \"string\" ? nodeOrId : nodeOrId.id\n\t});\n}\n//#endregion\n//#region src/actions/drive.ts\nconst DEFAULT_INITIAL_SYNC_TIMEOUT_MS = 3e4;\n/**\n* A drive add failed because the switchboard rejected the (anonymous or\n* unverified) caller — Forbidden/Unauthorized — rather than a transient\n* reachability error. Drives the login prompt.\n*/\nfunction isDriveAuthError(error) {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /forbidden|unauthorized|insufficient permissions|\\b401\\b|\\b403\\b/i.test(message);\n}\nconst inFlightRemoteRegistrations = /* @__PURE__ */ new Map();\n/**\n* Resolves once a document with the given id is queryable through the\n* reactor client. Subscribes to Created events filtered by id and\n* short-circuits if the document already exists.\n*/\nasync function waitForDocumentReady(reactorClient, documentId, options) {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_INITIAL_SYNC_TIMEOUT_MS;\n\tconst signal = options?.signal;\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet unsubscribe;\n\t\tlet timer;\n\t\tlet abortHandler;\n\t\tconst settle = (action) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tunsubscribe?.();\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n\t\t\taction();\n\t\t};\n\t\tunsubscribe = reactorClient.subscribe({ ids: [documentId] }, (event) => {\n\t\t\tif (event.type === DocumentChangeType$1.Created) settle(() => resolve());\n\t\t});\n\t\treactorClient.find({ ids: [documentId] }).then((existing) => {\n\t\t\tif (existing.results.length > 0) settle(() => resolve());\n\t\t}).catch(() => {});\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tsettle(() => reject(new DOMException(\"Aborted\", \"AbortError\")));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tabortHandler = () => {\n\t\t\t\tsettle(() => reject(new DOMException(\"Aborted\", \"AbortError\")));\n\t\t\t};\n\t\t\tsignal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\t\ttimer = setTimeout(() => {\n\t\t\tsettle(() => reject(/* @__PURE__ */ new Error(`Timed out after ${timeoutMs}ms waiting for document ${documentId}`)));\n\t\t}, timeoutMs);\n\t});\n}\nasync function addDrive(input, preferredEditor) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create drives\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst driveDoc = driveCreateDocument({ global: {\n\t\tname: input.global.name || \"\",\n\t\ticon: input.global.icon ?? null,\n\t\tnodes: []\n\t} });\n\tif (preferredEditor) driveDoc.header.meta = { preferredEditor };\n\treturn await reactorClient.create(driveDoc);\n}\nasync function addRemoteDrive(url, driveId, options) {\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n\tif (!sync) throw new Error(\"Sync not initialized\");\n\tconst response = await fetch(url);\n\tif (!response.ok) throw new Error(`Failed to resolve drive info from ${url}`);\n\tconst driveInfo = await response.json();\n\tconst resolvedDriveId = driveId ?? driveInfo.id;\n\tconst collectionId = DriveCollectionId$1.forDrive(resolvedDriveId);\n\tconst inFlight = inFlightRemoteRegistrations.get(collectionId.key);\n\ttry {\n\t\tif (inFlight) await inFlight;\n\t\telse if (!sync.list().find((remote) => remote.collectionId.equals(collectionId))) {\n\t\t\tconst remoteName = crypto.randomUUID();\n\t\t\tconst registration = sync.add(remoteName, collectionId, {\n\t\t\t\ttype: \"gql\",\n\t\t\t\tparameters: { url: driveInfo.graphqlEndpoint }\n\t\t\t}, void 0, options?.pollBehavior ? { pollBehavior: options.pollBehavior } : void 0).finally(() => inFlightRemoteRegistrations.delete(collectionId.key));\n\t\t\tinFlightRemoteRegistrations.set(collectionId.key, registration);\n\t\t\tawait registration;\n\t\t}\n\t} catch (error) {\n\t\tif (isDriveAuthError(error)) showPHModal({ type: \"driveAuthRequired\" });\n\t\tthrow error;\n\t}\n\tif (options?.awaitInitialSync) await waitForDocumentReady(reactorClient, resolvedDriveId, {\n\t\ttimeoutMs: options.initialSyncTimeoutMs,\n\t\tsignal: options.signal\n\t});\n\treturn resolvedDriveId;\n}\nasync function deleteDrive(driveId) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to delete drives\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n\tif (sync) {\n\t\tconst collectionId = DriveCollectionId$1.forDrive(driveId);\n\t\tconst remotes = sync.list().filter((remote) => remote.collectionId.equals(collectionId));\n\t\tfor (const remote of remotes) await sync.remove(remote.name);\n\t}\n\tawait reactorClient.deleteDocument(driveId, PropagationMode$1.Cascade);\n}\nasync function renameDrive(driveId, name) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to rename drives\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.rename(driveId, name);\n}\nasync function setDriveAvailableOffline(driveId, availableOffline) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to change drive availability\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(driveId, \"main\", [setAvailableOffline({ availableOffline })]);\n}\nasync function setDriveSharingType(driveId, sharingType) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to change drive sharing type\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(driveId, \"main\", [setSharingType({ type: sharingType })]);\n}\nasync function setDriveMetadata(driveId, metadata) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to update drive metadata\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst actions = [];\n\tif (metadata.name) actions.push(setDriveName({ name: metadata.name }));\n\tif (metadata.icon !== void 0 && metadata.icon !== null) actions.push(setDriveIcon({ icon: metadata.icon }));\n\tif (actions.length === 0) return;\n\treturn await reactorClient.execute(driveId, \"main\", actions);\n}\n//#endregion\n//#region src/constants.ts\nconst DEFAULT_DRIVE_EDITOR_ID = \"powerhouse/generic-drive-explorer\";\nconst COMMON_PACKAGE_ID = \"powerhouse/common\";\n//#endregion\n//#region src/document-model.ts\nconst baseDocumentModelsMap = {\n\tDocumentModel: documentModelDocumentModelModule,\n\tDocumentDrive: driveDocumentModelModule,\n\tReactorDrive: reactorDriveDocumentModelModule\n};\nconst baseDocumentModels = Object.values(baseDocumentModelsMap);\n//#endregion\n//#region src/graphql/adapters.ts\nfunction phDocumentFromQuery(document, documentSchema) {\n\tconst phDocument = {\n\t\theader: phDocumentHeaderFromQuery(document),\n\t\tstate: phDocumentStateFromQuery(document),\n\t\tinitialState: phDocumentStateFromQuery(document),\n\t\toperations: phDocumentOperationsFromGetDocumentWithOperationsQuery(document),\n\t\tclipboard: []\n\t};\n\tif (documentSchema !== void 0) documentSchema.parse(phDocument);\n\treturn phDocument;\n}\nfunction phDocumentsFromQuery(items, documentSchema) {\n\treturn pipe(items, map((document) => phDocumentFromQuery(document, documentSchema)));\n}\nfunction phDocumentHeaderFromQuery(queryDocument) {\n\treturn {\n\t\tbranch: \"main\",\n\t\tid: queryDocument.id,\n\t\tname: queryDocument.name,\n\t\tdocumentType: queryDocument.documentType,\n\t\tcreatedAtUtcIso: queryDocument.createdAtUtcIso instanceof Date ? queryDocument.createdAtUtcIso.toUTCString() : queryDocument.createdAtUtcIso,\n\t\tlastModifiedAtUtcIso: queryDocument.lastModifiedAtUtcIso instanceof Date ? queryDocument.lastModifiedAtUtcIso.toUTCString() : queryDocument.lastModifiedAtUtcIso,\n\t\tslug: queryDocument.slug ?? \"\"\n\t};\n}\nfunction phDocumentStateFromQuery(queryDocument, documentSchema) {\n\tif (documentSchema !== void 0) return documentSchema.shape.state.parse(queryDocument.state);\n\treturn queryDocument.state;\n}\nfunction phDocumentOperationsFromGetDocumentWithOperationsQuery(queryDocument) {\n\tif (queryDocument.operations === null || queryDocument.operations === void 0) return { global: [] };\n\treturn { global: [...queryDocument.operations.items] };\n}\nfunction identifierFromMutateDocumentOperationVariables(variables) {\n\treturn z.object({ documentIdentifier: z.string() }).parse(variables).documentIdentifier;\n}\n//#endregion\n//#region src/graphql/constants.ts\nconst DEFAULT_DRIVE_ID = \"powerhouse\";\nconst DEFAULT_SWITCHBOARD_URL = \"http://localhost:4001/graphql\";\nconst graphqlEventsToSyncDrive = [\n\t\"CreateEmptyDocument\",\n\t\"CreateDocument\",\n\t\"AddChildren\",\n\t\"RemoveChildren\",\n\t\"MoveChildren\",\n\t\"DeleteDocument\",\n\t\"DeleteDocuments\"\n];\nconst graphqlDocumentEvents = [\n\t\"MutateDocument\",\n\t\"MutateDocumentAsync\",\n\t\"DeleteDocument\"\n];\nconst graphqlDocumentsEvents = [\"DeleteDocuments\"];\n//#endregion\n//#region src/graphql/fetchers.ts\nasync function reactorGraphqlFetchDocument(identifier, documentSchema) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\ttry {\n\t\tconst document = (await client.GetDocument({ identifier })).document?.document;\n\t\tif (!document) return void 0;\n\t\treturn phDocumentFromQuery(document, documentSchema);\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function reactorGraphqlBatchFetchDocuments(identifiers) {\n\tif (!window.ph?.reactorGraphQLClient) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\tconst promises = map(identifiers, (identifier) => reactorGraphqlFetchDocument(identifier));\n\treturn await Promise.all(promises);\n}\n//#endregion\n//#region src/graphql/batch.ts\n/**\n* A reference implementation for an async batching utility function built on\n* top of the `funnel` general purpose execution utility function. It will\n* accumulate all params passed to an async `call` method within the defined\n* burst duration and then use an async executor to process them in one\n* invocation. It then extracts an individual result for each call which is\n* used to resolve the original call.\n*\n* This allows synchronizing multiple async calls while keeping each call site\n* isolated from the rest (for example, as react components).\n*\n* This reference implementation can be copied into your project as-is, or you\n* can use it as the basis for a more complex implementation with additional\n* features.\n*\n* @param callback - The main function that takes a batch and returns an\n* aggregated response. The typing for the it's parameters will derive the\n* typing for the extractor and the `call` method.\n* @param extractor - A function that takes the aggregated response and extracts\n* from it the result for each individual call. The function is called with both\n* the index in the batch, and the params passed to the `call` method. This\n* allows handling APIs that return batch results as both objects and arrays.\n* @param maxBurstDurationMs - The period of time where the batcher would\n* collect params before triggering the executor. When set to 0 the batcher\n* does not incur any additional delays to the execution and would trigger at\n* the next tick, just like a regular async function would. This is also the\n* default value.\n* @returns A Funnel object with the `call` method augmented to support async\n* response.\n*/\nfunction batch(callback, extractor, maxBurstDurationMs = 0) {\n\tconst batchFunnel = funnel((requests) => {\n\t\tcallback(requests.map(({ params }) => params)).then((response) => {\n\t\t\tfor (const [index, { params, promiseCallbacks: [resolve, reject] }] of requests.entries()) try {\n\t\t\t\tresolve(extractor(response, index, ...params));\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tfor (const { promiseCallbacks: [, reject] } of requests) reject(error);\n\t\t});\n\t}, {\n\t\treducer: (requests, request) => [...requests ?? [], request],\n\t\tmaxBurstDurationMs,\n\t\ttriggerAt: \"end\"\n\t});\n\treturn {\n\t\t...batchFunnel,\n\t\tcall: (...params) => new Promise((...promiseCallbacks) => {\n\t\t\tbatchFunnel.call({\n\t\t\t\tpromiseCallbacks,\n\t\t\t\tparams\n\t\t\t});\n\t\t})\n\t};\n}\n//#endregion\n//#region src/graphql/document-fetcher.ts\nfunction makeDocumentsById(documents = []) {\n\treturn pipe(documents, filter(isTruthy), mapToObj((document) => [document.header.id, document]));\n}\nvar DocumentFetcher = class {\n\tbatchGetDocuments;\n\tconstructor() {\n\t\tthis.batchGetDocuments = batch(async (requests) => {\n\t\t\treturn makeDocumentsById(await reactorGraphqlBatchFetchDocuments(unique(map(requests, ([id]) => id))));\n\t\t}, (documentsById, _, id) => {\n\t\t\treturn prop(documentsById, id);\n\t\t});\n\t}\n\tget(id) {\n\t\treturn this.batchGetDocuments.call(id);\n\t}\n\tgetBatch(ids) {\n\t\treturn Promise.all(map(ids, (id) => this.get(id)));\n\t}\n};\n//#endregion\n//#region src/graphql/graphql-client-document-cache.ts\nvar GraphQLClientDocumentCache = class {\n\tfetcher;\n\tdocuments = /* @__PURE__ */ new Map();\n\tbatchPromises = /* @__PURE__ */ new Map();\n\tlisteners = /* @__PURE__ */ new Map();\n\tconstructor() {\n\t\tthis.fetcher = new DocumentFetcher();\n\t\twindow.addEventListener(\"MutateDocument\", (event) => {\n\t\t\tthis.handleDocumentMutated(event.detail.identifier).catch(console.error);\n\t\t});\n\t\twindow.addEventListener(\"MutateDocumentAsync\", (event) => {\n\t\t\tthis.handleDocumentMutated(event.detail.identifier).catch(console.error);\n\t\t});\n\t}\n\tget(id, refetch) {\n\t\tconst current = this.documents.get(id);\n\t\tif (current) {\n\t\t\tif (current.status === \"pending\") return current;\n\t\t\tif (!refetch) return current;\n\t\t}\n\t\tconst promise = addPromiseState(this.fetcher.get(id).then((document) => {\n\t\t\tthis.invalidateBatchesContaining(id);\n\t\t\treturn document;\n\t\t}));\n\t\tthis.documents.set(id, promise);\n\t\treturn promise;\n\t}\n\tgetBatch(ids) {\n\t\tconst key = ids.join(\",\");\n\t\tconst cached = this.batchPromises.get(key);\n\t\tconst currentPromises = ids.map((id) => this.get(id));\n\t\tif (cached) {\n\t\t\tif (currentPromises.every((promise, index) => promise === cached.promises[index])) return cached.promise;\n\t\t}\n\t\tconst states = currentPromises.map((promise) => readPromiseState(promise));\n\t\tif (states.every((state) => state.status !== \"pending\")) {\n\t\t\tconst values = states.filter((state) => state.status === \"fulfilled\").map((state) => state.value);\n\t\t\tconst batchPromise = Promise.resolve(values);\n\t\t\tbatchPromise.status = \"fulfilled\";\n\t\t\tbatchPromise.value = values;\n\t\t\tthis.batchPromises.set(key, {\n\t\t\t\tpromises: currentPromises,\n\t\t\t\tpromise: batchPromise\n\t\t\t});\n\t\t\treturn batchPromise;\n\t\t}\n\t\tconst batchPromise = addPromiseState(Promise.allSettled(currentPromises).then((results) => {\n\t\t\tconst documents = [];\n\t\t\tfor (const result of results) if (result.status === \"fulfilled\") documents.push(result.value);\n\t\t\telse console.warn(\"[GraphQLClientDocumentCache] Skipped unavailable document:\", result.reason);\n\t\t\treturn documents;\n\t\t}));\n\t\tthis.batchPromises.set(key, {\n\t\t\tpromises: currentPromises,\n\t\t\tpromise: batchPromise\n\t\t});\n\t\treturn batchPromise;\n\t}\n\tinvalidateBatchesContaining(documentId) {\n\t\tfor (const key of this.batchPromises.keys()) if (key.split(\",\").includes(documentId)) this.batchPromises.delete(key);\n\t}\n\tsubscribe(id, callback) {\n\t\tconst ids = Array.isArray(id) ? id : [id];\n\t\tfor (const documentId of ids) {\n\t\t\tconst listeners = this.listeners.get(documentId) ?? [];\n\t\t\tthis.listeners.set(documentId, [...listeners, callback]);\n\t\t}\n\t\treturn () => {\n\t\t\tfor (const documentId of ids) {\n\t\t\t\tconst listeners = this.listeners.get(documentId) ?? [];\n\t\t\t\tthis.listeners.set(documentId, listeners.filter((listener) => listener !== callback));\n\t\t\t}\n\t\t};\n\t}\n\tnotify(id) {\n\t\tconst listeners = this.listeners.get(id) ?? [];\n\t\tfor (const listener of listeners) listener();\n\t}\n\tasync handleDocumentMutated(id) {\n\t\tthis.invalidateBatchesContaining(id);\n\t\tawait this.get(id);\n\t\tthis.notify(id);\n\t}\n\thandleDocumentDeleted(id) {\n\t\tthis.documents.delete(id);\n\t\tthis.invalidateBatchesContaining(id);\n\t\tthis.notify(id);\n\t}\n\thandleDocumentsDeleted(ids) {\n\t\tforEach(ids, (id) => this.handleDocumentDeleted(id));\n\t}\n};\n//#endregion\n//#region src/graphql/mutators.ts\nasync function reactorGraphqlCreateDocument(document, parentIdentifier = DEFAULT_DRIVE_ID) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.CreateDocument({\n\t\tdocument,\n\t\tparentIdentifier\n\t});\n}\nasync function reactorGraphqlDeleteDocument(identifier) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.DeleteDocument({ identifier });\n}\nasync function reactorGraphqlDeleteDocuments(identifiers) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.DeleteDocuments({ identifiers });\n}\nasync function reactorGraphqlMutateDocument(documentIdentifier, ...actions) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.MutateDocument({\n\t\tdocumentIdentifier,\n\t\tactions\n\t});\n}\n//#endregion\n//#region src/hooks/config/editor.ts\nconst isExternalControlsEnabledEventFunctions = makePHEventFunctions(\"isExternalControlsEnabled\");\n/** Sets whether external controls are enabled for a given editor. */\nconst setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;\n/** Gets whether external controls are enabled for a given editor. */\nconst useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;\n/** Adds an event handler for when the external controls enabled state changes. */\nconst addIsExternalControlsEnabledEventHandler = isExternalControlsEnabledEventFunctions.addEventHandler;\nconst isDragAndDropEnabledEventFunctions = makePHEventFunctions(\"isDragAndDropEnabled\");\n/** Sets whether drag and drop is enabled for a given app. */\nconst setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;\n/** Gets whether drag and drop is enabled for a given app. */\nconst useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;\n/** Adds an event handler for when the drag and drop enabled state changes. */\nconst addIsDragAndDropEnabledEventHandler = isDragAndDropEnabledEventFunctions.addEventHandler;\nconst allowedDocumentTypesEventFunctions = makePHEventFunctions(\"allowedDocumentTypes\");\n/** Sets the allowed document types for a given app. */\nconst setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;\n/** Defines the document types a drive supports.\n*\n* Defaults to all of the document types registered in the reactor.\n*/\nfunction useAllowedDocumentTypes() {\n\treturn allowedDocumentTypesEventFunctions.useValue();\n}\n/** Adds an event handler for when the allowed document types for a given app changes. */\nconst addAllowedDocumentTypesEventHandler = allowedDocumentTypesEventFunctions.addEventHandler;\nconst phAppConfigSetters = {\n\tallowedDocumentTypes: setAllowedDocumentTypes,\n\tisDragAndDropEnabled: setIsDragAndDropEnabled\n};\nconst phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };\nconst phAppConfigHooks = {\n\tallowedDocumentTypes: useAllowedDocumentTypes,\n\tisDragAndDropEnabled: useIsDragAndDropEnabled\n};\nconst phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };\n//#endregion\n//#region src/hooks/config/connect.ts\nconst { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions(\"routerBasename\");\nconst { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions(\"version\");\nconst { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions(\"requiresHardRefresh\");\nconst { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions(\"warnOutdatedApp\");\nconst { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions(\"studioMode\");\nconst { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions(\"basePath\");\nconst { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions(\"versionCheckInterval\");\nconst { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions(\"cliVersion\");\nconst { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions(\"fileUploadOperationsChunkSize\");\nconst { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions(\"isDocumentModelSelectionSettingsEnabled\");\nconst { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions(\"gaTrackingId\");\nconst { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions(\"defaultDrivesUrl\");\nconst { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions(\"drivesPreserveStrategy\");\nconst { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isLocalDrivesEnabled\");\nconst { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions(\"isAddDriveEnabled\");\nconst { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions(\"isPublicDrivesEnabled\");\nconst { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions(\"isAddPublicDrivesEnabled\");\nconst { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions(\"isDeletePublicDrivesEnabled\");\nconst { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions(\"isCloudDrivesEnabled\");\nconst { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions(\"isAddCloudDrivesEnabled\");\nconst { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions(\"isDeleteCloudDrivesEnabled\");\nconst { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isLocalDrivesEnabled\");\nconst { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isAddLocalDrivesEnabled\");\nconst { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isDeleteLocalDrivesEnabled\");\nconst { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions(\"isEditorDebugModeEnabled\");\nconst { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions(\"isEditorReadModeEnabled\");\nconst { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions(\"isAnalyticsDatabaseWorkerEnabled\");\nconst { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions(\"isDiffAnalyticsEnabled\");\nconst { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions(\"isDriveAnalyticsEnabled\");\nconst { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions(\"renownUrl\");\nconst { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions(\"renownNetworkId\");\nconst { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions(\"renownChainId\");\nconst { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions(\"sentryRelease\");\nconst { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions(\"sentryDsn\");\nconst { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions(\"sentryEnv\");\nconst { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions(\"isSentryTracingEnabled\");\nconst { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions(\"isExternalProcessorsEnabled\");\nconst { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions(\"isExternalPackagesEnabled\");\nconst enabledEditorsEventFunctions = makePHEventFunctions(\"enabledEditors\");\n/** Sets the enabled editors for Connect. */\nconst setEnabledEditors = enabledEditorsEventFunctions.setValue;\n/** Gets the enabled editors for Connect. */\nconst useEnabledEditors = enabledEditorsEventFunctions.useValue;\n/** Adds an event handler for when the enabled editors for Connect changes. */\nconst addEnabledEditorsEventHandler = enabledEditorsEventFunctions.addEventHandler;\nconst disabledEditorsEventFunctions = makePHEventFunctions(\"disabledEditors\");\n/** Sets the disabled editors for Connect. */\nconst setDisabledEditors = disabledEditorsEventFunctions.setValue;\n/** Gets the disabled editors for Connect. */\nconst useDisabledEditors = disabledEditorsEventFunctions.useValue;\n/** Adds an event handler for when the disabled editors for Connect changes. */\nconst addDisabledEditorsEventHandler = disabledEditorsEventFunctions.addEventHandler;\nconst isRelationalProcessorsEnabled = makePHEventFunctions(\"isRelationalProcessorsEnabled\");\n/** Sets the isRelationalProcessorsEnabled for Connect. */\nconst setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;\n/** Gets the isRelationalProcessorsEnabled for Connect. */\nconst useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;\n/** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */\nconst addIsRelationalProcessorsEnabledEventHandler = isRelationalProcessorsEnabled.addEventHandler;\nconst isExternalRelationalProcessorsEnabled = makePHEventFunctions(\"isExternalRelationalProcessorsEnabled\");\n/** Sets the isExternalRelationalProcessorsEnabled for Connect. */\nconst setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;\n/** Gets the isExternalRelationalProcessorsEnabled for Connect. */\nconst useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;\n/** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */\nconst addIsExternalRelationalProcessorsEnabledEventHandler = isExternalRelationalProcessorsEnabled.addEventHandler;\nconst isAnalyticsEnabledEventFunctions = makePHEventFunctions(\"isAnalyticsEnabled\");\n/** Sets the isAnalyticsEnabled for Connect. */\nconst setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;\n/** Gets the isAnalyticsEnabled for Connect. */\nconst useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;\n/** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */\nconst addIsAnalyticsEnabledEventHandler = isAnalyticsEnabledEventFunctions.addEventHandler;\nconst isAnalyticsExternalProcessorsEnabled = makePHEventFunctions(\"isAnalyticsExternalProcessorsEnabled\");\n/** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */\nconst setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;\n/** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */\nconst useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;\n/** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */\nconst addIsAnalyticsExternalProcessorsEnabledEventHandler = isAnalyticsExternalProcessorsEnabled.addEventHandler;\nconst analyticsDatabaseNameEventFunctions = makePHEventFunctions(\"analyticsDatabaseName\");\n/** Sets the analytics database name for Connect. */\nconst setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;\n/** Gets the analytics database name for Connect. */\nconst useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;\n/** Adds an event handler for when the analytics database name for Connect changes. */\nconst addAnalyticsDatabaseNameEventHandler = analyticsDatabaseNameEventFunctions.addEventHandler;\nconst logLevelEventFunctions = makePHEventFunctions(\"logLevel\");\n/** Sets the log level for Connect. */\nconst setLogLevel = logLevelEventFunctions.setValue;\n/** Gets the log level for Connect. */\nconst useLogLevel = logLevelEventFunctions.useValue;\n/** Adds an event handler for when the log level for Connect changes. */\nconst addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;\nconst allowListEventFunctions = makePHEventFunctions(\"allowList\");\n/** Sets the allow list for Connect. */\nconst setAllowList = allowListEventFunctions.setValue;\n/** Gets the allow list for Connect. */\nconst useAllowList = allowListEventFunctions.useValue;\n/** Adds an event handler for when the allow list for Connect changes. */\nconst addAllowListEventHandler = allowListEventFunctions.addEventHandler;\nconst nonUserConfigSetters = {\n\trouterBasename: setRouterBasename,\n\tversion: setVersion,\n\trequiresHardRefresh: setRequiresHardRefresh,\n\twarnOutdatedApp: setWarnOutdatedApp,\n\tstudioMode: setStudioMode,\n\tbasePath: setBasePath,\n\tversionCheckInterval: setVersionCheckInterval,\n\tcliVersion: setCliVersion,\n\tfileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,\n\tisDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,\n\tgaTrackingId: setGaTrackingId,\n\tdefaultDrivesUrl: setDefaultDrivesUrl,\n\tdrivesPreserveStrategy: setDrivesPreserveStrategy,\n\tisLocalDrivesEnabled: setIsLocalDrivesEnabled,\n\tisAddDriveEnabled: setIsAddDriveEnabled,\n\tisPublicDrivesEnabled: setIsPublicDrivesEnabled,\n\tisAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,\n\tisDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,\n\tisCloudDrivesEnabled: setIsCloudDrivesEnabled,\n\tisAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,\n\tisDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,\n\tisAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,\n\tisDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,\n\tisEditorDebugModeEnabled: setIsEditorDebugModeEnabled,\n\tisEditorReadModeEnabled: setIsEditorReadModeEnabled,\n\tisRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,\n\tisExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,\n\tisAnalyticsEnabled: setIsAnalyticsEnabled,\n\tanalyticsDatabaseName: setAnalyticsDatabaseName,\n\tisAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,\n\tisAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,\n\tisDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,\n\tisDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,\n\trenownUrl: setRenownUrl,\n\trenownNetworkId: setRenownNetworkId,\n\trenownChainId: setRenownChainId,\n\tsentryRelease: setSentryRelease,\n\tsentryDsn: setSentryDsn,\n\tsentryEnv: setSentryEnv,\n\tisSentryTracingEnabled: setIsSentryTracingEnabled,\n\tisExternalProcessorsEnabled: setIsExternalProcessorsEnabled,\n\tisExternalPackagesEnabled: setIsExternalPackagesEnabled,\n\tallowList: setAllowList,\n\tlogLevel: setLogLevel,\n\tdisabledEditors: setDisabledEditors,\n\tenabledEditors: setEnabledEditors\n};\nconst phGlobalConfigSetters = {\n\t...phAppConfigSetters,\n\t...phDocumentEditorConfigSetters,\n\t...nonUserConfigSetters\n};\nconst nonUserConfigHooks = {\n\trouterBasename: useRouterBasename,\n\tversion: useVersion,\n\trequiresHardRefresh: useRequiresHardRefresh,\n\twarnOutdatedApp: useWarnOutdatedApp,\n\tstudioMode: useStudioMode,\n\tbasePath: useBasePath,\n\tversionCheckInterval: useVersionCheckInterval,\n\tcliVersion: useCliVersion,\n\tfileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,\n\tisDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,\n\tgaTrackingId: useGaTrackingId,\n\tdefaultDrivesUrl: useDefaultDrivesUrl,\n\tdrivesPreserveStrategy: useDrivesPreserveStrategy,\n\tisAddDriveEnabled: useIsAddDriveEnabled,\n\tisPublicDrivesEnabled: useIsPublicDrivesEnabled,\n\tisAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,\n\tisDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,\n\tisCloudDrivesEnabled: useIsCloudDrivesEnabled,\n\tisAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,\n\tisDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,\n\tisLocalDrivesEnabled: useIsLocalDrivesEnabled,\n\tisAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,\n\tisDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,\n\tisEditorDebugModeEnabled: useIsEditorDebugModeEnabled,\n\tisEditorReadModeEnabled: useIsEditorReadModeEnabled,\n\tisAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,\n\tisDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,\n\tisDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,\n\trenownUrl: useRenownUrl,\n\trenownNetworkId: useRenownNetworkId,\n\trenownChainId: useRenownChainId,\n\tsentryRelease: useSentryRelease,\n\tsentryDsn: useSentryDsn,\n\tsentryEnv: useSentryEnv,\n\tisSentryTracingEnabled: useIsSentryTracingEnabled,\n\tisExternalProcessorsEnabled: useIsExternalProcessorsEnabled,\n\tisExternalPackagesEnabled: useIsExternalPackagesEnabled,\n\tallowList: useAllowList,\n\tisAnalyticsEnabled: useIsAnalyticsEnabled,\n\tisAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,\n\tisRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,\n\tisExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,\n\tanalyticsDatabaseName: useAnalyticsDatabaseName,\n\tlogLevel: useLogLevel,\n\tdisabledEditors: useDisabledEditors,\n\tenabledEditors: useEnabledEditors\n};\nconst phGlobalConfigHooks = {\n\t...phAppConfigHooks,\n\t...phDocumentEditorConfigHooks,\n\t...nonUserConfigHooks\n};\n//#endregion\n//#region src/hooks/attachment-service.ts\nconst attachmentServiceEventFunctions = makePHEventFunctions(\"attachmentService\");\n/** Returns the attachment service from window.ph */\nconst useAttachmentService = attachmentServiceEventFunctions.useValue;\n/** Sets the attachment service on window.ph */\nconst setAttachmentService = attachmentServiceEventFunctions.setValue;\n/** Registers the attachmentService window event handler */\nconst addAttachmentServiceEventHandler = attachmentServiceEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/features.ts\nconst featuresEventFunctions = makePHEventFunctions(\"features\");\nconst useFeatures = featuresEventFunctions.useValue;\nconst setFeatures = featuresEventFunctions.setValue;\nconst addFeaturesEventHandler = featuresEventFunctions.addEventHandler;\n//#endregion\n//#region src/utils/url.ts\nfunction resolveUrlPathname(path) {\n\treturn new URL(path.replace(/^\\/+/, \"\"), window.location.origin + (window.ph?.basePath ?? \"/\")).pathname;\n}\n/** Returns the current path without the base path */\nfunction getPathWithoutBase(path) {\n\tconst basePath = window.ph?.basePath ?? \"/\";\n\treturn path.replace(basePath, basePath.endsWith(\"/\") ? \"/\" : \"\");\n}\n/** Makes a URL component for a drive. */\nfunction makeDriveUrlComponent(drive) {\n\tif (!drive) return \"\";\n\treturn `/d/${slug(drive.header.slug)}`;\n}\n/** Makes a URL component for a node. */\nfunction makeNodeSlug(node) {\n\tif (!node) return \"\";\n\tconst nodeName = node.name;\n\tif (!nodeName) return slug(node.id);\n\treturn slug(`${nodeName}-${node.id}`);\n}\n/** Extracts the node slug from a path.\n*\n* The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.\n*/\nfunction extractNodeSlugFromPath(path) {\n\tconst currentPath = getPathWithoutBase(path);\n\treturn /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath)?.[1];\n}\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nfunction findUuid(input) {\n\tif (!input) return void 0;\n\treturn /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/.exec(input)?.[0];\n}\nfunction extractNodeIdFromSlug(nodeSlug) {\n\treturn findUuid(nodeSlug);\n}\nfunction extractNodeIdFromPath(path) {\n\treturn extractNodeIdFromSlug(extractNodeSlugFromPath(path));\n}\n/** Extracts the drive slug from a path.\n* Used for extracting drive ids from drive slugs in the URL.\n* Expects the path to be in the format `/d/<drive-slug>`.\n*/\nfunction extractDriveSlugFromPath(path) {\n\tconst currentPath = getPathWithoutBase(path);\n\treturn /^\\/d\\/([^/]+)/.exec(currentPath)?.[1] ?? \"\";\n}\nfunction extractDriveIdFromSlug(driveSlug) {\n\treturn findUuid(driveSlug);\n}\nfunction extractDriveIdFromPath(path) {\n\treturn extractDriveIdFromSlug(extractDriveSlugFromPath(path));\n}\n/**\n* Creates a URL string with the given pathname while preserving existing query parameters.\n*/\nfunction createUrlWithPreservedParams(pathname) {\n\tconst search = window.location.search;\n\treturn search ? `${pathname}${search}` : pathname;\n}\n//#endregion\n//#region src/hooks/drives.ts\nconst drivesEventFunctions = makePHEventFunctions(\"drives\");\n/** Returns all of the drives in the reactor */\nconst useDrives = drivesEventFunctions.useValue;\n/** Sets the drives in the reactor */\nconst setDrives = drivesEventFunctions.setValue;\n/** Adds an event handler for the drives */\nconst addDrivesEventHandler = drivesEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/set-selected-node.ts\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useSelectedNodeId = selectedNodeIdEventFunctions.useValue;\nconst setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\nconst addSelectedNodeIdEventHandler = selectedNodeIdEventFunctions.addEventHandler;\n/** Sets the selected node (file or folder). */\nfunction setSelectedNode(nodeOrNodeSlug) {\n\tconst nodeSlug = typeof nodeOrNodeSlug === \"string\" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);\n\tsetSelectedNodeId(extractNodeIdFromSlug(nodeSlug));\n\tconst driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);\n\tif (!driveSlugFromPath) return;\n\tif (!nodeSlug) {\n\t\tconst pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);\n\t\tif (pathname === window.location.pathname) return;\n\t\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n\t\treturn;\n\t}\n\tconst pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);\n\tif (pathname === window.location.pathname) return;\n\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\nfunction addResetSelectedNodeEventHandler() {\n\twindow.addEventListener(\"ph:selectedDriveIdUpdated\", () => {\n\t\tsetSelectedNodeId(void 0);\n\t});\n}\nfunction addSetSelectedNodeOnPopStateEventHandler() {\n\twindow.addEventListener(\"popstate\", () => {\n\t\tconst pathname = window.location.pathname;\n\t\tconst nodeSlug = extractNodeSlugFromPath(pathname);\n\t\tif (extractNodeIdFromSlug(nodeSlug) !== window.ph?.selectedNodeId) setSelectedNode(nodeSlug);\n\t});\n}\n//#endregion\n//#region src/hooks/selected-drive.ts\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\n/** Returns the selected drive id */\nconst useSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n/** Sets the selected drive id */\nconst setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n/** Adds an event handler for the selected drive id */\nconst addSelectedDriveIdEventHandler = selectedDriveIdEventFunctions.addEventHandler;\n/** Returns the selected drive */\nfunction useSelectedDrive() {\n\tconst drive = useSelectedDriveSafe();\n\tif (!drive[0]) throw new Error(\"There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?\");\n\treturn drive;\n}\n/** Returns the selected drive, or undefined if no drive is selected */\nfunction useSelectedDriveSafe() {\n\tconst selectedDriveId = useSelectedDriveId();\n\tconst selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);\n\tconst [drive, dispatch] = useDispatch(selectedDrive);\n\tif (!selectedDrive) return [void 0, void 0];\n\treturn [drive, dispatch];\n}\nfunction setSelectedDrive(driveOrDriveSlug) {\n\tconst driveSlug = typeof driveOrDriveSlug === \"string\" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;\n\tconst drives = window.ph?.drives;\n\tconst driveId = (typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;\n\tif (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {\n\t\tif (window.ph?.selectedDriveId) setSelectedDriveId(void 0);\n\t\tdeferDriveSelection(driveSlug);\n\t\treturn;\n\t}\n\tcancelPendingDriveSelection();\n\tsetSelectedDriveId(driveId);\n\tif (!driveId) {\n\t\tconst pathname = resolveUrlPathname(\"/\");\n\t\tif (pathname === window.location.pathname) return;\n\t\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n\t\treturn;\n\t}\n\tconst pathname = resolveUrlPathname(`/d/${driveSlug}`);\n\tif (pathname === window.location.pathname) return;\n\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\nconst DEFERRED_DRIVE_TICK_MS = 2e3;\nconst DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;\nfunction isInitialSyncInFlight() {\n\tconst remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();\n\tif (!remotes?.length) return false;\n\treturn remotes.some((remote) => {\n\t\ttry {\n\t\t\tconst snapshot = remote.channel.getConnectionState();\n\t\t\treturn snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== \"error\";\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\nlet pendingHandler;\nlet pendingTimeout;\nfunction cancelPendingDriveSelection() {\n\tif (pendingHandler) {\n\t\twindow.removeEventListener(\"ph:drivesUpdated\", pendingHandler);\n\t\tpendingHandler = void 0;\n\t}\n\tif (pendingTimeout) {\n\t\tclearTimeout(pendingTimeout);\n\t\tpendingTimeout = void 0;\n\t}\n}\nfunction deferDriveSelection(driveSlug) {\n\tcancelPendingDriveSelection();\n\tconst nodeSlug = extractNodeSlugFromPath(window.location.pathname);\n\tconst handler = () => {\n\t\tif (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;\n\t\tcancelPendingDriveSelection();\n\t\tsetSelectedDrive(driveSlug);\n\t\tsetSelectedNode(nodeSlug);\n\t};\n\tpendingHandler = handler;\n\twindow.addEventListener(\"ph:drivesUpdated\", handler);\n\tconst deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n\tconst scheduleTick = () => {\n\t\tpendingTimeout = setTimeout(() => {\n\t\t\tif (Date.now() < deadline && isInitialSyncInFlight()) {\n\t\t\t\tscheduleTick();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcancelPendingDriveSelection();\n\t\t\tconst pathname = resolveUrlPathname(\"/\");\n\t\t\tif (pathname === window.location.pathname) return;\n\t\t\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n\t\t}, DEFERRED_DRIVE_TICK_MS);\n\t};\n\tscheduleTick();\n}\nfunction addSetSelectedDriveOnPopStateEventHandler() {\n\twindow.addEventListener(\"popstate\", () => {\n\t\tconst pathname = window.location.pathname;\n\t\tconst driveId = extractDriveIdFromPath(pathname);\n\t\tif (driveId !== window.ph?.selectedDriveId) setSelectedDrive(driveId);\n\t});\n}\n//#endregion\n//#region src/hooks/use-drop-target.ts\nfunction useDropTarget() {\n\tconst [isDropTarget, setIsDropTarget] = useState(false);\n\tconst isDragAndDropEnabled = useIsDragAndDropEnabled();\n\tconst targetSetter = funnel(() => setIsDropTarget(true), {\n\t\ttriggerAt: \"start\",\n\t\tminQuietPeriodMs: 100\n\t});\n\tconst targetUnsetter = funnel(() => setIsDropTarget(false), {\n\t\ttriggerAt: \"start\",\n\t\tminQuietPeriodMs: 100\n\t});\n\tfunction setTarget() {\n\t\tif (!isDragAndDropEnabled) return;\n\t\ttargetUnsetter.cancel();\n\t\ttargetSetter.call();\n\t}\n\tfunction unsetTarget() {\n\t\tif (!isDragAndDropEnabled) return;\n\t\ttargetSetter.cancel();\n\t\ttargetUnsetter.call();\n\t}\n\treturn {\n\t\tisDropTarget,\n\t\tsetTarget,\n\t\tunsetTarget\n\t};\n}\n//#endregion\n//#region src/hooks/node-drag-and-drop.ts\nconst draggingNodeEventFunctions = makePHEventFunctions(\"draggingNode\");\nconst useDraggingNode = draggingNodeEventFunctions.useValue;\nconst setDraggingNode = draggingNodeEventFunctions.setValue;\nconst addDraggingNodeEventHandler = draggingNodeEventFunctions.addEventHandler;\nconst draggingNodeSetter = funnel((node) => setDraggingNode(node), {\n\treducer: (_, newNode) => newNode,\n\ttriggerAt: \"start\",\n\tminQuietPeriodMs: 100\n});\nconst draggingNodeUnsetter = funnel(() => setDraggingNode(void 0), {\n\ttriggerAt: \"start\",\n\tminQuietPeriodMs: 100\n});\nfunction setDragging(node) {\n\tdraggingNodeUnsetter.cancel();\n\tdraggingNodeSetter.call(node);\n}\nfunction unsetDragging() {\n\tdraggingNodeSetter.cancel();\n\tdraggingNodeUnsetter.call();\n}\nconst isNodeDrag = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isTruthy)(driveId), constant(false)], [({ driveId, srcId }) => isStrictEqual(driveId, srcId), constant(false)], constant(true));\nfunction useDragNode(args) {\n\tconst { srcId, parentId } = args;\n\tconst driveId = useSelectedDriveId();\n\tconst draggingNodeId = useDraggingNode()?.srcId;\n\tconst params = {\n\t\tdriveId,\n\t\tsrcId,\n\t\tparentId\n\t};\n\tconst draggable = isNodeDrag(params);\n\tconst isDragging = allPass({\n\t\tsrcId,\n\t\tdraggingNodeId\n\t}, [\n\t\t() => draggable,\n\t\t({ srcId }) => isString(srcId),\n\t\t({ draggingNodeId }) => isString(draggingNodeId),\n\t\t({ srcId, draggingNodeId }) => isStrictEqual(srcId, draggingNodeId)\n\t]);\n\tconst onDragStart = () => {\n\t\tif (!draggable) return;\n\t\tsetDragging(params);\n\t};\n\tconst onDragEnd = () => {\n\t\tif (!draggable) return;\n\t\tunsetDragging();\n\t};\n\treturn {\n\t\tisDragging,\n\t\tdraggable,\n\t\tonDragStart,\n\t\tonDragEnd\n\t};\n}\nconst isNodeDrop = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isDefined)(driveId), constant(false)], [({ srcId, targetId }) => isStrictEqual(srcId, targetId), constant(false)], [({ driveId, parentId, targetId }) => isNot(isTruthy)(parentId) && isStrictEqual(targetId, driveId), constant(false)], [({ targetId, parentId }) => isStrictEqual(targetId, parentId), constant(false)], constant(true));\nfunction useDropNode(targetId) {\n\tconst driveId = useSelectedDriveId();\n\tconst { srcId, parentId } = useDraggingNode() ?? {};\n\tconst { isDropTarget, setTarget, unsetTarget } = useDropTarget();\n\tconst params = {\n\t\tdriveId,\n\t\tparentId,\n\t\ttargetId,\n\t\tsrcId\n\t};\n\tfunction handleNodeDrop(event, cb) {\n\t\tif (!isNodeDrop(params)) return;\n\t\tevent.preventDefault();\n\t\tevent.stopPropagation();\n\t\tcb?.();\n\t}\n\tconst onDragEnter = (event) => handleNodeDrop(event);\n\tconst onDragOver = (event) => handleNodeDrop(event, once(setTarget));\n\tconst onDragLeave = (event) => handleNodeDrop(event, once(unsetTarget));\n\tconst onDrop = (event) => handleNodeDrop(event, once(() => {\n\t\tunsetDragging();\n\t\tunsetTarget();\n\t\tmoveNodeById(params).catch(console.error);\n\t}));\n\treturn {\n\t\tisDropTarget,\n\t\tonDragEnter,\n\t\tonDragOver,\n\t\tonDragLeave,\n\t\tonDrop\n\t};\n}\n//#endregion\n//#region src/hooks/graphql-reactor-client.ts\nconst graphQLReactorClientEventFunctions = makePHEventFunctions(\"reactorGraphQLClient\");\nconst useGraphQLReactorClient = graphQLReactorClientEventFunctions.useValue;\nconst setGraphQLReactorClient = graphQLReactorClientEventFunctions.setValue;\nconst addGraphQLReactorClientEventHandler = graphQLReactorClientEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/package-discovery.ts\nconst packageDiscoveryFunctions = makePHEventFunctions(\"packageDiscoveryService\");\nconst usePackageDiscoveryService = packageDiscoveryFunctions.useValue;\nconst setPackageDiscoveryService = packageDiscoveryFunctions.setValue;\nconst addPackageDiscoveryServiceEventHandler = packageDiscoveryFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/reactor.ts\nconst reactorClientModuleEventFunctions = makePHEventFunctions(\"reactorClientModule\");\nconst reactorClientEventFunctions = makePHEventFunctions(\"reactorClient\");\n/** Returns the reactor client module */\nconst useReactorClientModule = reactorClientModuleEventFunctions.useValue;\n/** Sets the reactor client module */\nconst setReactorClientModule = reactorClientModuleEventFunctions.setValue;\n/** Adds an event handler for the reactor client module */\nconst addReactorClientModuleEventHandler = reactorClientModuleEventFunctions.addEventHandler;\n/** Returns the reactor client */\nconst useReactorClient = reactorClientEventFunctions.useValue;\n/** Sets the reactor client */\nconst setReactorClient = reactorClientEventFunctions.setValue;\n/** Adds an event handler for the reactor client */\nconst addReactorClientEventHandler = reactorClientEventFunctions.addEventHandler;\nconst useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;\nconst useSyncList = () => {\n\treturn useSync()?.list() ?? [];\n};\nconst useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;\nconst useDatabase = () => useReactorClientModule()?.reactorModule?.database;\nconst usePGlite = () => useReactorClientModule()?.pg;\n//#endregion\n//#region src/hooks/revision-history.ts\nconst revisionHistoryEventFunctions = makePHEventFunctions(\"revisionHistoryVisible\");\n/** Returns whether revision history is visible */\nconst useRevisionHistoryVisible = revisionHistoryEventFunctions.useValue;\n/** Sets revision history visibility */\nconst setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;\n/** Adds event handler for revision history visibility */\nconst addRevisionHistoryVisibleEventHandler = revisionHistoryEventFunctions.addEventHandler;\n/** Shows the revision history */\nfunction showRevisionHistory() {\n\tsetRevisionHistoryVisible(true);\n}\n/** Hides the revision history */\nfunction hideRevisionHistory() {\n\tsetRevisionHistoryVisible(false);\n}\n//#endregion\n//#region src/utils/nodes.ts\n/** Sorts nodes by name. */\nfunction sortNodesByName(nodes) {\n\treturn nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n/** Returns whether a node is a file. */\nfunction isFileNodeKind(node) {\n\tif (!node) return false;\n\treturn node.kind.toUpperCase() === \"FILE\";\n}\n/** Returns whether a node is a folder. */\nfunction isFolderNodeKind(node) {\n\tif (!node) return false;\n\treturn node.kind.toUpperCase() === \"FOLDER\";\n}\n//#endregion\n//#region src/hooks/items-in-selected-drive.ts\n/** Returns the nodes in the selected drive. */\nfunction useNodesInSelectedDrive() {\n\tconst [selectedDrive] = useSelectedDriveSafe();\n\treturn selectedDrive?.state.global.nodes;\n}\n/** Returns the file nodes in the selected drive. */\nfunction useFileNodesInSelectedDrive() {\n\treturn useNodesInSelectedDrive()?.filter((n) => isFileNodeKind(n));\n}\n/** Returns the folder nodes in the selected drive. */\nfunction useFolderNodesInSelectedDrive() {\n\treturn useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));\n}\n/** Returns the documents in the selected drive. */\nfunction useDocumentsInSelectedDrive() {\n\tconst fileNodeIds = useFileNodesInSelectedDrive()?.map((node) => node.id);\n\treturn useDocumentsByIds(fileNodeIds);\n}\n/** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */\nfunction useDocumentTypesInSelectedDrive() {\n\treturn (useDocumentsInSelectedDrive()?.filter(isDocumentModelDocument))?.map((doc) => doc.state.global.id);\n}\nfunction isDocumentModelDocument(document) {\n\treturn document.header.documentType === \"powerhouse/document-model\";\n}\n//#endregion\n//#region src/hooks/selected-node.ts\n/** Returns the selected node. */\nfunction useSelectedNode() {\n\tconst selectedNodeId = useSelectedNodeId();\n\treturn useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);\n}\n//#endregion\n//#region src/hooks/selected-timeline-item.ts\nconst selectedTimelineItemEventFunctions = makePHEventFunctions(\"selectedTimelineItem\");\n/** Returns the selected timeline item */\nconst useSelectedTimelineItem = selectedTimelineItemEventFunctions.useValue;\n/** Sets the selected timeline item */\nconst setSelectedTimelineItem = selectedTimelineItemEventFunctions.setValue;\n/** Adds event handler for selected timeline item */\nconst addSelectedTimelineItemEventHandler = selectedTimelineItemEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/timeline-revision.ts\nconst selectedTimelineRevisionEventFunctions = makePHEventFunctions(\"selectedTimelineRevision\");\n/** Returns the selected timeline revision. */\nconst useSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.useValue;\n/** Sets the selected timeline revision. */\nconst setSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.setValue;\n/** Adds an event handler for the selected timeline revision. */\nconst addSelectedTimelineRevisionEventHandler = selectedTimelineRevisionEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/toast.ts\nconst toastEventFunctions = makePHEventFunctions(\"toast\");\n/** Returns the toast function */\nconst usePHToast = toastEventFunctions.useValue;\n/** Sets the toast function */\nconst setPHToast = toastEventFunctions.setValue;\n/** Adds an event handler for the toast */\nconst addToastEventHandler = toastEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/vetra-packages.ts\nconst vetraPackageManagerFunctions = makePHEventFunctions(\"vetraPackageManager\");\nconst useVetraPackageManager = vetraPackageManagerFunctions.useValue;\n/** Returns all of the Vetra packages loaded by the Connect instance */\nconst useVetraPackages = () => {\n\tconst packageManager = useVetraPackageManager();\n\treturn useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : () => {}, () => packageManager?.packages ?? []);\n};\n/** Adds the Vetra package manager event handler */\nconst addVetraPackageManagerEventHandler = vetraPackageManagerFunctions.addEventHandler;\n/** Sets the Vetra package manager and registers its packages */\nfunction setVetraPackageManager(packageManager) {\n\tvetraPackageManagerFunctions.setValue(packageManager);\n\tupdateReactorClientDocumentModels(packageManager.packages);\n\tupdateReactorClientUpgradeManifests(packageManager.packages);\n\tpackageManager.subscribe(({ packages }) => {\n\t\tupdateReactorClientDocumentModels(packages);\n\t\tupdateReactorClientUpgradeManifests(packages);\n\t});\n}\nfunction updateReactorClientDocumentModels(packages) {\n\tconst documentModelModules = packages.flatMap((pkg) => pkg.documentModels);\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tif (!registry || documentModelModules.length === 0) return;\n\tconst results = registry.registerModules(...documentModelModules);\n\tconst duplicates = [];\n\tfor (const result of results) if (result.status === \"error\") if (DuplicateModuleError.isError(result.error)) duplicates.push(result);\n\telse console.error(\"Failed to register document model module:\", result.error);\n\tif (duplicates.length > 0) {\n\t\tconst duplicateTypes = duplicates.map((r) => r.item.documentModel.global.id);\n\t\tregistry.unregisterModules(...duplicateTypes);\n\t\tregistry.registerModules(...duplicates.map((r) => r.item));\n\t}\n}\nfunction updateReactorClientUpgradeManifests(packages) {\n\tconst upgradeManifests = packages.flatMap((pkg) => pkg.upgradeManifests).filter((u) => u !== void 0);\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tif (!registry || upgradeManifests.length === 0) return;\n\tconst results = registry.registerUpgradeManifests(...upgradeManifests);\n\tconst duplicates = [];\n\tfor (const result of results) if (result.status === \"error\") if (DuplicateManifestError.isError(result.error)) duplicates.push(result);\n\telse console.error(\"Failed to register upgrade manifest:\", result.error);\n\tif (duplicates.length > 0) {\n\t\tconst duplicateTypes = duplicates.map((r) => r.item.documentType).filter((t) => !!t);\n\t\tregistry.unregisterUpgradeManifests(...duplicateTypes);\n\t\tregistry.registerUpgradeManifests(...duplicates.map((r) => r.item));\n\t}\n}\n//#endregion\n//#region src/hooks/add-ph-event-handlers.ts\nconst commonGlobalEventHandlerFunctions = {\n\tloading: addLoadingEventHandler,\n\tdrives: addDrivesEventHandler,\n\tselectedDriveId: () => {\n\t\taddSelectedDriveIdEventHandler();\n\t\taddSetSelectedDriveOnPopStateEventHandler();\n\t\taddResetSelectedNodeEventHandler();\n\t},\n\tselectedNodeId: () => {\n\t\taddSelectedNodeIdEventHandler();\n\t\taddSetSelectedNodeOnPopStateEventHandler();\n\t},\n\tdocumentCache: addDocumentCacheEventHandler,\n\treactorGraphQLClient: addGraphQLReactorClientEventHandler,\n\tdraggingNode: addDraggingNodeEventHandler\n};\nconst phGlobalEventHandlerRegisterFunctions = {\n\t...commonGlobalEventHandlerFunctions,\n\treactorClientModule: addReactorClientModuleEventHandler,\n\treactorClient: addReactorClientEventHandler,\n\tattachmentService: addAttachmentServiceEventHandler,\n\tfeatures: addFeaturesEventHandler,\n\tmodal: addModalEventHandler,\n\trenown: addRenownEventHandler,\n\tvetraPackageManager: addVetraPackageManagerEventHandler,\n\tpackageDiscoveryService: addPackageDiscoveryServiceEventHandler,\n\tselectedTimelineRevision: addSelectedTimelineRevisionEventHandler,\n\trevisionHistoryVisible: addRevisionHistoryVisibleEventHandler,\n\tselectedTimelineItem: addSelectedTimelineItemEventHandler,\n\trouterBasename: addRouterBasenameEventHandler,\n\tversion: addVersionEventHandler,\n\tlogLevel: addLogLevelEventHandler,\n\trequiresHardRefresh: addRequiresHardRefreshEventHandler,\n\twarnOutdatedApp: addWarnOutdatedAppEventHandler,\n\tstudioMode: addStudioModeEventHandler,\n\tbasePath: addBasePathEventHandler,\n\tversionCheckInterval: addVersionCheckIntervalEventHandler,\n\tcliVersion: addCliVersionEventHandler,\n\tfileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,\n\tisDocumentModelSelectionSettingsEnabled: addIsDocumentModelSelectionSettingsEnabledEventHandler,\n\tgaTrackingId: addGaTrackingIdEventHandler,\n\tallowList: addAllowListEventHandler,\n\tdefaultDrivesUrl: addDefaultDrivesUrlEventHandler,\n\tdrivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,\n\tallowedDocumentTypes: addAllowedDocumentTypesEventHandler,\n\tenabledEditors: addEnabledEditorsEventHandler,\n\tdisabledEditors: addDisabledEditorsEventHandler,\n\tisAddDriveEnabled: addIsAddDriveEnabledEventHandler,\n\tisLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,\n\tisPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,\n\tisAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,\n\tisDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,\n\tisCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,\n\tisAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,\n\tisDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,\n\tisAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,\n\tisDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,\n\tisDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,\n\tisExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,\n\tisEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,\n\tisEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,\n\tisRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,\n\tisExternalRelationalProcessorsEnabled: addIsExternalRelationalProcessorsEnabledEventHandler,\n\tisAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,\n\tisAnalyticsExternalProcessorsEnabled: addIsAnalyticsExternalProcessorsEnabledEventHandler,\n\tanalyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,\n\tisAnalyticsDatabaseWorkerEnabled: addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n\tisDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,\n\tisDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,\n\trenownUrl: addRenownUrlEventHandler,\n\trenownNetworkId: addRenownNetworkIdEventHandler,\n\trenownChainId: addRenownChainIdEventHandler,\n\tsentryRelease: addSentryReleaseEventHandler,\n\tsentryDsn: addSentryDsnEventHandler,\n\tsentryEnv: addSentryEnvEventHandler,\n\tisSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,\n\tisExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,\n\tisExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,\n\ttoast: addToastEventHandler\n};\nfunction addPHEventHandlers() {\n\tcallEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);\n}\nfunction callEventHandlerRegisterFunctions(registerFunctions) {\n\tforEachObj(registerFunctions, (fn) => fn());\n}\n//#endregion\n//#region src/hooks/document-model-modules.ts\nfunction useDocumentModelModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);\n}\nfunction useDocumentModelModuleById(id) {\n\treturn useDocumentModelModules()?.find((module) => module.documentModel.global.id === id);\n}\n//#endregion\n//#region src/hooks/allowed-document-model-modules.ts\nfunction useAllowedDocumentModelModules() {\n\tconst documentModelModules = useDocumentModelModules();\n\tconst allowedDocumentTypes = useAllowedDocumentTypes();\n\tif (!allowedDocumentTypes?.length) return documentModelModules;\n\treturn documentModelModules?.filter((module) => allowedDocumentTypes.includes(module.documentModel.global.id));\n}\n//#endregion\n//#region src/hooks/selected-folder.ts\n/** Returns the selected folder. */\nfunction useSelectedFolder() {\n\tconst selectedNode = useSelectedNode();\n\tif (isFolderNodeKind(selectedNode)) return selectedNode;\n}\n//#endregion\n//#region src/hooks/child-nodes.ts\n/** Returns the child nodes for the selected drive or folder. */\nfunction useNodesInSelectedDriveOrFolder() {\n\tconst nodes = useNodesInSelectedDrive();\n\tconst selectedFolderId = useSelectedFolder()?.id;\n\tif (!nodes) return [];\n\tif (!selectedFolderId) return sortNodesByName(nodes.filter((n) => !n.parentFolder));\n\treturn sortNodesByName(nodes.filter((n) => n.parentFolder === selectedFolderId));\n}\n//#endregion\n//#region src/hooks/config/set-config-by-key.ts\nfunction setPHGlobalConfigByKey(key, value) {\n\tconst setter = phGlobalConfigSetters[key];\n\tsetter(value);\n}\nfunction setPHAppConfigByKey(key, value) {\n\tconst setter = phAppConfigSetters[key];\n\tsetter(value);\n}\nfunction setPHDocumentEditorConfigByKey(key, value) {\n\tconst setter = phDocumentEditorConfigSetters[key];\n\tsetter(value);\n}\n//#endregion\n//#region src/hooks/config/utils.ts\nfunction callGlobalSetterForKey(key, value) {\n\tconst setter = phGlobalConfigSetters[key];\n\tsetter(value);\n}\n//#endregion\n//#region src/hooks/config/set-config-by-object.ts\nfunction setDefaultPHGlobalConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\n}\nfunction useSetDefaultPHGlobalConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetDefaultPHGlobalConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\n}\nfunction useResetPHGlobalConfig(defaultConfigForReset) {\n\treturn function reset() {\n\t\tsetPHGlobalConfig(defaultConfigForReset);\n\t};\n}\nfunction setPHGlobalConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\n}\nfunction useSetPHGlobalConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetPHGlobalConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\n}\n/** Sets the global drive config.\n*\n* Pass in a partial object of the global drive config to set.\n*/\nfunction setPHAppConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\n}\n/** Sets the global document config.\n*\n* Pass in a partial object of the global document config to set.\n*/\nfunction setPHDocumentEditorConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\n}\n/** Wrapper hook for setting the global app config.\n*\n* Automatically sets the global app config when the component mounts.\n*\n* Pass in a partial object of the global app config to set.\n*/\nfunction useSetPHAppConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetPHAppConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\n}\n/** Wrapper hook for setting the global document editor config.\n*\n* Automatically sets the global document editor config when the component mounts.\n*\n* Pass in a partial object of the global document editor config to set.\n*/\nfunction useSetPHDocumentEditorConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetPHDocumentEditorConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\n}\n//#endregion\n//#region src/hooks/config/use-value-by-key.ts\nfunction usePHGlobalConfigByKey(key) {\n\tconst useValueHook = phGlobalConfigHooks[key];\n\treturn useValueHook();\n}\n/** Gets the value of an item in the global drive config for a given key.\n*\n* Strongly typed, inferred from type definition for the key.\n*/\nfunction usePHAppConfigByKey(key) {\n\tconst useValueHook = phAppConfigHooks[key];\n\treturn useValueHook();\n}\n/** Gets the value of an item in the global document config for a given key.\n*\n* Strongly typed, inferred from type definition for the key.\n*/\nfunction usePHDocumentEditorConfigByKey(key) {\n\tconst useValueHook = phDocumentEditorConfigHooks[key];\n\treturn useValueHook();\n}\n//#endregion\n//#region src/hooks/connection-state.ts\n/**\n* Returns a map of remote name to connection state snapshot for all remotes.\n* Re-renders when any remote's connection state changes.\n*/\nfunction useConnectionStates() {\n\tconst syncManager = useSync();\n\tconst [states, setStates] = useState(() => buildSnapshot(syncManager));\n\tconst unsubscribesRef = useRef([]);\n\tuseEffect(() => {\n\t\tif (!syncManager) return;\n\t\tfunction subscribe() {\n\t\t\tfor (const unsub of unsubscribesRef.current) unsub();\n\t\t\tunsubscribesRef.current = [];\n\t\t\tconst remotes = syncManager.list();\n\t\t\tfor (const remote of remotes) {\n\t\t\t\tconst unsub = remote.channel.onConnectionStateChange(() => {\n\t\t\t\t\tsetStates(buildSnapshot(syncManager));\n\t\t\t\t});\n\t\t\t\tunsubscribesRef.current.push(unsub);\n\t\t\t}\n\t\t\tsetStates(buildSnapshot(syncManager));\n\t\t}\n\t\tsubscribe();\n\t\tconst interval = setInterval(subscribe, 5e3);\n\t\treturn () => {\n\t\t\tclearInterval(interval);\n\t\t\tfor (const unsub of unsubscribesRef.current) unsub();\n\t\t\tunsubscribesRef.current = [];\n\t\t};\n\t}, [syncManager]);\n\treturn states;\n}\n/**\n* Returns the connection state snapshot for a specific remote by name.\n*/\nfunction useConnectionState(remoteName) {\n\treturn useConnectionStates().get(remoteName);\n}\nfunction buildSnapshot(syncManager) {\n\tconst map = /* @__PURE__ */ new Map();\n\tif (!syncManager) return map;\n\tfor (const remote of syncManager.list()) map.set(remote.name, remote.channel.getConnectionState());\n\treturn map;\n}\n//#endregion\n//#region src/hooks/document-of-type.ts\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nfunction useDocumentOfType(documentId, documentType) {\n\tconst [document, dispatch] = useDocumentById(documentId);\n\tconst documentModelModule = useDocumentModelModuleById(documentType);\n\tif (!documentId || !documentType) return [];\n\tif (!document) throw new Error(`Document not found: ${documentId}`);\n\tif (!documentModelModule) throw new ModuleNotFoundError(documentType);\n\tif (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);\n\treturn [document, dispatch];\n}\n//#endregion\n//#region src/hooks/document-operations.ts\n/**\n* Hook to fetch document operations via the reactor client.\n* Operations are no longer auto-populated on documents and must be fetched explicitly.\n*\n* @param documentId - The document ID to fetch operations for\n* @returns Object containing globalOperations, localOperations, isLoading, and error\n*/\nfunction useDocumentOperations(documentId) {\n\tconst reactorClient = useReactorClient();\n\tconst hasFetchedRef = useRef(false);\n\tconst [state, setState] = useState(() => ({\n\t\tglobalOperations: [],\n\t\tlocalOperations: [],\n\t\tisLoading: !!documentId,\n\t\terror: void 0\n\t}));\n\tconst fetchOperations = useCallback(async (retryCount = 0) => {\n\t\tconst MAX_RETRIES = 5;\n\t\tconst RETRY_DELAY_MS = 500;\n\t\tif (!documentId || !reactorClient) {\n\t\t\tsetState({\n\t\t\t\tglobalOperations: [],\n\t\t\t\tlocalOperations: [],\n\t\t\t\tisLoading: false,\n\t\t\t\terror: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tsetState((prev) => ({\n\t\t\t...prev,\n\t\t\tisLoading: true,\n\t\t\terror: void 0\n\t\t}));\n\t\tlet globalOps = [];\n\t\tlet localOps = [];\n\t\tlet fetchError;\n\t\ttry {\n\t\t\tglobalOps = (await reactorClient.getOperations(documentId, { scopes: [\"global\"] })).results;\n\t\t} catch (err) {\n\t\t\tfetchError = err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (!fetchError) try {\n\t\t\tlocalOps = (await reactorClient.getOperations(documentId, { scopes: [\"local\"] })).results;\n\t\t} catch (err) {\n\t\t\tfetchError = err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (!fetchError && globalOps.length === 0 && localOps.length === 0 && retryCount < MAX_RETRIES) {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));\n\t\t\treturn fetchOperations(retryCount + 1);\n\t\t}\n\t\tsetState({\n\t\t\tglobalOperations: globalOps,\n\t\t\tlocalOperations: localOps,\n\t\t\tisLoading: false,\n\t\t\terror: fetchError\n\t\t});\n\t\thasFetchedRef.current = true;\n\t}, [documentId, reactorClient]);\n\tuseEffect(() => {\n\t\tif (documentId && reactorClient) fetchOperations();\n\t\telse if (!documentId) {\n\t\t\tsetState({\n\t\t\t\tglobalOperations: [],\n\t\t\t\tlocalOperations: [],\n\t\t\t\tisLoading: false,\n\t\t\t\terror: void 0\n\t\t\t});\n\t\t\thasFetchedRef.current = false;\n\t\t}\n\t}, [\n\t\tdocumentId,\n\t\treactorClient,\n\t\tfetchOperations\n\t]);\n\tconst refetch = useCallback(() => {\n\t\tfetchOperations(0);\n\t}, [fetchOperations]);\n\treturn {\n\t\t...state,\n\t\trefetch\n\t};\n}\n//#endregion\n//#region src/hooks/supported-document-types.ts\n/** Returns the supported document types for the reactor (derived from the document model modules) */\nfunction useSupportedDocumentTypesInReactor() {\n\treturn useDocumentModelModules()?.map((module) => module.documentModel.global.id);\n}\n//#endregion\n//#region src/hooks/document-types.ts\n/** Returns the document types a app supports.\n*\n* If present, uses the `allowedDocumentTypes` config value.\n* Otherwise, uses the supported document types from the reactor.\n*/\nfunction useDocumentTypes() {\n\tconst allowedDocumentTypes = useAllowedDocumentTypes();\n\tconst supportedDocumentTypes = useSupportedDocumentTypesInReactor();\n\treturn allowedDocumentTypes ?? supportedDocumentTypes;\n}\n//#endregion\n//#region src/utils/validate-document.ts\nconst validateDocument = (document) => {\n\tconst errors = [];\n\tif (document.header.documentType !== \"powerhouse/document-model\") return errors;\n\tconst doc = document;\n\tconst specs = doc.state.global.specifications[0];\n\tconst initialStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {\n\t\tconst scope = scopeKey;\n\t\treturn [...acc, ...validateInitialState(specs.state[scope].initialValue, scope !== \"global\").map((err) => ({\n\t\t\t...err,\n\t\t\tmessage: `${err.message}. Scope: ${scope}`,\n\t\t\tdetails: {\n\t\t\t\t...err.details,\n\t\t\t\tscope\n\t\t\t}\n\t\t}))];\n\t}, []);\n\tconst schemaStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {\n\t\tconst scope = scopeKey;\n\t\tconst isGlobalScope = scope === \"global\";\n\t\treturn [...acc, ...validateStateSchemaName(specs.state[scope].schema, doc.state.global?.name || doc.header.name || \"\", !isGlobalScope ? scope : \"\", !isGlobalScope).map((err) => ({\n\t\t\t...err,\n\t\t\tmessage: `${err.message}. Scope: ${scope}`,\n\t\t\tdetails: {\n\t\t\t\t...err.details,\n\t\t\t\tscope\n\t\t\t}\n\t\t}))];\n\t}, []);\n\tconst modulesErrors = validateModules(specs.modules);\n\treturn [\n\t\t...initialStateErrors,\n\t\t...schemaStateErrors,\n\t\t...modulesErrors\n\t];\n};\n//#endregion\n//#region src/utils/download-document.ts\nfunction defaultHandleError(error) {\n\tconsole.error(`Failed to export document: ${error.message}`);\n}\nfunction handleDocumentValidation(document) {\n\tif (hasAtLeast(validateDocument(document), 1)) return false;\n\treturn true;\n}\nfunction downloadDocument(document, handleError = defaultHandleError) {\n\tif (!document) return;\n\tif (!handleDocumentValidation(document)) {\n\t\tshowPHModal({\n\t\t\ttype: \"downloadDocumentWithErrors\",\n\t\t\tdocumentId: document.header.id\n\t\t});\n\t\treturn;\n\t}\n\texportFile(document).catch((error) => handleError(normalizeException(error)));\n}\n//#endregion\n//#region src/hooks/download-document.ts\nfunction useDownloadDocument(id) {\n\tconst getDocument = useGetDocument();\n\tconst toast = usePHToast();\n\treturn async () => {\n\t\tif (!id) return;\n\t\tconst handleError = (error) => toast?.(`Failed to export document: ${error.message}`);\n\t\ttry {\n\t\t\tdownloadDocument(await getDocument(id), handleError);\n\t\t} catch (error) {\n\t\t\thandleError(error);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/hooks/drive-by-id.ts\nfunction useDriveById(driveId) {\n\tconst foundDrive = useDrives()?.find((drive) => drive.header.id === driveId);\n\tconst [drive, dispatch] = useDispatch(foundDrive);\n\tif (!foundDrive) throw new Error(`Drive with id ${driveId} not found`);\n\treturn [drive, dispatch];\n}\n//#endregion\n//#region src/hooks/editor-modules.ts\nfunction useEditorModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.editors).filter((module) => !module.documentTypes.includes(\"powerhouse/document-drive\"));\n}\nfunction useAppModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.editors).filter((module) => module.documentTypes.includes(\"powerhouse/document-drive\"));\n}\nfunction useFallbackEditorModule(documentType) {\n\tconst editorModules = useEditorModules();\n\tif (!documentType) return void 0;\n\tif (editorModules?.length === 0) return void 0;\n\treturn (editorModules?.filter((module) => module.documentTypes.includes(documentType)))?.[0];\n}\nfunction useAppModuleById(id) {\n\treturn useAppModules()?.find((module) => module.config.id === id);\n}\nfunction useDefaultAppModule() {\n\treturn useAppModuleById(DEFAULT_DRIVE_EDITOR_ID);\n}\nfunction useEditorModuleById(id) {\n\treturn useEditorModules()?.find((module) => module.config.id === id);\n}\nfunction useEditorModulesForDocumentType(documentType) {\n\tconst editorModules = useEditorModules();\n\tif (!documentType) return void 0;\n\treturn editorModules?.filter((module) => module.documentTypes.includes(documentType));\n}\n//#endregion\n//#region src/hooks/file-drag-and-drop.ts\nconst allowedExtensions = [\n\t\"zip\",\n\t\"phd\",\n\t\"phdm\"\n];\nconst hasFilesType = (types) => isDefined(find(types, (type) => isStrictEqual(type, \"Files\")));\nconst isFileDrop = (event) => allPass(event.dataTransfer.types, [\n\tisArray,\n\thasAtLeast(1),\n\thasFilesType\n]);\nconst EDITOR_FILE_DROP_OPT_OUT_ATTR = \"data-accepts-files\";\nconst isInsideEditorFileDropOptOut = (event) => {\n\tconst target = event.target;\n\tif (!(target instanceof Element)) return false;\n\treturn target.closest(`[${EDITOR_FILE_DROP_OPT_OUT_ATTR}]`) !== null;\n};\nconst hasAllowedExtension = (file) => pipe(file, (file) => file.name, split(\".\"), last(), isIncludedIn(allowedExtensions));\nconst getFileItems = (event) => pipe([...event.dataTransfer.items], filter((item) => isStrictEqual(item.kind, \"file\")), map((item) => item.getAsFile()), filter(isTruthy));\nfunction useDropFile(handleAddFile) {\n\tconst { isDropTarget, setTarget, unsetTarget } = useDropTarget();\n\tconst isDragAndDropEnabled = useIsDragAndDropEnabled();\n\tconst selectedFolder = useSelectedFolder();\n\tfunction handleDragEvent(event, cb) {\n\t\tif (!isDragAndDropEnabled) return;\n\t\tif (!isFileDrop(event)) return;\n\t\tif (isInsideEditorFileDropOptOut(event)) {\n\t\t\tunsetTarget();\n\t\t\treturn;\n\t\t}\n\t\tevent.preventDefault();\n\t\tevent.stopPropagation();\n\t\tcb?.();\n\t}\n\tconst handleAddFiles = (event) => Promise.all(pipe(event, getFileItems, filter(hasAllowedExtension), map((file) => handleAddFile(file, selectedFolder))));\n\tconst onDragEnter = (event) => handleDragEvent(event);\n\tconst onDragOver = (event) => handleDragEvent(event, setTarget);\n\tconst onDragLeave = (event) => handleDragEvent(event, unsetTarget);\n\tconst onDrop = (event) => handleDragEvent(event, once(() => {\n\t\tunsetTarget();\n\t\thandleAddFiles(event).catch(console.error);\n\t}));\n\treturn {\n\t\tonDragEnter,\n\t\tonDragOver,\n\t\tonDragLeave,\n\t\tonDrop,\n\t\tisDropTarget\n\t};\n}\n//#endregion\n//#region src/hooks/folder-by-id.ts\nfunction useFolderById(id) {\n\treturn useFolderNodesInSelectedDrive()?.find((n) => n.id === id);\n}\n//#endregion\n//#region src/graphql/events.ts\nfunction dispatchGraphQLClientDocumentEvent(operationName, identifier) {\n\tconst event = new CustomEvent(operationName, { detail: { identifier } });\n\twindow.dispatchEvent(event);\n}\n//#endregion\n//#region src/graphql/document-cache-client-middleware.ts\nconst documentCacheClientMiddleware = async (action, operationName, operationType, variables) => {\n\tconsole.log({\n\t\toperationName,\n\t\toperationType,\n\t\tvariables\n\t});\n\tconst result = await action();\n\tif (isIncludedIn(operationName, graphqlEventsToSyncDrive)) window.dispatchEvent(new CustomEvent(operationName));\n\tif (isStrictEqual(operationName, \"MutateDocument\")) dispatchGraphQLClientDocumentEvent(operationName, identifierFromMutateDocumentOperationVariables(variables));\n\treturn result;\n};\n//#endregion\n//#region src/hooks/init-graphql-reactor-client.ts\nfunction useInitReactorGraphqlClient(switchboardUrl = DEFAULT_SWITCHBOARD_URL, driveId = DEFAULT_DRIVE_ID) {\n\tconst [hasInit, setHasInit] = useState(false);\n\tuseEffect(() => {\n\t\tif (hasInit) return;\n\t\tinitGraphQLReactorClientWithDocumentCache(switchboardUrl, driveId).then(() => setHasInit(true)).catch(console.error);\n\t}, [hasInit]);\n\treturn hasInit;\n}\nasync function reactorGraphqlFetchDrive(identifier) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\tconst result = await client.GetDocument({ identifier });\n\tif (!result.document?.document) throw new Error(\"Could not fetch drive with id: \" + identifier);\n\treturn phDocumentFromQuery(result.document.document, DriveDocumentSchema);\n}\nasync function reactorGraphqlSyncDrive(driveId) {\n\tif (!window.ph?.reactorGraphQLClient) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\tconst drive = await reactorGraphqlFetchDrive(driveId);\n\tsetDrives([drive]);\n\tsetSelectedDrive(drive);\n}\nasync function initGraphQLReactorClientWithDocumentCache(switchboardUrl, driveId) {\n\tif (!window.ph) window.ph = {};\n\tcallEventHandlerRegisterFunctions(commonGlobalEventHandlerFunctions);\n\tsetGraphQLReactorClient(createClient(switchboardUrl, documentCacheClientMiddleware));\n\tawait reactorGraphqlSyncDrive(driveId);\n\tsetSelectedNode(void 0);\n\tsetDocumentCache(new GraphQLClientDocumentCache());\n\tforEach(graphqlEventsToSyncDrive, (name) => {\n\t\twindow.addEventListener(name, () => {\n\t\t\treactorGraphqlSyncDrive(driveId).catch(console.error);\n\t\t});\n\t});\n}\n//#endregion\n//#region src/hooks/items-in-selected-folder.ts\n/** Returns the nodes in the selected folder. */\nfunction useNodesInSelectedFolder() {\n\tconst selectedFolder = useSelectedFolder();\n\tconst nodes = useNodesInSelectedDrive();\n\tif (!selectedFolder || !nodes) return void 0;\n\treturn nodes.filter((n) => n.parentFolder === selectedFolder.id);\n}\n/** Returns the file nodes in the selected folder. */\nfunction useFileNodesInSelectedFolder() {\n\tconst nodes = useNodesInSelectedFolder();\n\tif (!nodes) return void 0;\n\treturn nodes.filter((n) => isFileNodeKind(n));\n}\n/** Returns the folder nodes in the selected folder. */\nfunction useFolderNodesInSelectedFolder() {\n\tconst nodes = useNodesInSelectedFolder();\n\tif (!nodes) return void 0;\n\treturn nodes.filter((n) => isFolderNodeKind(n));\n}\n/** Returns the documents in the selected folder. */\nfunction useDocumentsInSelectedFolder() {\n\tconst documents = useDocumentsInSelectedDrive();\n\tconst fileNodeIds = useFileNodesInSelectedFolder()?.map((node) => node.id);\n\treturn documents?.filter((d) => fileNodeIds?.includes(d.header.id));\n}\n//#endregion\n//#region src/hooks/node-actions.ts\nfunction resolveNode(driveId, node) {\n\treturn node?.id !== driveId ? node : void 0;\n}\nfunction useNodeActions() {\n\tconst [selectedDrive] = useSelectedDriveSafe();\n\tconst selectedFolder = useSelectedFolder();\n\tconst selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);\n\tconst selectedDriveId = selectedDrive?.header.id;\n\tconst drives = useDrives();\n\tasync function onAddFile(file, parent) {\n\t\tif (!selectedDriveId) return;\n\t\treturn addFile(file, selectedDriveId, file.name.replace(/\\..+/gim, \"\"), resolveNode(selectedDriveId, parent)?.id);\n\t}\n\tasync function onAddFolder(name, parent) {\n\t\tif (!selectedDriveId) return;\n\t\treturn addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);\n\t}\n\tasync function onRenameNode(newName, node) {\n\t\tif (!selectedDriveId) return;\n\t\tif (!resolveNode(selectedDriveId, node)) {\n\t\t\tconsole.error(`Node ${node.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\treturn await renameNode(selectedDriveId, node.id, newName);\n\t}\n\tasync function onCopyNode(src, target) {\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedSrc = resolveNode(selectedDriveId, src);\n\t\tif (!resolvedSrc) {\n\t\t\tconsole.error(`Node ${src.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\tawait copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, target));\n\t}\n\tasync function onMoveNode(src, target) {\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedSrc = resolveNode(selectedDriveId, src);\n\t\tif (!resolvedSrc) {\n\t\t\tconsole.error(`Node ${src.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\tconst resolvedTarget = resolveNode(selectedDriveId, target);\n\t\tif (!resolvedTarget?.id && !src.parentFolder || resolvedTarget?.id === src.parentFolder) return;\n\t\tawait moveNode$1(selectedDriveId, resolvedSrc, resolvedTarget);\n\t}\n\tasync function onDuplicateNode(src) {\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedSrc = resolveNode(selectedDriveId, src);\n\t\tif (!resolvedSrc) {\n\t\t\tconsole.error(`Node ${src.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\tawait copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder));\n\t}\n\tasync function onAddAndSelectNewFolder(name) {\n\t\tif (!name) return;\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedTarget = resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder);\n\t\tif (!resolvedTarget) return;\n\t\tconst newFolder = await onAddFolder(name, resolvedTarget);\n\t\tif (newFolder) setSelectedNode(newFolder);\n\t}\n\tasync function onRenameDriveNodes(newName, nodeId) {\n\t\tif (!drives) return;\n\t\tconst drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));\n\t\tawait Promise.all(drivesWithNode.map((drive) => renameDriveNode(drive.header.id, nodeId, newName)));\n\t}\n\treturn {\n\t\tonAddFile,\n\t\tonAddFolder,\n\t\tonRenameNode,\n\t\tonCopyNode,\n\t\tonMoveNode,\n\t\tonDuplicateNode,\n\t\tonAddAndSelectNewFolder,\n\t\tonRenameDriveNodes\n\t};\n}\n//#endregion\n//#region src/hooks/node-by-id.ts\n/** Returns a node in the selected drive by id. */\nfunction useNodeById(id) {\n\treturn useNodesInSelectedDrive()?.find((n) => n.id === id);\n}\n//#endregion\n//#region src/hooks/node-path.ts\n/** Returns the path to a node in the selected drive */\nfunction useNodePathById(id) {\n\tconst nodes = useNodesInSelectedDrive();\n\tif (!nodes) return [];\n\tconst path = [];\n\tlet current = nodes.find((n) => n.id === id);\n\twhile (current) {\n\t\tpath.push(current);\n\t\tif (!current.parentFolder) break;\n\t\tcurrent = nodes.find((n) => n.id === current?.parentFolder);\n\t}\n\treturn path.reverse();\n}\n/** Returns the path to the currently selected node in the selected drive. */\nfunction useSelectedNodePath() {\n\treturn useNodePathById(useSelectedNode()?.id);\n}\n//#endregion\n//#region src/hooks/parent-folder.ts\nfunction useNodeParentFolderById(id) {\n\treturn useFolderById(useNodeById(id)?.parentFolder);\n}\nfunction useParentFolderForSelectedNode() {\n\treturn useNodeParentFolderById(useSelectedNode()?.id);\n}\n//#endregion\n//#region src/hooks/selected-document.ts\n/** Returns the selected document id */\nfunction useSelectedDocumentId() {\n\tconst selectedNode = useSelectedNode();\n\treturn selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;\n}\n/** Returns the selected document. */\nfunction useSelectedDocument() {\n\tconst [document, dispatch] = useDocumentById(useSelectedDocumentId());\n\tif (!document) throw new NoSelectedDocumentError();\n\treturn [document, dispatch];\n}\n/** Returns the selected document. */\nfunction useSelectedDocumentSafe() {\n\treturn useDocumentById(useSelectedDocumentId());\n}\nfunction useSelectedDocumentOfType(documentType) {\n\tconst documentId = useSelectedDocumentId();\n\tif (!documentType) return [];\n\tif (!documentId) throw new NoSelectedDocumentError();\n\treturn useDocumentOfType(documentId, documentType);\n}\n//#endregion\n//#region src/hooks/subgraph-modules.ts\nfunction useSubgraphModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.subgraphs || []);\n}\n//#endregion\n//#region src/hooks/theme.ts\nconst STORED_THEME_KEY = \"ph:theme\";\nconst UPDATE_STORED_THEME = \"ph:updateStoredTheme\";\nconst STORED_THEME_UPDATED = \"ph:storedThemeUpdated\";\nconst SYSTEM_THEME_UPDATED = \"ph:systemThemeUpdated\";\nconst isServer = typeof window === \"undefined\";\nfunction setStoredTheme(storedTheme) {\n\tif (isServer) return;\n\tlocalStorage.setItem(STORED_THEME_KEY, storedTheme);\n}\nfunction setTheme(storedTheme) {\n\tif (isServer) return;\n\tconst updateStoredThemeEvent = new CustomEvent(UPDATE_STORED_THEME, { detail: { storedTheme } });\n\twindow.dispatchEvent(updateStoredThemeEvent);\n}\nfunction handleUpdateStoredTheme(event) {\n\tif (isServer) return;\n\tconst storedTheme = event.detail.storedTheme;\n\tsetStoredTheme(storedTheme);\n\tconst storedThemeUpdatedEvent = new CustomEvent(STORED_THEME_UPDATED, { detail: { storedTheme } });\n\twindow.dispatchEvent(storedThemeUpdatedEvent);\n}\nfunction getStoredTheme() {\n\tif (isServer) return void 0;\n\treturn localStorage.getItem(STORED_THEME_KEY) ?? void 0;\n}\nfunction getPrefersDarkMediaQuery() {\n\tif (isServer) return;\n\treturn window.matchMedia(\"(prefers-color-scheme: dark)\");\n}\nfunction getPrefersDark() {\n\tif (isServer) return false;\n\tif (getPrefersDarkMediaQuery()?.matches) return true;\n\treturn false;\n}\nfunction getSystemTheme() {\n\tif (isServer) return \"light\";\n\tif (getPrefersDark()) return \"dark\";\n\treturn \"light\";\n}\nfunction handleSystemThemeChange(event) {\n\tconst systemTheme = event.matches ? \"dark\" : \"light\";\n\tconst systemThemeUpdatedEvent = new CustomEvent(SYSTEM_THEME_UPDATED, { detail: { systemTheme } });\n\twindow.dispatchEvent(systemThemeUpdatedEvent);\n}\nfunction toggleDark(isDark) {\n\tif (isServer) return;\n\tdocument.documentElement.classList.toggle(\"dark\", isDark);\n}\nfunction initTheme() {\n\tif (isServer) return;\n\tuseEffect(() => {\n\t\twindow.addEventListener(UPDATE_STORED_THEME, handleUpdateStoredTheme);\n\t\tconst prefersDarkMediaQuery = getPrefersDarkMediaQuery();\n\t\tprefersDarkMediaQuery?.addEventListener(\"change\", handleSystemThemeChange);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(UPDATE_STORED_THEME, handleUpdateStoredTheme);\n\t\t\tprefersDarkMediaQuery?.removeEventListener(\"change\", handleSystemThemeChange);\n\t\t};\n\t}, []);\n}\nfunction subscribeToStoredTheme(onStoreChange) {\n\tif (isServer) return () => {};\n\twindow.addEventListener(STORED_THEME_UPDATED, onStoreChange);\n\treturn () => {\n\t\twindow.removeEventListener(STORED_THEME_UPDATED, onStoreChange);\n\t};\n}\nfunction subscribeToSystemTheme(onStoreChange) {\n\tif (isServer) return () => {};\n\twindow.addEventListener(SYSTEM_THEME_UPDATED, onStoreChange);\n\treturn () => {\n\t\twindow.removeEventListener(SYSTEM_THEME_UPDATED, onStoreChange);\n\t};\n}\nfunction useTheme() {\n\tconst storedTheme = useSyncExternalStore(subscribeToStoredTheme, () => getStoredTheme(), () => \"system\");\n\tconst systemTheme = useSyncExternalStore(subscribeToSystemTheme, () => getSystemTheme(), () => \"light\");\n\tconst isSystem = storedTheme === void 0 || storedTheme === \"system\";\n\tconst theme = isSystem ? systemTheme : storedTheme;\n\tconst isDark = theme === \"dark\";\n\tuseEffect(() => {\n\t\ttoggleDark(isDark);\n\t}, [isDark]);\n\treturn {\n\t\ttheme,\n\t\tisSystem,\n\t\tsetTheme\n\t};\n}\n//#endregion\n//#region src/hooks/use-drive-system-info.ts\nfunction deriveSystemUrl(channelUrl) {\n\ttry {\n\t\tconst url = new URL(channelUrl);\n\t\turl.search = \"\";\n\t\turl.hash = \"\";\n\t\tif (url.pathname.endsWith(\"/graphql/r\")) url.pathname = url.pathname.slice(0, -10) + \"/graphql/system\";\n\t\telse url.pathname = \"/graphql/system\";\n\t\treturn url.toString();\n\t} catch {\n\t\treturn null;\n\t}\n}\nconst cache = /* @__PURE__ */ new Map();\nfunction useDriveSystemInfo(drive) {\n\tconst remotes = useSyncList();\n\tconst driveId = drive?.header.id;\n\tconst systemUrl = useMemo(() => {\n\t\tif (!driveId) return null;\n\t\tconst channelUrl = (remotes.find((r) => r.collectionId.equals(DriveCollectionId$1.forDrive(driveId)))?.channel)?.config.url;\n\t\tif (typeof channelUrl !== \"string\") return null;\n\t\treturn deriveSystemUrl(channelUrl);\n\t}, [remotes, driveId]);\n\tconst [state, setState] = useState(() => systemUrl ? cache.get(systemUrl) ?? { status: \"loading\" } : { status: \"local\" });\n\tuseEffect(() => {\n\t\tif (!systemUrl) {\n\t\t\tsetState({ status: \"local\" });\n\t\t\treturn;\n\t\t}\n\t\tconst cached = cache.get(systemUrl);\n\t\tif (cached && cached.status !== \"loading\") {\n\t\t\tsetState(cached);\n\t\t\treturn;\n\t\t}\n\t\tsetState({ status: \"loading\" });\n\t\tcache.set(systemUrl, { status: \"loading\" });\n\t\tconst controller = new AbortController();\n\t\tfetch(systemUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ query: \"{ system { version gitHash gitUrl } }\" }),\n\t\t\tsignal: controller.signal\n\t\t}).then(async (res) => {\n\t\t\tconst json = await res.json();\n\t\t\tif (json.errors?.length) throw new Error(json.errors.map((e) => e.message).join(\"; \"));\n\t\t\tconst sys = json.data?.system;\n\t\t\tif (!sys) throw new Error(\"Missing system in response\");\n\t\t\tconst next = {\n\t\t\t\tstatus: \"ready\",\n\t\t\t\tversion: sys.version,\n\t\t\t\tgitHash: sys.gitHash,\n\t\t\t\tgitUrl: sys.gitUrl ?? null,\n\t\t\t\thost: new URL(systemUrl).host\n\t\t\t};\n\t\t\tcache.set(systemUrl, next);\n\t\t\tsetState(next);\n\t\t}).catch((err) => {\n\t\t\tif (controller.signal.aborted) return;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tconsole.error(message);\n\t\t\tconst next = {\n\t\t\t\tstatus: \"error\",\n\t\t\t\tmessage\n\t\t\t};\n\t\t\tcache.set(systemUrl, next);\n\t\t\tsetState(next);\n\t\t});\n\t\treturn () => controller.abort();\n\t}, [systemUrl]);\n\treturn state;\n}\n//#endregion\n//#region src/hooks/use-editor-file-drop.ts\nconst hasFiles = (event) => event.dataTransfer.types.includes(\"Files\");\nconst filterByExtension = (files, accept) => {\n\tconst all = Array.from(files);\n\tif (!accept || accept.length === 0) return all;\n\tconst lowerAccept = accept.map((ext) => ext.toLowerCase());\n\treturn all.filter((file) => {\n\t\tconst lower = file.name.toLowerCase();\n\t\treturn lowerAccept.some((ext) => lower.endsWith(ext));\n\t});\n};\nfunction useEditorFileDrop(options) {\n\tconst { accept, onFiles } = options;\n\tconst [isDragOver, setIsDragOver] = useState(false);\n\tconst depthRef = useRef(0);\n\tconst onDragOver = useCallback((event) => {\n\t\tif (!hasFiles(event)) return;\n\t\tevent.preventDefault();\n\t}, []);\n\treturn {\n\t\tdragProps: {\n\t\t\tonDragEnter: useCallback((event) => {\n\t\t\t\tif (!hasFiles(event)) return;\n\t\t\t\tdepthRef.current += 1;\n\t\t\t\tif (depthRef.current === 1) setIsDragOver(true);\n\t\t\t}, []),\n\t\t\tonDragOver,\n\t\t\tonDragLeave: useCallback((event) => {\n\t\t\t\tif (!hasFiles(event)) return;\n\t\t\t\tdepthRef.current = Math.max(0, depthRef.current - 1);\n\t\t\t\tif (depthRef.current === 0) setIsDragOver(false);\n\t\t\t}, []),\n\t\t\tonDrop: useCallback((event) => {\n\t\t\t\tif (!hasFiles(event)) return;\n\t\t\t\tevent.preventDefault();\n\t\t\t\tdepthRef.current = 0;\n\t\t\t\tsetIsDragOver(false);\n\t\t\t\tconst accepted = filterByExtension(event.dataTransfer.files, accept);\n\t\t\t\tif (accepted.length === 0) return;\n\t\t\t\tonFiles(accepted);\n\t\t\t}, [accept, onFiles]),\n\t\t\t[EDITOR_FILE_DROP_OPT_OUT_ATTR]: \"\"\n\t\t},\n\t\tisDragOver\n\t};\n}\n//#endregion\n//#region src/utils/drives.ts\nconst syncStatusToUI = {\n\t[SyncStatus.Synced]: \"SUCCESS\",\n\t[SyncStatus.Outgoing]: \"SYNCING\",\n\t[SyncStatus.Incoming]: \"SYNCING\",\n\t[SyncStatus.OutgoingAndIncoming]: \"SYNCING\",\n\t[SyncStatus.Error]: \"ERROR\"\n};\nasync function getDrives(reactor) {\n\treturn (await reactor.find({ type: \"powerhouse/document-drive\" })).results;\n}\nfunction getSyncStatus(documentId, sharingType) {\n\treturn Promise.resolve(getSyncStatusSync(documentId, sharingType));\n}\nfunction getSyncStatusSync(documentId, sharingType) {\n\tif (sharingType === \"LOCAL\") return;\n\tconst syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n\tif (!syncManager) return;\n\tconst status = syncManager.getSyncStatus(documentId);\n\tif (status === void 0) return;\n\treturn syncStatusToUI[status];\n}\n//#endregion\n//#region src/utils/get-revision-from-date.ts\nconst getRevisionFromDate = (startDate, endDate, operations = []) => {\n\tif (!startDate || !endDate) return 0;\n\tconst operation = operations.find((operation) => {\n\t\tconst operationDate = new Date(operation.timestampUtcMs);\n\t\treturn operationDate >= startDate && operationDate <= endDate;\n\t});\n\treturn operation ? operation.index : 0;\n};\n//#endregion\n//#region src/utils/switchboard.ts\nasync function getDriveIdBySlug(driveUrl, slug) {\n\tif (!driveUrl) return;\n\tconst urlParts = driveUrl.split(\"/\");\n\turlParts.pop();\n\turlParts.pop();\n\turlParts.push(\"drives\");\n\tconst drivesUrl = urlParts.join(\"/\");\n\treturn (await (await fetch(drivesUrl, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({\n\t\t\tquery: `\n query getDriveIdBySlug($slug: String!) {\n driveIdBySlug(slug: $slug)\n }\n `,\n\t\t\tvariables: { slug }\n\t\t})\n\t})).json()).data.driveIdBySlug;\n}\nfunction getSlugFromDriveUrl(driveUrl) {\n\treturn driveUrl.split(\"/\").pop();\n}\nfunction getSwitchboardGatewayUrlFromDriveUrl(driveUrl) {\n\tconst urlParts = driveUrl.split(\"/\");\n\turlParts.pop();\n\turlParts.pop();\n\turlParts.push(\"graphql\");\n\treturn urlParts.join(\"/\");\n}\nfunction getDocumentGraphqlQuery() {\n\tconst loc = GetDocumentWithOperationsDocument.loc;\n\tif (!loc) throw new Error(\"GetDocumentWithOperationsDocument is misconfigured, loc is missing.\");\n\treturn loc.source.body;\n}\nfunction buildDocumentSubgraphQuery(identifier, authToken) {\n\tconst query = getDocumentGraphqlQuery();\n\tconst variables = { identifier };\n\tconst headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;\n\tconst payload = {\n\t\tdocument: query.trim(),\n\t\tvariables: JSON.stringify(variables, null, 2)\n\t};\n\tif (headers) payload.headers = JSON.stringify(headers);\n\treturn lzString.compressToEncodedURIComponent(JSON.stringify(payload));\n}\nfunction buildDocumentSubgraphUrl(driveUrl, identifier, authToken) {\n\treturn `${driveUrl}?explorerURLState=${buildDocumentSubgraphQuery(identifier, authToken)}`;\n}\n//#endregion\n//#region src/hooks/use-get-switchboard-link.ts\n/**\n* Hook that returns a function to generate a document's switchboard URL.\n* Only returns a function for documents in remote drives.\n* Returns null for local drives or when the document/drive cannot be determined.\n*\n* The returned function generates a fresh bearer token and builds the switchboard URL\n* with authentication when called.\n*\n* @param document - The document to create a switchboard URL generator for\n* @returns An async function that returns the switchboard URL, or null if not applicable\n*/\nfunction useGetSwitchboardLink(document) {\n\tconst [drive] = useSelectedDriveSafe();\n\tconst remotes = useSyncList();\n\tconst isRemoteDrive = useMemo(() => {\n\t\tif (!isDefined(drive)) return false;\n\t\treturn remotes.some((remote) => remote.collectionId.equals(DriveCollectionId$1.forDrive(drive.header.id)));\n\t}, [remotes, drive]);\n\tconst remoteUrl = useMemo(() => {\n\t\tif (!isDefined(drive)) return null;\n\t\ttry {\n\t\t\tconst channelUrl = (remotes.find((remote) => remote.collectionId.equals(DriveCollectionId$1.forDrive(drive.header.id)))?.channel)?.config.url;\n\t\t\tif (typeof channelUrl === \"string\") return channelUrl;\n\t\t\treturn null;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error determining remote URL:\", error);\n\t\t\treturn null;\n\t\t}\n\t}, [remotes, drive]);\n\tconst renown = useRenown();\n\tconst user = useUser();\n\treturn useMemo(() => {\n\t\tif (!isRemoteDrive || !document?.header.id || !remoteUrl) return null;\n\t\treturn async () => {\n\t\t\tconst token = user?.address ? await renown?.getBearerToken({\n\t\t\t\texpiresIn: 600,\n\t\t\t\taud: remoteUrl\n\t\t\t}) : void 0;\n\t\t\treturn buildDocumentSubgraphUrl(remoteUrl, document.header.id, token);\n\t\t};\n\t}, [\n\t\tisRemoteDrive,\n\t\tremoteUrl,\n\t\tdocument,\n\t\tuser,\n\t\trenown\n\t]);\n}\n//#endregion\n//#region src/hooks/use-on-drop-file.ts\nconst useOnDropFile = (documentTypesOverride) => {\n\tconst selectedDriveId = useSelectedDriveId();\n\tconst selectedFolder = useSelectedFolder();\n\tconst documentTypes = useDocumentTypes();\n\tconst onDropFile = async (file, onProgress, resolveConflict) => {\n\t\tif (!selectedDriveId) {\n\t\t\tconsole.warn(\"No selected drive - upload skipped\");\n\t\t\treturn;\n\t\t}\n\t\tconst fileName = file.name.replace(/\\..+/gim, \"\");\n\t\tconst targetNodeId = selectedFolder?.id;\n\t\treturn await addFileWithProgress(file, selectedDriveId, fileName, targetNodeId, onProgress, documentTypesOverride ?? documentTypes, resolveConflict);\n\t};\n\treturn onDropFile;\n};\n//#endregion\n//#region src/hooks/user-permissions.ts\nfunction useUserPermissions() {\n\tconst user = useUser();\n\tconst allowList = useAllowList();\n\tif (!allowList) return {\n\t\tisAllowedToCreateDocuments: true,\n\t\tisAllowedToEditDocuments: true\n\t};\n\treturn {\n\t\tisAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n\t\tisAllowedToEditDocuments: allowList.includes(user?.address ?? \"\")\n\t};\n}\n//#endregion\n//#region src/hooks/use-attachments.ts\n/** Returns an IAttachmentClient wrapping the current IAttachmentService, or undefined if none is set. */\nfunction useAttachments() {\n\tconst service = useAttachmentService();\n\treturn useMemo(() => service ? createAttachmentClient(service) : void 0, [service]);\n}\n/** Upload lifecycle status. progress is coarse (0 before/during, 1 on Done) because RemoteAttachmentUpload buffers the full body before issuing a single PUT. */\nlet UploadStatus = /* @__PURE__ */ function(UploadStatus) {\n\tUploadStatus[\"None\"] = \"None\";\n\tUploadStatus[\"Hashing\"] = \"Hashing\";\n\tUploadStatus[\"Uploading\"] = \"Uploading\";\n\tUploadStatus[\"Done\"] = \"Done\";\n\tUploadStatus[\"Error\"] = \"Error\";\n\treturn UploadStatus;\n}({});\n/** Hook for managing the full attachment preprocess + upload lifecycle. preprocess and upload callbacks are stable (useCallback) and depend only on the current IAttachmentClient reference. */\nfunction useAttachmentUpload() {\n\tconst [status, setStatus] = useState(UploadStatus.None);\n\tconst [progress, setProgress] = useState(0);\n\tconst [error, setError] = useState(void 0);\n\tconst client = useAttachments();\n\treturn {\n\t\tpreprocess: useCallback(async (file) => {\n\t\t\tif (!client) throw new Error(\"AttachmentClient not available\");\n\t\t\tsetError(void 0);\n\t\t\tsetStatus(UploadStatus.Hashing);\n\t\t\ttry {\n\t\t\t\treturn await client.preprocess(file);\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err : new Error(String(err)));\n\t\t\t\tsetStatus(UploadStatus.Error);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}, [client]),\n\t\tupload: useCallback(async (results) => {\n\t\t\tif (!client) throw new Error(\"AttachmentClient not available\");\n\t\t\tsetError(void 0);\n\t\t\tsetStatus(UploadStatus.Uploading);\n\t\t\tsetProgress(0);\n\t\t\ttry {\n\t\t\t\tawait client.reserve(results.options, (handle) => handle.send(results.stream()));\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err : new Error(String(err)));\n\t\t\t\tsetStatus(UploadStatus.Error);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tsetProgress(1);\n\t\t\tsetStatus(UploadStatus.Done);\n\t\t}, [client]),\n\t\tstatus,\n\t\tprogress,\n\t\terror\n\t};\n}\n//#endregion\n//#region src/pglite/drop.ts\nasync function dropTablesInSchema(pg, schema) {\n\tawait pg.exec(`\nDO $$\nDECLARE\n _schemaname text := '${schema}';\n _tablename text;\nBEGIN\n FOR _tablename IN SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = _schemaname LOOP\n RAISE INFO 'Dropping table %.%', _schemaname, _tablename;\n EXECUTE format('DROP TABLE %I.%I CASCADE;', _schemaname, _tablename);\n END LOOP;\n IF NOT FOUND THEN\n RAISE WARNING 'Schema % does not exist', _schemaname;\n END IF;\nEND $$;\n`);\n}\nasync function truncateAllTables(pg, schema = REACTOR_SCHEMA$1) {\n\tawait dropTablesInSchema(pg, schema);\n}\nasync function dropAllReactorStorage(pg) {\n\tawait dropTablesInSchema(pg, REACTOR_SCHEMA$1);\n\tawait dropTablesInSchema(pg, \"public\");\n}\n//#endregion\n//#region src/reactor.ts\nconst DEFAULT_DEBOUNCE_DELAY_MS = 200;\nconst DEFAULT_IMMEDIATE_THRESHOLD_MS = 1e3;\nasync function _refreshReactorData(reactor) {\n\tsetDrives(await getDrives(reactor));\n}\nasync function _refreshReactorDataClient(reactor) {\n\tif (!reactor) return;\n\tsetDrives((await reactor.find({ type: \"powerhouse/document-drive\" })).results);\n}\nfunction createDebouncedRefreshReactorData(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {\n\tlet timeout = null;\n\tlet lastRefreshTime = 0;\n\treturn (reactor, immediate = false) => {\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastRefresh = now - lastRefreshTime;\n\t\tif (timeout !== null) clearTimeout(timeout);\n\t\tif (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n\t\t\tlastRefreshTime = now;\n\t\t\treturn _refreshReactorData(reactor);\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tlastRefreshTime = Date.now();\n\t\t\t\t_refreshReactorData(reactor).then(resolve);\n\t\t\t}, debounceDelayMs);\n\t\t});\n\t};\n}\nfunction createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {\n\tlet timeout = null;\n\tlet lastRefreshTime = 0;\n\treturn (reactor, immediate = false) => {\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastRefresh = now - lastRefreshTime;\n\t\tif (timeout !== null) clearTimeout(timeout);\n\t\tif (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n\t\t\tlastRefreshTime = now;\n\t\t\treturn _refreshReactorDataClient(reactor);\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tlastRefreshTime = Date.now();\n\t\t\t\t_refreshReactorDataClient(reactor).then(resolve);\n\t\t\t}, debounceDelayMs);\n\t\t});\n\t};\n}\nconst refreshReactorData = createDebouncedRefreshReactorData();\nconst refreshReactorDataClient = createDebouncedRefreshReactorDataClient();\n//#endregion\n//#region src/registry/fetchers.ts\nfunction trimTrailingSlash(url) {\n\treturn url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\nasync function getPackages(registryUrl) {\n\tconst res = await fetch(`${trimTrailingSlash(registryUrl)}/packages`);\n\tif (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n\treturn await res.json();\n}\nasync function getPackagesByDocumentType(registryUrl, documentType) {\n\tconst encodedType = encodeURIComponent(documentType);\n\tconst res = await fetch(`${trimTrailingSlash(registryUrl)}/packages/by-document-type?type=${encodedType}`);\n\tif (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n\treturn await res.json();\n}\n//#endregion\n//#region src/registry/client.ts\nfunction cdnUrlToApiUrl(cdnUrl) {\n\treturn cdnUrl.replace(/\\/-\\/cdn\\/?$/, \"\");\n}\nvar RegistryClient = class {\n\tapiUrl;\n\tconstructor(cdnUrl) {\n\t\tthis.apiUrl = cdnUrlToApiUrl(cdnUrl);\n\t}\n\tasync getPackages() {\n\t\treturn await getPackages(this.apiUrl);\n\t}\n\tasync getPackagesByDocumentType(documentType) {\n\t\treturn await getPackagesByDocumentType(this.apiUrl, documentType);\n\t}\n\tasync searchPackages(query) {\n\t\tconst packages = await this.getPackages();\n\t\tif (!query) return packages;\n\t\tconst lowerQuery = query.toLowerCase();\n\t\treturn packages.filter((pkg) => pkg.name.toLowerCase().includes(lowerQuery) || pkg.manifest?.description?.toLowerCase().includes(lowerQuery));\n\t}\n\tonPublish(callback) {\n\t\tconst eventSource = new EventSource(`${this.apiUrl}/-/events`);\n\t\teventSource.addEventListener(\"publish\", (e) => {\n\t\t\tcallback(JSON.parse(e.data));\n\t\t});\n\t\treturn () => {\n\t\t\teventSource.close();\n\t\t};\n\t}\n};\n//#endregion\n//#region src/remote-controller/action-tracker.ts\n/**\n* Tracks pending actions with their operation context (prevOpHash, prevOpIndex).\n* Actions are accumulated until flushed (on push).\n*/\nvar ActionTracker = class {\n\tpending = [];\n\t/** Track a new action with its operation context. */\n\ttrack(action, prevOpHash, prevOpIndex) {\n\t\tthis.pending.push({\n\t\t\taction,\n\t\t\tprevOpHash,\n\t\t\tprevOpIndex\n\t\t});\n\t}\n\t/** Flush all pending actions and return them. Clears the internal queue. */\n\tflush() {\n\t\tconst actions = this.pending;\n\t\tthis.pending = [];\n\t\treturn actions;\n\t}\n\t/** Number of pending actions. */\n\tget count() {\n\t\treturn this.pending.length;\n\t}\n\t/** Prepend previously flushed actions back to the queue (for retry on failure). */\n\trestore(actions) {\n\t\tthis.pending = [...actions, ...this.pending];\n\t}\n\t/** Clear all pending actions without returning them. */\n\tclear() {\n\t\tthis.pending = [];\n\t}\n};\n//#endregion\n//#region src/remote-controller/remote-client.ts\n/**\n* Thin facade over the GraphQL SDK for remote document operations.\n*/\nconst DEFAULT_PAGE_SIZE = 100;\nvar RemoteClient = class {\n\tpageSize;\n\tconstructor(client, pageSize) {\n\t\tthis.client = client;\n\t\tthis.pageSize = pageSize ?? DEFAULT_PAGE_SIZE;\n\t}\n\t/** Fetch a document by identifier. Returns null if not found. */\n\tasync getDocument(identifier, branch) {\n\t\treturn (await this.client.GetDocument({\n\t\t\tidentifier,\n\t\t\tview: branch ? { branch } : void 0\n\t\t})).document ?? null;\n\t}\n\t/**\n\t* Fetch a document and its operations.\n\t*\n\t* When scopes are provided and BatchGetDocumentWithOperations is available,\n\t* fetches the document and per-scope operations in a single HTTP request.\n\t* Otherwise falls back to GetDocumentWithOperations for the first page,\n\t* then paginates remaining operations per scope.\n\t*/\n\tasync getDocumentWithOperations(identifier, branch, sinceRevision, scopes) {\n\t\tif (this.client.BatchGetDocumentWithOperations && scopes && scopes.length > 0) return this.batchGetDocumentWithOperations(identifier, branch, sinceRevision, scopes);\n\t\tconst result = await this.client.GetDocumentWithOperations({\n\t\t\tidentifier,\n\t\t\tview: branch ? { branch } : void 0,\n\t\t\toperationsPaging: {\n\t\t\t\tlimit: this.pageSize,\n\t\t\t\tcursor: null\n\t\t\t}\n\t\t});\n\t\tif (!result.document) return null;\n\t\tconst doc = result.document.document;\n\t\tconst opsPage = doc.operations;\n\t\tconst operationsByScope = {};\n\t\tif (opsPage) for (const op of opsPage.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\tconst expectedTotal = doc.revisionsList.reduce((sum, r) => sum + r.revision, 0);\n\t\tif ((opsPage?.items.length ?? 0) >= expectedTotal) return {\n\t\t\tdocument: doc,\n\t\t\tchildIds: result.document.childIds,\n\t\t\toperations: { operationsByScope }\n\t\t};\n\t\tconst allScopes = doc.revisionsList.map((r) => r.scope);\n\t\tconst allOps = await this.getAllOperations(doc.id, branch, sinceRevision, allScopes);\n\t\treturn {\n\t\t\tdocument: doc,\n\t\t\tchildIds: result.document.childIds,\n\t\t\toperations: allOps\n\t\t};\n\t}\n\t/**\n\t* Fetch document + per-scope operations in a single HTTP request\n\t* via BatchGetDocumentWithOperations, then paginate any remaining pages.\n\t*/\n\tasync batchGetDocumentWithOperations(identifier, branch, sinceRevision, scopes) {\n\t\tconst view = branch ? { branch } : void 0;\n\t\tconst filters = scopes.map((scope) => ({\n\t\t\tdocumentId: identifier,\n\t\t\tbranch: branch ?? null,\n\t\t\tsinceRevision: sinceRevision?.[scope] ?? 0,\n\t\t\tscopes: [scope]\n\t\t}));\n\t\tconst pagings = scopes.map(() => ({\n\t\t\tlimit: this.pageSize,\n\t\t\tcursor: null\n\t\t}));\n\t\tconst result = await this.client.BatchGetDocumentWithOperations(identifier, view, filters, pagings);\n\t\tif (!result.document) return null;\n\t\tconst operationsByScope = {};\n\t\tlet pending = [];\n\t\tfor (let i = 0; i < scopes.length; i++) {\n\t\t\tconst page = result.operations[i];\n\t\t\tfor (const op of page.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\t\tif (page.hasNextPage && page.cursor) pending.push({\n\t\t\t\tscope: scopes[i],\n\t\t\t\tfilter: filters[i],\n\t\t\t\tcursor: page.cursor\n\t\t\t});\n\t\t}\n\t\twhile (pending.length > 0) {\n\t\t\tconst pages = await this.fetchOperationPages(pending.map((p) => p.filter), pending.map((p) => ({\n\t\t\t\tlimit: this.pageSize,\n\t\t\t\tcursor: p.cursor\n\t\t\t})));\n\t\t\tconst nextPending = [];\n\t\t\tfor (let i = 0; i < pending.length; i++) {\n\t\t\t\tconst page = pages[i];\n\t\t\t\tfor (const op of page.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\t\t\tif (page.hasNextPage && page.cursor) nextPending.push({\n\t\t\t\t\t...pending[i],\n\t\t\t\t\tcursor: page.cursor\n\t\t\t\t});\n\t\t\t}\n\t\t\tpending = nextPending;\n\t\t}\n\t\treturn {\n\t\t\tdocument: result.document.document,\n\t\t\tchildIds: result.document.childIds,\n\t\t\toperations: { operationsByScope }\n\t\t};\n\t}\n\t/**\n\t* Fetch all operations for a document, paginating through all pages.\n\t* Each scope is queried individually because the API only returns\n\t* pagination cursors for single-scope queries.\n\t*/\n\tasync getAllOperations(documentId, branch, sinceRevision, scopes) {\n\t\tif (scopes && scopes.length > 0) {\n\t\t\tconst operationsByScope = {};\n\t\t\tlet pending = scopes.map((scope) => ({\n\t\t\t\tscope,\n\t\t\t\tfilter: {\n\t\t\t\t\tdocumentId,\n\t\t\t\t\tbranch: branch ?? null,\n\t\t\t\t\tsinceRevision: sinceRevision?.[scope] ?? 0,\n\t\t\t\t\tscopes: [scope]\n\t\t\t\t},\n\t\t\t\tcursor: null\n\t\t\t}));\n\t\t\twhile (pending.length > 0) {\n\t\t\t\tconst pages = await this.fetchOperationPages(pending.map((p) => p.filter), pending.map((p) => ({\n\t\t\t\t\tlimit: this.pageSize,\n\t\t\t\t\tcursor: p.cursor\n\t\t\t\t})));\n\t\t\t\tconst nextPending = [];\n\t\t\t\tfor (let i = 0; i < pending.length; i++) {\n\t\t\t\t\tconst page = pages[i];\n\t\t\t\t\tfor (const op of page.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\t\t\t\tif (page.hasNextPage && page.cursor) nextPending.push({\n\t\t\t\t\t\t...pending[i],\n\t\t\t\t\t\tcursor: page.cursor\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tpending = nextPending;\n\t\t\t}\n\t\t\treturn { operationsByScope };\n\t\t}\n\t\treturn this.fetchOperationsForScope(documentId, branch);\n\t}\n\t/**\n\t* Fetch one page of operations per filter.\n\t* Uses the composed query (single HTTP request) when available,\n\t* otherwise falls back to parallel individual requests.\n\t*/\n\tasync fetchOperationPages(filters, pagings) {\n\t\tif (this.client.BatchGetDocumentOperations) return this.client.BatchGetDocumentOperations(filters, pagings);\n\t\treturn Promise.all(filters.map((filter, i) => this.client.GetDocumentOperations({\n\t\t\tfilter,\n\t\t\tpaging: pagings[i]\n\t\t}).then((r) => r.documentOperations)));\n\t}\n\t/** Fetch all pages of operations for a single scope (or all scopes if none specified). */\n\tasync fetchOperationsForScope(documentId, branch, sinceRevision, scope) {\n\t\tconst operationsByScope = {};\n\t\tlet cursor;\n\t\tlet hasNextPage = true;\n\t\twhile (hasNextPage) {\n\t\t\tconst page = (await this.client.GetDocumentOperations({\n\t\t\t\tfilter: {\n\t\t\t\t\tdocumentId,\n\t\t\t\t\tbranch: branch ?? null,\n\t\t\t\t\tsinceRevision: sinceRevision ?? 0,\n\t\t\t\t\tscopes: scope ? [scope] : null\n\t\t\t\t},\n\t\t\t\tpaging: {\n\t\t\t\t\tlimit: this.pageSize,\n\t\t\t\t\tcursor: cursor ?? null\n\t\t\t\t}\n\t\t\t})).documentOperations;\n\t\t\tfor (const op of page.items) {\n\t\t\t\tconst s = op.action.scope;\n\t\t\t\t(operationsByScope[s] ??= []).push(op);\n\t\t\t}\n\t\t\thasNextPage = page.hasNextPage;\n\t\t\tcursor = page.cursor;\n\t\t}\n\t\treturn { operationsByScope };\n\t}\n\t/** Push actions to an existing document via MutateDocument. */\n\tasync pushActions(documentIdentifier, actions, branch) {\n\t\treturn (await this.client.MutateDocument({\n\t\t\tdocumentIdentifier,\n\t\t\tactions,\n\t\t\tview: branch ? { branch } : void 0\n\t\t})).mutateDocument;\n\t}\n\t/** Create a new document on the remote. */\n\tasync createDocument(document, parentIdentifier) {\n\t\treturn (await this.client.CreateDocument({\n\t\t\tdocument,\n\t\t\tparentIdentifier: parentIdentifier ?? null\n\t\t})).createDocument;\n\t}\n\t/** Create an empty document of a given type on the remote. */\n\tasync createEmptyDocument(documentType, parentIdentifier) {\n\t\treturn (await this.client.CreateEmptyDocument({\n\t\t\tdocumentType,\n\t\t\tparentIdentifier: parentIdentifier ?? null\n\t\t})).createEmptyDocument;\n\t}\n\t/** Delete a document on the remote. Returns true if successful. */\n\tasync deleteDocument(identifier, propagate) {\n\t\treturn (await this.client.DeleteDocument({\n\t\t\tidentifier,\n\t\t\tpropagate\n\t\t})).deleteDocument;\n\t}\n};\n//#endregion\n//#region src/remote-controller/utils.ts\n/** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. \"SET_MODEL_NAME\" → \"setModelName\"). */\nfunction screamingSnakeToCamel(s) {\n\treturn s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());\n}\n/** Error thrown when a push conflict is detected with the \"reject\" strategy. */\nvar ConflictError = class extends Error {\n\tconstructor(conflict) {\n\t\tsuper(\"Push conflict: remote has new operations since last pull\");\n\t\tthis.conflict = conflict;\n\t\tthis.name = \"ConflictError\";\n\t}\n};\n/** Convert a remote operation to the local Operation type. */\nfunction remoteOperationToLocal(remote) {\n\treturn {\n\t\tid: remote.id ?? \"\",\n\t\tindex: remote.index,\n\t\tskip: remote.skip,\n\t\ttimestampUtcMs: remote.timestampUtcMs,\n\t\thash: remote.hash,\n\t\terror: remote.error ?? void 0,\n\t\taction: {\n\t\t\tid: remote.action.id,\n\t\t\ttype: remote.action.type,\n\t\t\ttimestampUtcMs: remote.action.timestampUtcMs,\n\t\t\tinput: remote.action.input,\n\t\t\tscope: remote.action.scope,\n\t\t\tcontext: remote.action.context?.signer ? { signer: {\n\t\t\t\tuser: remote.action.context.signer.user ?? {\n\t\t\t\t\taddress: \"\",\n\t\t\t\t\tnetworkId: \"\",\n\t\t\t\t\tchainId: 0\n\t\t\t\t},\n\t\t\t\tapp: remote.action.context.signer.app ?? {\n\t\t\t\t\tname: \"\",\n\t\t\t\t\tkey: \"\"\n\t\t\t\t},\n\t\t\t\tsignatures: remote.action.context.signer.signatures.map((s) => deserializeSignature(s))\n\t\t\t} } : void 0\n\t\t}\n\t};\n}\n/**\n* Deserialize a signature string back to a 5-element tuple.\n* The server serializes tuples via `tuple.join(\", \")`.\n*/\nfunction deserializeSignature(s) {\n\tconst parts = s.split(\", \");\n\treturn [\n\t\tparts[0] ?? \"\",\n\t\tparts[1] ?? \"\",\n\t\tparts[2] ?? \"\",\n\t\tparts[3] ?? \"\",\n\t\tparts[4] ?? \"\"\n\t];\n}\n/** Convert remote operations to local DocumentOperations format. */\nfunction convertRemoteOperations(operationsByScope) {\n\tconst operations = {};\n\tfor (const [scope, remoteOps] of Object.entries(operationsByScope)) operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));\n\treturn operations;\n}\n/** Reconstruct a PHDocument from remote document data and operations. */\nfunction buildPulledDocument(remoteDoc, operations, initialDoc, branch) {\n\treturn {\n\t\theader: {\n\t\t\t...initialDoc.header,\n\t\t\tid: remoteDoc.id,\n\t\t\tname: remoteDoc.name,\n\t\t\tslug: remoteDoc.slug ?? \"\",\n\t\t\tdocumentType: remoteDoc.documentType,\n\t\t\tcreatedAtUtcIso: typeof remoteDoc.createdAtUtcIso === \"string\" ? remoteDoc.createdAtUtcIso : remoteDoc.createdAtUtcIso.toISOString(),\n\t\t\tlastModifiedAtUtcIso: typeof remoteDoc.lastModifiedAtUtcIso === \"string\" ? remoteDoc.lastModifiedAtUtcIso : remoteDoc.lastModifiedAtUtcIso.toISOString(),\n\t\t\trevision: Object.fromEntries(remoteDoc.revisionsList.map((r) => [r.scope, r.revision])),\n\t\t\tbranch\n\t\t},\n\t\tstate: remoteDoc.state,\n\t\tinitialState: initialDoc.initialState,\n\t\toperations,\n\t\tclipboard: []\n\t};\n}\n/** Extract revision map from a remote document's revisionsList. */\nfunction extractRevisionMap(revisionsList) {\n\treturn Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));\n}\n/**\n* Check if any scope in currentRevision is ahead of knownRevision.\n* When `scopes` is provided, only those scopes are checked.\n*/\nfunction hasRevisionConflict(currentRevision, knownRevision, scopes) {\n\tfor (const scope in currentRevision) {\n\t\tif (scopes && !scopes.has(scope)) continue;\n\t\tif ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) return true;\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/remote-controller/remote-controller.ts\n/**\n* A controller that wraps a PHDocumentController with remote push/pull capabilities.\n* Composes a local controller and adds GraphQL-based sync with a reactor server.\n*/\nvar RemoteDocumentController = class RemoteDocumentController {\n\tinner;\n\tremoteClient;\n\ttracker = new ActionTracker();\n\toptions;\n\tdocumentId;\n\tremoteRevision = {};\n\thasPulled = false;\n\tpushScheduled = false;\n\tpushQueue = Promise.resolve();\n\tlisteners = [];\n\tconstructor(inner, options) {\n\t\tthis.inner = inner;\n\t\tthis.options = options;\n\t\tthis.documentId = options.documentId ?? \"\";\n\t\tthis.remoteClient = new RemoteClient(options.client, options.operationsPageSize);\n\t\tthis.setupActionInterceptors();\n\t}\n\tget header() {\n\t\treturn this.inner.header;\n\t}\n\tget state() {\n\t\treturn this.inner.state;\n\t}\n\tget operations() {\n\t\treturn this.inner.operations;\n\t}\n\tget document() {\n\t\treturn this.inner.document;\n\t}\n\tget status() {\n\t\treturn {\n\t\t\tpendingActionCount: this.tracker.count,\n\t\t\tconnected: this.documentId !== \"\",\n\t\t\tdocumentId: this.documentId,\n\t\t\tremoteRevision: { ...this.remoteRevision }\n\t\t};\n\t}\n\t/** Register a listener for document changes. Returns an unsubscribe function. */\n\tonChange(listener) {\n\t\tthis.listeners.push(listener);\n\t\treturn () => {\n\t\t\tthis.listeners = this.listeners.filter((l) => l !== listener);\n\t\t};\n\t}\n\tnotifyListeners(source) {\n\t\tif (this.listeners.length === 0) return;\n\t\tconst event = {\n\t\t\tsource,\n\t\t\tdocument: this.document\n\t\t};\n\t\tfor (const listener of this.listeners) listener(event);\n\t}\n\t/** Push all pending actions to remote, then pull latest state. */\n\tasync push() {\n\t\tlet tracked = this.tracker.flush();\n\t\tif (tracked.length === 0 && this.documentId !== \"\") return {\n\t\t\tremoteDocument: await this.pull(),\n\t\t\tactionCount: 0,\n\t\t\toperations: []\n\t\t};\n\t\ttry {\n\t\t\tawait this.ensureRemoteDocument();\n\t\t\tif (this.options.onConflict && tracked.length > 0) tracked = await this.handleConflicts(tracked, this.options.onConflict);\n\t\t} catch (error) {\n\t\t\tthis.tracker.restore(tracked);\n\t\t\tthrow error;\n\t\t}\n\t\tlet pushedActions = [];\n\t\ttry {\n\t\t\tif (tracked.length > 0) {\n\t\t\t\tconst actions = await this.prepareActionsForPush(tracked);\n\t\t\t\tpushedActions = actions;\n\t\t\t\tawait this.remoteClient.pushActions(this.documentId, actions, this.options.branch);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.tracker.restore(tracked);\n\t\t\tthrow error;\n\t\t}\n\t\treturn {\n\t\t\tremoteDocument: await this.pull(),\n\t\t\tactionCount: tracked.length,\n\t\t\toperations: pushedActions\n\t\t};\n\t}\n\t/** Delete the document on the remote. */\n\tasync delete(propagate) {\n\t\tif (this.documentId === \"\") throw new Error(\"Cannot delete: no document ID set\");\n\t\treturn await this.remoteClient.deleteDocument(this.documentId, propagate);\n\t}\n\t/** Pull latest state from remote, replacing local document. Returns the remote document data. */\n\tasync pull() {\n\t\tif (this.documentId === \"\") throw new Error(\"Cannot pull: no document ID set\");\n\t\tconst { remoteDoc, operations } = await this.fetchDocumentAndOperations();\n\t\tconst pulledDocument = buildPulledDocument(remoteDoc, operations, this.inner.module.utils.createDocument(), this.options.branch ?? \"main\");\n\t\tconst ControllerClass = this.inner.constructor;\n\t\tthis.inner = new ControllerClass(pulledDocument);\n\t\tthis.setupActionInterceptors();\n\t\tthis.tracker.clear();\n\t\tthis.remoteRevision = extractRevisionMap(remoteDoc.revisionsList);\n\t\tthis.notifyListeners(\"pull\");\n\t\treturn remoteDoc;\n\t}\n\t/**\n\t* Pull an existing document from remote and create a controller for it.\n\t*/\n\tstatic async pull(ControllerClass, options) {\n\t\tconst remote = new RemoteDocumentController(new ControllerClass(), options);\n\t\tif (options.documentId) await remote.pull();\n\t\treturn remote;\n\t}\n\t/**\n\t* Wrap an existing controller instance with remote capabilities.\n\t* Pending local actions on the inner controller are NOT tracked\n\t* (only new actions through the remote controller are tracked).\n\t*/\n\tstatic from(controller, options) {\n\t\treturn new RemoteDocumentController(controller, options);\n\t}\n\t/** Create the document on the remote if it doesn't exist yet. */\n\tasync ensureRemoteDocument() {\n\t\tif (this.documentId !== \"\") return;\n\t\tthis.documentId = (await this.remoteClient.createEmptyDocument(this.inner.header.documentType, this.options.parentIdentifier)).id;\n\t}\n\t/** Set up interceptors for all action methods on the inner controller. */\n\tsetupActionInterceptors() {\n\t\tconst module = this.inner[\"module\"];\n\t\tfor (const actionType in module.actions) {\n\t\t\tif (actionType in RemoteDocumentController.prototype) continue;\n\t\t\tObject.defineProperty(this, actionType, {\n\t\t\t\tvalue: (input) => {\n\t\t\t\t\tconst opCountsBefore = {};\n\t\t\t\t\tfor (const scope in this.inner.operations) opCountsBefore[scope] = this.inner.operations[scope].length;\n\t\t\t\t\tthis.inner[actionType](input);\n\t\t\t\t\tconst newOp = this.findNewOperation(opCountsBefore);\n\t\t\t\t\tconst prevOp = newOp ? this.getLastOperationInScope(newOp.action.scope, newOp) : void 0;\n\t\t\t\t\tconst prevOpHash = prevOp?.hash ?? \"\";\n\t\t\t\t\tconst prevOpIndex = prevOp?.index ?? -1;\n\t\t\t\t\tif (!newOp) return this;\n\t\t\t\t\tthis.tracker.track(newOp.action, prevOpHash, prevOpIndex);\n\t\t\t\t\tthis.notifyListeners(\"action\");\n\t\t\t\t\tif (this.options.mode === \"streaming\") this.schedulePush();\n\t\t\t\t\treturn this;\n\t\t\t\t},\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Find the new operation added after applying an action,\n\t* by comparing current operation counts against a previous snapshot.\n\t*/\n\tfindNewOperation(opCountsBefore) {\n\t\tconst ops = this.inner.operations;\n\t\tfor (const scope in ops) {\n\t\t\tconst scopeOps = ops[scope];\n\t\t\tconst prevCount = opCountsBefore[scope] ?? 0;\n\t\t\tif (scopeOps.length > prevCount) return scopeOps[scopeOps.length - 1];\n\t\t}\n\t}\n\t/**\n\t* Get the last operation in a specific scope, optionally excluding\n\t* a given operation (e.g. the one just added).\n\t*/\n\tgetLastOperationInScope(scope, excludeOp) {\n\t\tconst scopeOps = this.inner.operations[scope];\n\t\tif (scopeOps.length === 0) return void 0;\n\t\tfor (let i = scopeOps.length - 1; i >= 0; i--) if (scopeOps[i] !== excludeOp) return scopeOps[i];\n\t}\n\t/**\n\t* Detect and handle conflicts between local pending actions and remote state.\n\t* Returns the (possibly rebased) tracked actions to push.\n\t*/\n\tasync handleConflicts(localTracked, strategy) {\n\t\tconst remoteResult = await this.remoteClient.getDocument(this.documentId, this.options.branch);\n\t\tif (!remoteResult) throw new Error(`Document \"${this.documentId}\" not found on remote`);\n\t\tconst currentRevision = extractRevisionMap(remoteResult.document.revisionsList);\n\t\tconst localScopes = new Set(localTracked.map((t) => t.action.scope));\n\t\tif (!hasRevisionConflict(currentRevision, this.remoteRevision, localScopes)) return localTracked;\n\t\tconst conflictingScopes = [...localScopes].filter((scope) => (currentRevision[scope] ?? 0) > (this.remoteRevision[scope] ?? 0));\n\t\tconst { operationsByScope } = await this.remoteClient.getAllOperations(this.documentId, this.options.branch, this.remoteRevision, conflictingScopes);\n\t\tconst remoteOperations = {};\n\t\tfor (const [scope, ops] of Object.entries(operationsByScope)) remoteOperations[scope] = ops;\n\t\tconst conflictInfo = {\n\t\t\tremoteOperations,\n\t\t\tlocalActions: localTracked,\n\t\t\tknownRevision: { ...this.remoteRevision },\n\t\t\tcurrentRevision: { ...currentRevision }\n\t\t};\n\t\tif (strategy === \"reject\") throw new ConflictError(conflictInfo);\n\t\tif (strategy === \"rebase\") return this.pullAndReplay(localTracked.map((t) => t.action));\n\t\tconst mergedActions = await strategy(conflictInfo);\n\t\treturn this.pullAndReplay(mergedActions);\n\t}\n\t/**\n\t* Pull latest remote state and replay actions through interceptors.\n\t* Returns newly tracked actions with correct prevOpHash values.\n\t*/\n\tasync pullAndReplay(actions) {\n\t\tawait this.pull();\n\t\tfor (const action of actions) {\n\t\t\tconst methodName = screamingSnakeToCamel(action.type);\n\t\t\tconst method = this[methodName];\n\t\t\tif (typeof method === \"function\") method.call(this, action.input);\n\t\t}\n\t\treturn this.tracker.flush();\n\t}\n\t/** Prepare actions for push, optionally signing them. */\n\tasync prepareActionsForPush(tracked) {\n\t\tconst actions = [];\n\t\tfor (const { action, prevOpHash, prevOpIndex } of tracked) {\n\t\t\tlet prepared = {\n\t\t\t\t...action,\n\t\t\t\tcontext: {\n\t\t\t\t\t...action.context,\n\t\t\t\t\tprevOpHash,\n\t\t\t\t\tprevOpIndex\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (this.options.signer) prepared = await this.signAction(prepared);\n\t\t\tactions.push(prepared);\n\t\t}\n\t\treturn actions;\n\t}\n\t/** Sign an action using the configured signer, preserving existing signatures. */\n\tasync signAction(action) {\n\t\tconst signer = this.options.signer;\n\t\tconst signature = await signer.signAction(action);\n\t\tconst existingSignatures = action.context?.signer?.signatures ?? [];\n\t\treturn {\n\t\t\t...action,\n\t\t\tcontext: {\n\t\t\t\t...action.context,\n\t\t\t\tsigner: {\n\t\t\t\t\tuser: signer.user,\n\t\t\t\t\tapp: signer.app,\n\t\t\t\t\tsignatures: [...existingSignatures, signature]\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Fetch document and operations from the remote.\n\t*\n\t* On the first pull, uses the combined document+operations query.\n\t* On subsequent pulls, fetches only new operations per scope using\n\t* sinceRevision, then merges with existing local operations.\n\t* Falls back to a full fetch if the merge produces a count mismatch.\n\t*/\n\tasync fetchDocumentAndOperations() {\n\t\tif (this.hasPulled) return this.incrementalFetch();\n\t\tconst result = await this.remoteClient.getDocumentWithOperations(this.documentId, this.options.branch);\n\t\tif (!result) throw new Error(`Document \"${this.documentId}\" not found on remote`);\n\t\tthis.hasPulled = true;\n\t\treturn {\n\t\t\tremoteDoc: result.document,\n\t\t\toperations: convertRemoteOperations(result.operations.operationsByScope)\n\t\t};\n\t}\n\t/**\n\t* Incremental fetch: fetches the document and only new operations per scope\n\t* using sinceRevision in a single request when possible.\n\t* Falls back to a full fetch on count mismatch.\n\t*/\n\tasync incrementalFetch() {\n\t\tconst scopes = Object.keys(this.remoteRevision);\n\t\tconst result = await this.remoteClient.getDocumentWithOperations(this.documentId, this.options.branch, this.remoteRevision, scopes.length > 0 ? scopes : void 0);\n\t\tif (!result) throw new Error(`Document \"${this.documentId}\" not found on remote`);\n\t\tconst remoteDoc = result.document;\n\t\tconst expectedRevision = extractRevisionMap(remoteDoc.revisionsList);\n\t\tconst newOps = convertRemoteOperations(result.operations.operationsByScope);\n\t\tconst merged = this.mergeOperations(this.inner.operations, newOps);\n\t\tif (this.hasExpectedOperationCounts(merged, expectedRevision)) return {\n\t\t\tremoteDoc,\n\t\t\toperations: merged\n\t\t};\n\t\treturn this.fullFetch(remoteDoc);\n\t}\n\t/**\n\t* Full fetch fallback: fetches all operations from the beginning.\n\t* Used when an incremental fetch produces a count mismatch.\n\t*/\n\tasync fullFetch(remoteDoc) {\n\t\tconst { operationsByScope } = await this.remoteClient.getAllOperations(this.documentId, this.options.branch);\n\t\treturn {\n\t\t\tremoteDoc,\n\t\t\toperations: convertRemoteOperations(operationsByScope)\n\t\t};\n\t}\n\t/**\n\t* Validate that the merged operations match the expected revision per scope.\n\t* Each scope's operation count should equal its revision number.\n\t*/\n\thasExpectedOperationCounts(operations, expectedRevision) {\n\t\tfor (const [scope, revision] of Object.entries(expectedRevision)) if ((scope in operations ? operations[scope].length : 0) !== revision) return false;\n\t\treturn true;\n\t}\n\t/**\n\t* Merge existing local operations with newly fetched operations.\n\t* Appends new operations to existing ones per scope.\n\t*/\n\tmergeOperations(existingOps, newOps) {\n\t\tconst merged = {};\n\t\tfor (const [scope, ops] of Object.entries(existingOps)) if (ops.length > 0) merged[scope] = [...ops];\n\t\tfor (const [scope, ops] of Object.entries(newOps)) if (ops.length > 0) (merged[scope] ??= []).push(...ops);\n\t\treturn merged;\n\t}\n\t/** Schedule a push via microtask (for streaming mode coalescing). */\n\tschedulePush() {\n\t\tif (this.pushScheduled) return;\n\t\tthis.pushScheduled = true;\n\t\tqueueMicrotask(() => {\n\t\t\tthis.pushScheduled = false;\n\t\t\tthis.pushQueue = this.pushQueue.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.push();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.options.onPushError?.(error);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n};\n//#endregion\n//#region src/storage/base-storage.ts\nvar BaseStorage = class {\n\t[Symbol.iterator]() {\n\t\treturn this.entries();\n\t}\n\tforEach(callback) {\n\t\tfor (const [key, value] of this) callback(value, key, this);\n\t}\n};\n//#endregion\n//#region src/storage/local-storage.ts\nvar BrowserLocalStorage = class extends BaseStorage {\n\t#namespace;\n\t#storage = window.localStorage;\n\tconstructor(namespace) {\n\t\tsuper();\n\t\tthis.#namespace = namespace;\n\t}\n\t#readMap() {\n\t\tconst raw = this.#storage.getItem(this.#namespace);\n\t\tif (!raw) return /* @__PURE__ */ new Map();\n\t\treturn new Map(JSON.parse(raw));\n\t}\n\t#writeMap(map) {\n\t\tthis.#storage.setItem(this.#namespace, JSON.stringify(Array.from(map.entries())));\n\t}\n\tget(key) {\n\t\treturn this.#readMap().get(key);\n\t}\n\tset(key, value) {\n\t\tconst map = this.#readMap();\n\t\tmap.set(key, value);\n\t\tthis.#writeMap(map);\n\t}\n\tdelete(key) {\n\t\tconst map = this.#readMap();\n\t\tconst deleted = map.delete(key);\n\t\tif (deleted) this.#writeMap(map);\n\t\treturn deleted;\n\t}\n\thas(key) {\n\t\treturn this.#readMap().has(key);\n\t}\n\tclear() {\n\t\tthis.#storage.removeItem(this.#namespace);\n\t}\n\tentries() {\n\t\treturn this.#readMap().entries();\n\t}\n\tkeys() {\n\t\treturn this.#readMap().keys();\n\t}\n\tvalues() {\n\t\treturn this.#readMap().values();\n\t}\n\t[Symbol.iterator]() {\n\t\treturn this.#readMap().entries();\n\t}\n};\n//#endregion\nexport { ActionTracker, BaseStorage, BrowserLocalStorage, COMMON_PACKAGE_ID, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, ChannelScheme, ChevronDownIcon, ConflictError, CopyIcon, DEFAULT_DRIVE_EDITOR_ID, DEFAULT_DRIVE_ID, DEFAULT_SWITCHBOARD_URL, DOMAIN_TYPE, DisconnectIcon, DocumentCache, DocumentChangeType, DocumentIntegrityService, DriveCollectionId, EDITOR_FILE_DROP_OPT_OUT_ATTR, GqlRequestChannel, GraphQLClientDocumentCache, ISSUER_TYPE, InMemoryQueue, IntervalPollTimer, PollBehavior, PropagationMode, REACTOR_SCHEMA, RENOWN_CHAIN_ID, RENOWN_NETWORK_ID, RENOWN_URL, ReactorBuilder, ReactorClientBuilder, RegistryClient, RelationalDbProcessor, RemoteClient, RemoteDocumentController, Renown, RenownAuthButton, RenownLoginButton, RenownLogo, RenownUserButton, SpinnerIcon, SyncOperationStatus, UploadStatus, UserIcon, VERIFIABLE_CREDENTIAL_EIP712_TYPE, addAllowListEventHandler, addAllowedDocumentTypesEventHandler, addAnalyticsDatabaseNameEventHandler, addAttachmentServiceEventHandler, addBasePathEventHandler, addCliVersionEventHandler, addDefaultDrivesUrlEventHandler, addDisabledEditorsEventHandler, addDocument, addDocumentCacheEventHandler, addDraggingNodeEventHandler, addDrive, addDrivesEventHandler, addDrivesPreserveStrategyEventHandler, addEnabledEditorsEventHandler, addFeaturesEventHandler, addFileUploadOperationsChunkSizeEventHandler, addFolder, addGaTrackingIdEventHandler, addGraphQLReactorClientEventHandler, addIsAddCloudDrivesEnabledEventHandler, addIsAddDriveEnabledEventHandler, addIsAddLocalDrivesEnabledEventHandler, addIsAddPublicDrivesEnabledEventHandler, addIsAnalyticsDatabaseWorkerEnabledEventHandler, addIsAnalyticsEnabledEventHandler, addIsAnalyticsExternalProcessorsEnabledEventHandler, addIsCloudDrivesEnabledEventHandler, addIsDeleteCloudDrivesEnabledEventHandler, addIsDeleteLocalDrivesEnabledEventHandler, addIsDeletePublicDrivesEnabledEventHandler, addIsDiffAnalyticsEnabledEventHandler, addIsDocumentModelSelectionSettingsEnabledEventHandler, addIsDragAndDropEnabledEventHandler, addIsDriveAnalyticsEnabledEventHandler, addIsEditorDebugModeEnabledEventHandler, addIsEditorReadModeEnabledEventHandler, addIsExternalControlsEnabledEventHandler, addIsExternalPackagesEnabledEventHandler, addIsExternalProcessorsEnabledEventHandler, addIsExternalRelationalProcessorsEnabledEventHandler, addIsLocalDrivesEnabledEventHandler, addIsPublicDrivesEnabledEventHandler, addIsRelationalProcessorsEnabledEventHandler, addIsSentryTracingEnabledEventHandler, addLoadingEventHandler, addLocalDrivesEnabledEventHandler, addLogLevelEventHandler, addModalEventHandler, addPHEventHandlers, addPackageDiscoveryServiceEventHandler, addPromiseState, addReactorClientEventHandler, addReactorClientModuleEventHandler, addRemoteDrive, addRenownChainIdEventHandler, addRenownEventHandler, addRenownNetworkIdEventHandler, addRenownUrlEventHandler, addRequiresHardRefreshEventHandler, addResetSelectedNodeEventHandler, addRevisionHistoryVisibleEventHandler, addRouterBasenameEventHandler, addSelectedDriveIdEventHandler, addSelectedNodeIdEventHandler, addSelectedTimelineItemEventHandler, addSelectedTimelineRevisionEventHandler, addSentryDsnEventHandler, addSentryEnvEventHandler, addSentryReleaseEventHandler, addSetSelectedDriveOnPopStateEventHandler, addSetSelectedNodeOnPopStateEventHandler, addStudioModeEventHandler, addToastEventHandler, addVersionCheckIntervalEventHandler, addVersionEventHandler, addVetraPackageManagerEventHandler, addWarnOutdatedAppEventHandler, baseDocumentModels, baseDocumentModelsMap, buildDocumentSubgraphQuery, buildDocumentSubgraphUrl, callEventHandlerRegisterFunctions, callGlobalSetterForKey, clearGlobal, closePHModal, commonGlobalEventHandlerFunctions, convertRemoteOperations, createAnalyticsStore, createClient, createProcessorQuery, createUrlWithPreservedParams, deleteDrive, deleteNode, deriveSystemUrl, dispatchActions, downloadDocument, driveIdFromUrl, dropAllReactorStorage, exportFile, extractDriveIdFromPath, extractDriveIdFromSlug, extractDriveSlugFromPath, extractNodeIdFromPath, extractNodeIdFromSlug, extractNodeSlugFromPath, findUuid, getAnalyticsStore, getDocumentGraphqlQuery, getDriveIdBySlug, getDrives, getGlobal, getPackages, getPackagesByDocumentType, getPathWithoutBase, getRevisionFromDate, getSlugFromDriveUrl, getSwitchboardGatewayUrlFromDriveUrl, getSyncStatus, getSyncStatusSync, getUserPermissions, graphqlDocumentEvents, graphqlDocumentsEvents, graphqlEventsToSyncDrive, hideRevisionHistory, identifierFromMutateDocumentOperationVariables, initConnectCrypto, initRenownCrypto, initTheme, isDocumentTypeSupported, isExternalControlsEnabledEventFunctions, isFileNodeKind, isFolderNodeKind, loading, login, logout, makeDriveUrlComponent, makeNodeSlug, makePHEventFunctions, openRenown, parseDriveUrl, phAppConfigHooks, phAppConfigSetters, phDocumentEditorConfigHooks, phDocumentEditorConfigSetters, phDocumentFromQuery, phDocumentsFromQuery, phGlobalConfigHooks, phGlobalConfigSetters, reactorGraphqlBatchFetchDocuments, reactorGraphqlCreateDocument, reactorGraphqlDeleteDocument, reactorGraphqlDeleteDocuments, reactorGraphqlFetchDocument, reactorGraphqlMutateDocument, readPromiseState, refreshReactorData, refreshReactorDataClient, renameDrive, renameDriveNode, resolveUrlPathname, setAllowList, setAllowedDocumentTypes, setAnalyticsDatabaseName, setAttachmentService, setBasePath, setCliVersion, setDefaultDrivesUrl, setDefaultPHGlobalConfig, setDisabledEditors, setDocumentCache, setDriveAvailableOffline, setDriveMetadata, setDriveSharingType, setDrives, setDrivesPreserveStrategy, setEnabledEditors, setFeatures, setFileUploadOperationsChunkSize, setGaTrackingId, setGlobal, setGraphQLReactorClient, setIsAddCloudDrivesEnabled, setIsAddDriveEnabled, setIsAddLocalDrivesEnabled, setIsAddPublicDrivesEnabled, setIsAnalyticsDatabaseWorkerEnabled, setIsAnalyticsEnabled, setIsAnalyticsExternalProcessorsEnabled, setIsCloudDrivesEnabled, setIsDeleteCloudDrivesEnabled, setIsDeleteLocalDrivesEnabled, setIsDeletePublicDrivesEnabled, setIsDiffAnalyticsEnabled, setIsDocumentModelSelectionSettingsEnabled, setIsDragAndDropEnabled, setIsDriveAnalyticsEnabled, setIsEditorDebugModeEnabled, setIsEditorReadModeEnabled, setIsExternalControlsEnabled, setIsExternalPackagesEnabled, setIsExternalProcessorsEnabled, setIsExternalRelationalProcessorsEnabled, setIsLocalDrivesEnabled, setIsPublicDrivesEnabled, setIsRelationalProcessorsEnabled, setIsSentryTracingEnabled, setLoading, setLocalDrivesEnabled, setLogLevel, setPHAppConfig, setPHAppConfigByKey, setPHDocumentEditorConfig, setPHDocumentEditorConfigByKey, setPHGlobalConfig, setPHGlobalConfigByKey, setPHModal, setPHToast, setPackageDiscoveryService, setReactorClient, setReactorClientModule, setRenown, setRenownChainId, setRenownNetworkId, setRenownUrl, setRequiresHardRefresh, setRevisionHistoryVisible, setRouterBasename, setSelectedDrive, setSelectedDriveId, setSelectedNode, setSelectedTimelineItem, setSelectedTimelineRevision, setSentryDsn, setSentryEnv, setSentryRelease, setStudioMode, setVersion, setVersionCheckInterval, setVetraPackageManager, setWarnOutdatedApp, showCreateDocumentModal, showDeleteNodeModal, showPHModal, showRevisionHistory, sortNodesByName, trimTrailingSlash, truncateAllTables, useAllowList, useAllowedDocumentModelModules, useAllowedDocumentTypes, useAnalyticsDatabaseName, useAppModuleById, useAppModules, useAttachmentService, useAttachmentUpload, useAttachments, useBasePath, useCliVersion, useConnectionState, useConnectionStates, useDatabase, useDefaultAppModule, useDefaultDrivesUrl, useDid, useDisabledEditors, useDispatch, useDocument, useDocumentById, useDocumentCache, useDocumentModelModuleById, useDocumentModelModules, useDocumentOfType, useDocumentOperations, useDocumentSafe, useDocumentTypes, useDocumentTypesInSelectedDrive, useDocuments, useDocumentsByIds, useDocumentsInSelectedDrive, useDocumentsInSelectedFolder, useDownloadDocument, useDragNode, useDriveById, useDriveSystemInfo, useDrives, useDrivesPreserveStrategy, useDropFile, useDropNode, useEditorFileDrop, useEditorModuleById, useEditorModules, useEditorModulesForDocumentType, useEnabledEditors, useFallbackEditorModule, useFeatures, useFileNodesInSelectedDrive, useFileNodesInSelectedFolder, useFileUploadOperationsChunkSize, useFolderById, useFolderNodesInSelectedDrive, useFolderNodesInSelectedFolder, useGaTrackingId, useGetDocument, useGetDocumentAsync, useGetDocuments, useGetSwitchboardLink, useGraphQLReactorClient, useInitReactorGraphqlClient, useIsAddCloudDrivesEnabled, useIsAddDriveEnabled, useIsAddLocalDrivesEnabled, useIsAddPublicDrivesEnabled, useIsAnalyticsDatabaseWorkerEnabled, useIsAnalyticsEnabled, useIsAnalyticsExternalProcessorsEnabled, useIsCloudDrivesEnabled, useIsDeleteCloudDrivesEnabled, useIsDeleteLocalDrivesEnabled, useIsDeletePublicDrivesEnabled, useIsDiffAnalyticsEnabled, useIsDocumentModelSelectionSettingsEnabled, useIsDragAndDropEnabled, useIsDriveAnalyticsEnabled, useIsEditorDebugModeEnabled, useIsEditorReadModeEnabled, useIsExternalControlsEnabled, useIsExternalPackagesEnabled, useIsExternalProcessorsEnabled, useIsExternalRelationalProcessorsEnabled, useIsLocalDrivesEnabled, useIsPublicDrivesEnabled, useIsRelationalProcessorsEnabled, useIsSentryTracingEnabled, useLoading, useLocalDrivesEnabled, useLogLevel, useLoginStatus, useModelRegistry, useNodeActions, useNodeById, useNodeParentFolderById, useNodePathById, useNodesInSelectedDrive, useNodesInSelectedDriveOrFolder, useNodesInSelectedFolder, useOnDropFile, usePGlite, usePHAppConfigByKey, usePHDocumentEditorConfigByKey, usePHGlobalConfigByKey, usePHModal, usePHToast, usePackageDiscoveryService, useParentFolderForSelectedNode, useReactorClient, useReactorClientModule, useRelationalDb, useRelationalQuery, useRenown, useRenownAuth, useRenownChainId, useRenownInit, useRenownNetworkId, useRenownUrl, useRequiresHardRefresh, useResetPHGlobalConfig, useRevisionHistoryVisible, useRouterBasename, useSelectedDocument, useSelectedDocumentId, useSelectedDocumentOfType, useSelectedDocumentSafe, useSelectedDrive, useSelectedDriveId, useSelectedDriveSafe, useSelectedFolder, useSelectedNode, useSelectedNodePath, useSelectedTimelineItem, useSelectedTimelineRevision, useSentryDsn, useSentryEnv, useSentryRelease, useSetDefaultPHGlobalConfig, useSetPHAppConfig, useSetPHDocumentEditorConfig, useSetPHGlobalConfig, useStudioMode, useSubgraphModules, useSupportedDocumentTypesInReactor, useSync, useSyncList, useTheme, useUser, useUserPermissions, useVersion, useVersionCheckInterval, useVetraPackageManager, useVetraPackages, useWarnOutdatedApp, validateDocument, waitForDocumentReady };\n\n//# sourceMappingURL=index.js.map","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { DocumentDispatch } from '@powerhousedao/reactor-browser';\nimport { useDocumentById, useDocumentsInSelectedDrive, useDocumentsInSelectedFolder, useSelectedDocument } from '@powerhousedao/reactor-browser';\nimport type { PhClintProjectAction, PhClintProjectDocument } from 'document-models/ph-clint-project/v1';\nimport { assertIsPhClintProjectDocument, isPhClintProjectDocument } from './gen/document-schema.js';\n\n/** Hook to get a PhClintProject document by its id */\nexport function usePhClintProjectDocumentById(documentId: string | null | undefined): [PhClintProjectDocument, DocumentDispatch<PhClintProjectAction>] | [undefined, undefined] {\n const [document, dispatch] = useDocumentById(documentId);\n if (!isPhClintProjectDocument(document)) return [undefined, undefined];\n return [document, dispatch];\n}\n\n/** Hook to get the selected PhClintProject document */\nexport function useSelectedPhClintProjectDocument(): [PhClintProjectDocument, DocumentDispatch<PhClintProjectAction>] {\n const [document, dispatch] = useSelectedDocument();\n\n assertIsPhClintProjectDocument(document);\n return [document, dispatch] as const;\n}\n\n/** Hook to get all PhClintProject documents in the selected drive */\nexport function usePhClintProjectDocumentsInSelectedDrive() {\n const documentsInSelectedDrive = useDocumentsInSelectedDrive();\n return documentsInSelectedDrive?.filter(isPhClintProjectDocument);\n}\n\n/** Hook to get all PhClintProject documents in the selected folder */\nexport function usePhClintProjectDocumentsInSelectedFolder() {\n const documentsInSelectedFolder = useDocumentsInSelectedFolder();\n return documentsInSelectedFolder?.filter(isPhClintProjectDocument);\n}\n"],"x_google_ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49],"mappings":";;;;;;;;AAQA,MAAa,2BAA2B,qBAAqB,iBAA8D,eAAe;;;ACE1I,SAAgB,qBAAgD;AAC9D,QAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,aAAa;EACb,UAAU;GACR,YAAY;GACZ,QAAQ;IACN,SAAS;IACT,WAAW;IACX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AG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,IAAI;CACJ,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,IAAI;CACJ,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,IAAI;CACJ,GAAG;CACH,GAAG;CACH,GAAG;CACH,GA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