@powerhousedao/connect 6.0.0-dev.5 → 6.0.0-dev.52

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 (207) hide show
  1. package/.env +1 -1
  2. package/dist/assets/AddDriveModal-CJtOv39H.js +1 -0
  3. package/dist/assets/ClearStorageModal-y5IKZ5QW.js +1 -0
  4. package/dist/assets/CookiesPolicyModal-CRQMjvin.js +1 -0
  5. package/dist/assets/CreateDocumentModal-wq9SMWoi.js +1 -0
  6. package/dist/assets/DebugSettingsModal-DRXZ3l1V.js +1 -0
  7. package/dist/assets/DeleteDriveModal-Cr5Usb_L.js +1 -0
  8. package/dist/assets/DeleteItemModal-8enl6kcm.js +1 -0
  9. package/dist/assets/DisclaimerModal-XxPC9Ejt.js +1 -0
  10. package/dist/assets/DriveSettingsModal-6h8SadLE.js +1 -0
  11. package/dist/assets/ExportDocumentWithErrorsModal-DXqXD8JC.js +1 -0
  12. package/dist/assets/SettingsModal-hbCXOBTZ.js +1 -0
  13. package/dist/assets/UpgradeDriveModal-iM7KnmAQ.js +1 -0
  14. package/dist/assets/config-0mYxXHFp.js +1 -0
  15. package/dist/assets/{design_system-DVdodNjK.js → design_system-DuOTmGnv.js} +2 -2
  16. package/dist/assets/design_system_connect-oOPqJKY4.js +47 -0
  17. package/dist/assets/design_system_ui-BpFBMLtp.js +1 -0
  18. package/dist/assets/document_drive-DiwReQ7A.js +154 -0
  19. package/dist/assets/document_engineering-p8dj-Cba.js +1 -0
  20. package/dist/assets/document_model-ly1Z8uco.js +241 -0
  21. package/dist/assets/document_model_editor-Da4AAuKL.js +25 -0
  22. package/dist/assets/drive_explorer-DgTtoOmx.js +2 -0
  23. package/dist/assets/editor-D3CEoO4i.js +1 -0
  24. package/dist/assets/{graphql-AKTCpY7l.js → graphql-BXSeDpaV.js} +2 -2
  25. package/dist/assets/{graphql-editor-pM_6zgoE.js → graphql-editor-CduYMSwz.js} +2 -2
  26. package/dist/assets/graphql_request-BHyPFzlZ.js +3 -0
  27. package/dist/assets/{hooks-CcLWqK8A.js → hooks-DfJBOC53.js} +1 -1
  28. package/dist/assets/index-B6A7sjLB.css +1 -0
  29. package/dist/assets/index-DO1hMFtq.js +149 -0
  30. package/dist/assets/index-DaxIv9p8.js +29 -0
  31. package/dist/assets/index-nPVGMhnl.js +208 -0
  32. package/dist/assets/json-editor-ge2w_43Q.js +1 -0
  33. package/dist/assets/nodefs-BDOJRpNU.js +1 -0
  34. package/dist/assets/nodefs-CVTQ2TCv.js +1 -0
  35. package/dist/assets/nodefs-_NvywCGz.js +1 -0
  36. package/dist/assets/opfs-ahp--n7Av8I7.js +3 -0
  37. package/dist/assets/opfs-ahp-DN9nZuJs.js +3 -0
  38. package/dist/assets/opfs-ahp-gToYnU-E.js +3 -0
  39. package/dist/assets/pg_dump-Cvfbb5Q0.wasm +0 -0
  40. package/dist/assets/pglite-COscPi1Y.data +0 -0
  41. package/dist/assets/pglite-CeYkvzd0.wasm +0 -0
  42. package/dist/assets/pglite.worker-Ca6pWokV.js +141 -0
  43. package/dist/assets/{react-DQSxOgtG.js → react-D_vzfE_e.js} +1 -1
  44. package/dist/assets/react-dom/client-SoBEzBdt.js +9 -0
  45. package/dist/assets/{react-dom-D6zQJsh6.js → react-dom-Cz_KAjfm.js} +1 -1
  46. package/dist/assets/reactor_browser-D9uAHhHf.js +136 -0
  47. package/dist/assets/{sentry_browser-B4YoBIIG.js → sentry_browser-TIBDlywD.js} +3 -3
  48. package/dist/assets/{sentry_react-cODD7zWc.js → sentry_react-CVx4Qq7f.js} +1 -1
  49. package/dist/assets/state-schemas-CNNgCMhK.js +2 -0
  50. package/dist/assets/tailwind_merge-CXl88Wxt.js +1 -0
  51. package/dist/assets/zod-Cc38s6JG.js +39 -0
  52. package/dist/index.html +19 -20
  53. package/heroku/Dockerfile +1 -1
  54. package/lib/package.copy.json +30 -28
  55. package/lib/src/components/document-editor-container.d.ts.map +1 -1
  56. package/lib/src/components/document-editor-container.js +7 -34
  57. package/lib/src/components/document-editor-container.js.map +1 -1
  58. package/lib/src/components/drive-icon.d.ts.map +1 -1
  59. package/lib/src/components/drive-icon.js +10 -3
  60. package/lib/src/components/drive-icon.js.map +1 -1
  61. package/lib/src/components/editors.d.ts.map +1 -1
  62. package/lib/src/components/editors.js +12 -5
  63. package/lib/src/components/editors.js.map +1 -1
  64. package/lib/src/components/error-boundary.js +1 -1
  65. package/lib/src/components/error-boundary.js.map +1 -1
  66. package/lib/src/components/modal/modals/AddDriveModal.d.ts.map +1 -1
  67. package/lib/src/components/modal/modals/AddDriveModal.js +17 -48
  68. package/lib/src/components/modal/modals/AddDriveModal.js.map +1 -1
  69. package/lib/src/components/modal/modals/ClearStorageModal.js +2 -2
  70. package/lib/src/components/modal/modals/ClearStorageModal.js.map +1 -1
  71. package/lib/src/components/modal/modals/DriveSettingsModal.d.ts.map +1 -1
  72. package/lib/src/components/modal/modals/DriveSettingsModal.js +9 -4
  73. package/lib/src/components/modal/modals/DriveSettingsModal.js.map +1 -1
  74. package/lib/src/components/modal/modals/InspectorModal/InspectorModal.d.ts.map +1 -1
  75. package/lib/src/components/modal/modals/InspectorModal/InspectorModal.js +3 -1
  76. package/lib/src/components/modal/modals/InspectorModal/InspectorModal.js.map +1 -1
  77. package/lib/src/components/modal/modals/InspectorModal/useQueueInspector.d.ts +3 -0
  78. package/lib/src/components/modal/modals/InspectorModal/useQueueInspector.d.ts.map +1 -0
  79. package/lib/src/components/modal/modals/InspectorModal/useQueueInspector.js +61 -0
  80. package/lib/src/components/modal/modals/InspectorModal/useQueueInspector.js.map +1 -0
  81. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.d.ts +2 -1
  82. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.d.ts.map +1 -1
  83. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.js +4 -1
  84. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.js.map +1 -1
  85. package/lib/src/components/sidebar.d.ts.map +1 -1
  86. package/lib/src/components/sidebar.js +2 -2
  87. package/lib/src/components/sidebar.js.map +1 -1
  88. package/lib/src/connect.config.js +1 -1
  89. package/lib/src/connect.config.js.map +1 -1
  90. package/lib/src/context/index.d.ts +1 -1
  91. package/lib/src/context/index.d.ts.map +1 -1
  92. package/lib/src/context/index.js +1 -1
  93. package/lib/src/context/index.js.map +1 -1
  94. package/lib/src/context/processor-manager.d.ts +1 -2
  95. package/lib/src/context/processor-manager.d.ts.map +1 -1
  96. package/lib/src/context/processor-manager.js +1 -188
  97. package/lib/src/context/processor-manager.js.map +1 -1
  98. package/lib/src/context/processor-manager.old.d.ts +3 -0
  99. package/lib/src/context/processor-manager.old.d.ts.map +1 -0
  100. package/lib/src/context/processor-manager.old.js +189 -0
  101. package/lib/src/context/processor-manager.old.js.map +1 -0
  102. package/lib/src/feature-flags.d.ts.map +1 -1
  103. package/lib/src/feature-flags.js +13 -0
  104. package/lib/src/feature-flags.js.map +1 -1
  105. package/lib/src/hooks/useCheckLatestVersion.d.ts.map +1 -1
  106. package/lib/src/hooks/useCheckLatestVersion.js +1 -1
  107. package/lib/src/hooks/useCheckLatestVersion.js.map +1 -1
  108. package/lib/src/hooks/useClientErrorHandler.d.ts.map +1 -1
  109. package/lib/src/hooks/useClientErrorHandler.js +5 -40
  110. package/lib/src/hooks/useClientErrorHandler.js.map +1 -1
  111. package/lib/src/hooks/useInitSentry.js +2 -2
  112. package/lib/src/hooks/useInitSentry.js.map +1 -1
  113. package/lib/src/pages/demo/atlas-import.js +2 -2
  114. package/lib/src/pglite.db.d.ts +2 -0
  115. package/lib/src/pglite.db.d.ts.map +1 -0
  116. package/lib/src/pglite.db.js +19 -0
  117. package/lib/src/pglite.db.js.map +1 -0
  118. package/lib/src/pglite.worker.d.ts +2 -0
  119. package/lib/src/pglite.worker.d.ts.map +1 -0
  120. package/lib/src/pglite.worker.js +15 -0
  121. package/lib/src/pglite.worker.js.map +1 -0
  122. package/lib/src/services/hmr.js +1 -1
  123. package/lib/src/services/hmr.js.map +1 -1
  124. package/lib/src/services/index.d.ts +0 -3
  125. package/lib/src/services/index.d.ts.map +1 -1
  126. package/lib/src/services/index.js +0 -3
  127. package/lib/src/services/index.js.map +1 -1
  128. package/lib/src/store/editor.d.ts.map +1 -1
  129. package/lib/src/store/editor.js +4 -5
  130. package/lib/src/store/editor.js.map +1 -1
  131. package/lib/src/store/processor-host-module.d.ts +3 -0
  132. package/lib/src/store/processor-host-module.d.ts.map +1 -0
  133. package/lib/src/store/processor-host-module.js +22 -0
  134. package/lib/src/store/processor-host-module.js.map +1 -0
  135. package/lib/src/store/reactor.d.ts +1 -1
  136. package/lib/src/store/reactor.d.ts.map +1 -1
  137. package/lib/src/store/reactor.js +77 -189
  138. package/lib/src/store/reactor.js.map +1 -1
  139. package/lib/src/utils/reactor.d.ts +13 -7
  140. package/lib/src/utils/reactor.d.ts.map +1 -1
  141. package/lib/src/utils/reactor.js +37 -63
  142. package/lib/src/utils/reactor.js.map +1 -1
  143. package/lib/src/utils/signature.d.ts.map +1 -1
  144. package/lib/src/utils/signature.js +1 -1
  145. package/lib/src/utils/signature.js.map +1 -1
  146. package/lib/style.css +373 -115
  147. package/lib/test/utils/signer.test.js +25 -28
  148. package/lib/test/utils/signer.test.js.map +1 -1
  149. package/lib/tsconfig.tsbuildinfo +1 -1
  150. package/lib/vite.config.d.ts.map +1 -1
  151. package/lib/vite.config.js +0 -4
  152. package/lib/vite.config.js.map +1 -1
  153. package/package.copy.json +30 -28
  154. package/package.json +39 -37
  155. package/dist/assets/AddDriveModal-BQm-PcmC.js +0 -1
  156. package/dist/assets/ClearStorageModal-28jHiUGr.js +0 -1
  157. package/dist/assets/CookiesPolicyModal-B8ON6Aot.js +0 -1
  158. package/dist/assets/CreateDocumentModal-Dq3Bi3cq.js +0 -1
  159. package/dist/assets/DebugSettingsModal-CJONGfBK.js +0 -1
  160. package/dist/assets/DeleteDriveModal-bUDGgtH-.js +0 -1
  161. package/dist/assets/DeleteItemModal-B8ZzH9at.js +0 -1
  162. package/dist/assets/DisclaimerModal-BOLKXvyT.js +0 -1
  163. package/dist/assets/DriveSettingsModal-DIbcmIVs.js +0 -1
  164. package/dist/assets/ExportDocumentWithErrorsModal-gHdbtQ3B.js +0 -1
  165. package/dist/assets/SettingsModal-DP7GWuuW.js +0 -1
  166. package/dist/assets/UpgradeDriveModal--uyH9aU-.js +0 -1
  167. package/dist/assets/config-CU-aFfVJ.js +0 -1
  168. package/dist/assets/design_system_connect-GjcNtEuR.js +0 -47
  169. package/dist/assets/design_system_ui-CirzPTGM.js +0 -1
  170. package/dist/assets/document_drive-CwpHvdiT.js +0 -316
  171. package/dist/assets/document_engineering-x8qLjrlA.js +0 -1
  172. package/dist/assets/document_model-_oCbt5YE.js +0 -230
  173. package/dist/assets/document_model_editor-H_2IAVLg.js +0 -25
  174. package/dist/assets/drive_explorer-DaOEkDU-.js +0 -2
  175. package/dist/assets/graphql_request-BJtmW2JS.js +0 -3
  176. package/dist/assets/index-C44AjweI.js +0 -28
  177. package/dist/assets/index-DNce0SAe.css +0 -1
  178. package/dist/assets/index-Dxjl28rF.js +0 -18
  179. package/dist/assets/json-editor-BFca9ePf.js +0 -1
  180. package/dist/assets/nodefs-BRqoxQYy.js +0 -1
  181. package/dist/assets/opfs-ahp-DetoV0on.js +0 -3
  182. package/dist/assets/pg_dump-CW0pN9tG.wasm +0 -0
  183. package/dist/assets/react-dom/client-BVPiT_FE.js +0 -9
  184. package/dist/assets/reactor_browser-BTFz4lY7.js +0 -129
  185. package/dist/assets/state-schemas-DBLZHoPv.js +0 -2
  186. package/dist/assets/tailwind_merge-Dr4f9Rms.js +0 -1
  187. package/dist/assets/zod-9j67vCAu.js +0 -39
  188. package/lib/src/service-worker.d.ts +0 -2
  189. package/lib/src/service-worker.d.ts.map +0 -1
  190. package/lib/src/service-worker.js +0 -58
  191. package/lib/src/service-worker.js.map +0 -1
  192. package/lib/src/services/renown/browser.d.ts +0 -2
  193. package/lib/src/services/renown/browser.d.ts.map +0 -1
  194. package/lib/src/services/renown/browser.js +0 -6
  195. package/lib/src/services/renown/browser.js.map +0 -1
  196. package/lib/src/services/renown/constants.d.ts +0 -130
  197. package/lib/src/services/renown/constants.d.ts.map +0 -1
  198. package/lib/src/services/renown/constants.js +0 -41
  199. package/lib/src/services/renown/constants.js.map +0 -1
  200. package/lib/src/services/renown/utils.d.ts +0 -7
  201. package/lib/src/services/renown/utils.d.ts.map +0 -1
  202. package/lib/src/services/renown/utils.js +0 -20
  203. package/lib/src/services/renown/utils.js.map +0 -1
  204. package/lib/src/workers/pglite-worker.d.ts +0 -2
  205. package/lib/src/workers/pglite-worker.d.ts.map +0 -1
  206. package/lib/src/workers/pglite-worker.js +0 -32
  207. package/lib/src/workers/pglite-worker.js.map +0 -1
@@ -0,0 +1,136 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/nodefs-BDOJRpNU.js","assets/document_model-ly1Z8uco.js","assets/zod-Cc38s6JG.js","assets/react-D_vzfE_e.js","assets/document_drive-DiwReQ7A.js","assets/sentry_react-CVx4Qq7f.js","assets/sentry_browser-TIBDlywD.js","assets/document_model_editor-Da4AAuKL.js","assets/graphql-BXSeDpaV.js","assets/drive_explorer-DgTtoOmx.js","assets/react/jsx-runtime-DldvXD6N.js","assets/design_system-DuOTmGnv.js","assets/tailwind_merge-CXl88Wxt.js","assets/react-dom-Cz_KAjfm.js","assets/design_system_connect-oOPqJKY4.js","assets/design_system_ui-BpFBMLtp.js","assets/opfs-ahp-gToYnU-E.js","assets/index-nPVGMhnl.js"])))=>i.map(i=>d[i]);
2
+ import{l as logger$1,J as buildSignedAction,d as baseSaveToFileHandle,K as documentModelDocumentType,L as createZip,g as generateId,M as createPresignedHeader,N as replayDocument,e as baseLoadFromInput,O as actions,h as defaultBaseState,P as deriveOperationId,Q as isUndoRedo,R as ConsoleLogger,S as childLogger,T as capitalCase,U as validateInitialState,V as validateStateSchemaName,W as validateModules,j as createState}from"./document_model-ly1Z8uco.js";import{d as deleteNode$1,a as addFolder$1,i as isFolderNode,u as updateNode,g as generateNodesCopy,h as handleTargetNameCollisions,b as isFileNode,c as copyNode$1,e as addFile$1,A as AbortError,f as fnv1a,s as setSharingType,j as setAvailableOffline,k as driveCreateDocument,D as DocumentNotFoundError,l as DocumentModelNotFoundError}from"./document_drive-DiwReQ7A.js";import{r as reactExports}from"./sentry_react-CVx4Qq7f.js";import{j as jsxRuntimeExports}from"./document_model_editor-Da4AAuKL.js";import{_ as __vitePreload}from"./drive_explorer-DgTtoOmx.js";import{p as process$1,g as getDefaultExportFromCjs,a as getAugmentedNamespace}from"./react-D_vzfE_e.js";async function queueActions(r,e){if(!r)throw new Error("No document provided");if(!e)throw new Error("No actions provided");const M=Array.isArray(e)?e:[e];if(M.length===0)throw new Error("No actions provided");const tr=window.ph?.reactorClient;if(!tr)throw new Error("ReactorClient not initialized");return await tr.execute(r.header.id,"main",M)}async function queueOperations(r,e){if(!r)throw new Error("No documentId provided");if(!e)throw new Error("No operations provided");const M=Array.isArray(e)?e:[e];if(M.length===0)throw new Error("No operations provided");const tr=window.ph?.reactorClient;if(!tr)throw new Error("ReactorClient not initialized");const rr=M.map(ir=>ir.action);return await tr.execute(r,"main",rr)}async function uploadOperations(r,e,M,tr){const rr=tr?.operationsLimit||50,ir=tr?.onProgress;logger$1.verbose(`uploadDocumentOperations(documentId:${r}, ops: ${Object.keys(e).join(",")}, limit:${rr})`);const lr=Object.values(e).filter(fr=>fr!==void 0),dr=lr.reduce((fr,mr)=>fr+mr.length,0);let hr=0;for(const fr of lr)for(let mr=0;mr<fr.length;mr+=rr){logger$1.verbose(`uploadDocumentOperations:for(i:${mr}, ops:${fr.length}, limit:${rr}): START`);const _r=fr.slice(mr,mr+rr),gr=_r.at(-1);if(!gr)break;const wr=gr.action.scope;if(await M(r,_r),hr+=_r.length,ir){const yr=Math.round(hr/dr*100);ir({stage:"uploading",progress:yr,totalOperations:dr,uploadedOperations:hr})}logger$1.verbose(`uploadDocumentOperations:for:waitForUpdate(${r}:${wr} rev ${gr.index}): NEXT`)}logger$1.verbose(`uploadDocumentOperations:for:waitForUpdate(${r}): END`)}async function signAction$1(r,e){const M=window.ph?.reactorClient;if(!M)return r;const rr=(await M.getDocumentModelModule(e.header.documentType)).reducer,ir=window.ph?.user,lr=window.ph?.connectCrypto;if(!ir||!lr||!r.context?.signer)return r;const dr=r.context.signer;return await buildSignedAction(r,rr,e,dr,lr.sign)}function addActionContext(r){const e=window.ph?.user,M=window.ph?.did;return e?{context:{signer:{app:{name:"Connect",key:M||""},user:{address:e.address,networkId:e.networkId,chainId:e.chainId},signatures:[]}},...r}:r}async function makeSignedActionWithContext(r,e){if(!r){logger$1.error("No action found");return}if(!e){logger$1.error("No document found");return}const M=await signAction$1(r,e);return addActionContext(M)}async function makeSignedActionsWithContext(r,e){if(!r){logger$1.error("No actions found");return}const M=Array.isArray(r)?r:[r];return(await Promise.all(M.map(rr=>makeSignedActionWithContext(rr,e)))).filter(rr=>rr!==void 0)}async function getDocument(r){try{return await window.ph?.reactorClient?.get(r)}catch(e){logger$1.debug(`Failed to get document with id ${r}:`,e);return}}function getActionErrors(r,e){return e.reduce((M,tr)=>{const rr=r.operations[tr.scope];if(!rr)return M;const ir=rr.findLast(lr=>lr.action.id===tr.id);return ir?.error&&M.push(new Error(ir.error)),M},new Array)}async function dispatchActions(r,e,M,tr){const rr=typeof e=="string"?await getDocument(e):e;if(!rr){logger$1.error(`Document with id ${JSON.stringify(e)} not found`);return}const ir=await makeSignedActionsWithContext(r,rr);if(!ir){logger$1.error("No signed actions with context found");return}const lr=await queueActions(rr,ir);if(M&&lr){const dr=getActionErrors(lr,ir);dr.length&&M(dr)}return tr&&lr&&tr(lr),lr}class UnsupportedDocumentTypeError extends Error{constructor(e){super(`Document type ${e} is not supported`),this.name="UnsupportedDocumentTypeError"}static isError(e){return Error.isError(e)&&e.name==="UnsupportedDocumentTypeError"}}class DocumentTypeMismatchError extends Error{constructor(e,M,tr){super(`Document ${e} is not of type ${M}. Actual type: ${tr}`)}}class NoSelectedDocumentError extends Error{constructor(){super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?")}}function isDocumentTypeSupported(r,e){return e?.length?e.some(M=>{if(M.endsWith("/*")){const tr=M.slice(0,-2);return r.startsWith(tr+"/")}if(M.endsWith("*")&&!M.endsWith("/*")){const tr=M.slice(0,-1);return r.startsWith(tr)}return M===r}):!0}function getUserPermissions(){const r=window.ph?.user,e=window.ph?.allowList;return e?{isAllowedToCreateDocuments:e.includes(r?.address??""),isAllowedToEditDocuments:e.includes(r?.address??"")}:{isAllowedToCreateDocuments:!0,isAllowedToEditDocuments:!0}}async function isDocumentInLocation(r,e,M){const tr=window.ph?.reactorClient;if(!tr)return{isDuplicate:!1};let rr;try{rr=await tr.get(e)}catch{return{isDuplicate:!1}}const ir=rr.state.global.nodes.find(dr=>dr.id===r.header.id);if(ir&&ir.parentFolder===(M??null))return{isDuplicate:!0,duplicateType:"id",nodeId:ir.id};const lr=rr.state.global.nodes.find(dr=>isFileNode(dr)&&dr.name===r.header.name&&dr.documentType===r.header.documentType&&dr.parentFolder===(M??null));return lr?{isDuplicate:!0,duplicateType:"name",nodeId:lr.id}:{isDuplicate:!1}}function getDocumentTypeIcon(r){switch(r.header.documentType){case"powerhouse/document-model":return"document-model";case"powerhouse/app":return"app";case"powerhouse/document-editor":return"editor";case"powerhouse/subgraph":return"subgraph";case"powerhouse/package":return"package";case"powerhouse/processor":{const tr=r.state.global?.type;return tr==="analytics"?"analytics-processor":tr==="relational"?"relational-processor":tr==="codegen"?"codegen-processor":void 0}default:return}}function downloadFile(r,e){createZip(r).generateAsync({type:"blob"}).then(tr=>{const rr=window.document.createElement("a");rr.style.display="none",rr.href=URL.createObjectURL(tr),rr.download=e,window.document.body.appendChild(rr),rr.click(),window.document.body.removeChild(rr)}).catch(logger$1.error)}async function getDocumentExtension(r){const e=r.header.documentType;if(e===documentModelDocumentType)return"phdm";let M;const tr=window.ph?.reactorClient;if(tr){const{results:ir}=await tr.getDocumentModelModules();M=ir.find(dr=>dr.documentModel.global.id===e)?.utils.fileExtension}return(M??"phdm").replace(/^\.+|\.+$/g,"")||"phdm"}async function exportFile(r,e){if(!window.ph?.reactorClient)throw new Error("ReactorClient not initialized");const M=await getDocumentExtension(r),tr=`${r.header.name||"Untitled"}.${M}.phd`;if(!window.showSaveFilePicker)return downloadFile(r,tr);try{const rr=await window.showSaveFilePicker({suggestedName:tr});return await baseSaveToFileHandle(r,rr),rr}catch(rr){if(!(rr instanceof DOMException&&rr.name==="AbortError"))throw rr}}async function loadFile(r){const e=await baseLoadFromInput(r,ir=>ir,{checkHashes:!0}),M=window.ph?.reactorClient;if(!M)throw new Error("ReactorClient not initialized");const{results:tr}=await M.getDocumentModelModules(),rr=tr.find(ir=>ir.documentModel.global.id===e.header.documentType);if(!rr)throw new Error(`Document "${e.header.documentType}" is not supported`);return rr.utils.loadFromInput(r)}async function addDocument(r,e,M,tr,rr,ir,lr){const{isAllowedToCreateDocuments:dr}=getUserPermissions();if(!dr)throw new Error("User is not allowed to create documents");const hr=window.ph?.reactorClient;if(!hr)throw new Error("ReactorClient not initialized");const mr=(await hr.getDocumentModelModule(M)).utils.createDocument({...rr?.state});mr.header.name=e;let _r;try{_r=await hr.createDocumentInDrive(r,mr,tr)}catch(gr){throw logger$1.error("Error adding document",gr),new Error("There was an error adding document")}return{id:_r.header.id,name:_r.header.name,documentType:M,parentFolder:tr??null,kind:"file"}}async function addFile(r,e,M,tr){logger$1.verbose(`addFile(drive: ${e}, name: ${M}, folder: ${tr})`);const{isAllowedToCreateDocuments:rr}=getUserPermissions();if(!rr)throw new Error("User is not allowed to create files");const ir=await loadFile(r);let lr=!1;const dr=window.ph?.reactorClient;if(!dr)throw new Error("ReactorClient not initialized");try{await dr.get(ir.header.id),lr=!0}catch{}const hr=lr?generateId():ir.header.id,fr=createPresignedHeader(hr,ir.header.documentType);fr.lastModifiedAtUtcIso=ir.header.createdAtUtcIso,fr.meta=ir.header.meta,fr.name=M||ir.header.name;const mr={...ir,state:ir.initialState,operations:Object.keys(ir.operations).reduce((_r,gr)=>(_r[gr]=[],_r),{})};await addDocument(e,M||ir.header.name,ir.header.documentType,tr,mr,hr,ir.header.meta?.preferredEditor),uploadOperations(hr,ir.operations,queueOperations).catch(_r=>{throw _r})}async function addFileWithProgress(r,e,M,tr,rr,ir,lr){logger$1.verbose(`addFileWithProgress(drive: ${e}, name: ${M}, folder: ${tr})`);const dr=window.ph?.reactorClient;if(!dr)return;const{isAllowedToCreateDocuments:hr}=getUserPermissions();if(!hr)throw new Error("User is not allowed to create files");try{rr?.({stage:"loading",progress:0});const fr=await loadFile(r),mr=await isDocumentInLocation(fr,e,tr);if(mr.isDuplicate&&!lr){rr?.({stage:"conflict",progress:0,duplicateType:mr.duplicateType});return}mr.isDuplicate&&lr==="replace"&&mr.nodeId&&await deleteNode(e,mr.nodeId);const _r=getDocumentTypeIcon(fr);if(rr?.(_r?{stage:"loading",progress:10,documentType:_r}:{stage:"loading",progress:10}),!isDocumentTypeSupported(fr.header.documentType,ir))throw rr?.({stage:"unsupported-document-type",progress:100,error:`Document type ${fr.header.documentType} is not supported`}),new UnsupportedDocumentTypeError(fr.header.documentType);await dr.getDocumentModelModule(fr.header.documentType),rr?.({stage:"initializing",progress:10});let gr=!1;try{await dr.get(fr.header.id),gr=!0}catch{}const wr=gr?generateId():fr.header.id,yr=createPresignedHeader(wr,fr.header.documentType);yr.lastModifiedAtUtcIso=fr.header.createdAtUtcIso,yr.meta=fr.header.meta,yr.name=M||fr.header.name;const br={...fr,header:yr,state:fr.initialState,operations:Object.keys(fr.operations).reduce((vr,Sr)=>(vr[Sr]=[],vr),{})},Mr=await addDocument(e,M||fr.header.name,fr.header.documentType,tr,br,wr,fr.header.meta?.preferredEditor);if(!Mr)throw new Error("There was an error adding file");return rr?.({stage:"initializing",progress:20}),await uploadOperations(wr,fr.operations,queueOperations,{onProgress:vr=>{if(vr.totalOperations&&vr.uploadedOperations!==void 0){const Sr=vr.totalOperations>0?vr.uploadedOperations/vr.totalOperations:0,xr=20+Math.round(Sr*80);rr?.({stage:"uploading",progress:xr,totalOperations:vr.totalOperations,uploadedOperations:vr.uploadedOperations})}}}),rr?.({stage:"complete",progress:100}),Mr}catch(fr){if(!UnsupportedDocumentTypeError.isError(fr)){const mr=fr instanceof Error?fr.message:"Unknown error occurred";rr?.({stage:"failed",progress:100,error:mr})}throw fr}}async function addFolder(r,e,M){const{isAllowedToCreateDocuments:tr}=getUserPermissions();if(!tr)throw new Error("User is not allowed to create folders");const rr=window.ph?.reactorClient;if(!rr)throw new Error("ReactorClient not initialized");await rr.get(r);const ir=generateId(),dr=(await rr.execute(r,"main",[addFolder$1({id:ir,name:e,parentFolder:M})])).state.global.nodes.find(hr=>hr.id===ir);if(!dr||!isFolderNode(dr))throw new Error("There was an error adding folder");return dr}async function deleteNode(r,e){const{isAllowedToCreateDocuments:M}=getUserPermissions();if(!M)throw new Error("User is not allowed to delete documents");const tr=window.ph?.reactorClient;if(!tr)throw new Error("ReactorClient not initialized");await tr.execute(r,"main",[deleteNode$1({id:e})]),await tr.deleteDocument(e)}async function renameNode(r,e,M){const{isAllowedToCreateDocuments:tr}=getUserPermissions();if(!tr)throw new Error("User is not allowed to rename documents");const rr=window.ph?.reactorClient;if(!rr)throw new Error("ReactorClient not initialized");const lr=(await rr.execute(r,"main",[updateNode({id:e,name:M})])).state.global.nodes.find(dr=>dr.id===e);if(!lr)throw new Error("There was an error renaming node");return lr}async function renameDriveNode(r,e,M){const{isAllowedToCreateDocuments:tr}=getUserPermissions();if(!tr)throw new Error("User is not allowed to rename documents");const rr=window.ph?.reactorClient;if(!rr)throw new Error("ReactorClient not initialized");return await rr.execute(r,"main",[updateNode({id:e,name:M})]),(await rr.get(r)).state.global.nodes.find(lr=>lr.id===e)}async function moveNode(r,e,M){const{isAllowedToCreateDocuments:tr}=getUserPermissions();if(!tr)throw new Error("User is not allowed to move documents");const rr=window.ph?.reactorClient;if(!rr)throw new Error("ReactorClient not initialized");const ir=e.parentFolder??r,lr=M?.id??r;return await rr.moveChildren(ir,lr,[e.id])}async function _duplicateDocument(r,e,M=generateId()){const tr=await r.getDocumentModelModule(e.header.documentType);return replayDocument(e.initialState,e.operations,tr.reducer,createPresignedHeader(M,e.header.documentType))}async function copyNode(r,e,M){const tr=window.ph?.reactorClient;if(!tr)return;const{isAllowedToCreateDocuments:rr}=getUserPermissions();if(!rr)throw new Error("User is not allowed to copy documents");const ir=await tr.get(r),lr=generateNodesCopy({srcId:e.id,targetParentFolder:M?.id,targetName:e.name},()=>generateId(),ir.state.global.nodes),dr=new Map;for(const mr of lr){const _r=ir.state.global.nodes.find(gr=>gr.id===mr.srcId);if(_r){const gr=handleTargetNameCollisions({nodes:ir.state.global.nodes,srcName:mr.targetName||_r.name,targetParentFolder:mr.targetParentFolder||null});dr.set(mr.targetId,gr)}}const hr=lr.filter(mr=>{const _r=ir.state.global.nodes.find(gr=>gr.id===mr.srcId);return _r!==void 0&&isFileNode(_r)});for(const mr of hr)try{const _r=await tr.get(mr.srcId),gr=await _duplicateDocument(tr,_r,mr.targetId),wr=dr.get(mr.targetId);wr&&(gr.header.name=wr),await tr.createDocumentInDrive(r,gr,M?.id)}catch(_r){logger$1.error(`Error copying document ${mr.srcId}: ${String(_r)}`)}const fr=lr.map(mr=>copyNode$1(mr));return await queueActions(ir,fr)}function createDocumentAction(r){return{id:generateId(),type:"CREATE_DOCUMENT",scope:"document",timestampUtcMs:new Date().toISOString(),input:r}}function upgradeDocumentAction(r){return{id:generateId(),type:"UPGRADE_DOCUMENT",scope:"document",timestampUtcMs:new Date().toISOString(),input:r}}function deleteDocumentAction(r){const e={documentId:r};return{id:generateId(),type:"DELETE_DOCUMENT",scope:"document",timestampUtcMs:new Date().toISOString(),input:e}}function addRelationshipAction(r,e,M="child"){const tr={sourceId:r,targetId:e,relationshipType:M};return{id:generateId(),type:"ADD_RELATIONSHIP",scope:"document",timestampUtcMs:new Date().toISOString(),input:tr}}function removeRelationshipAction(r,e,M="child"){const tr={sourceId:r,targetId:e,relationshipType:M};return{id:generateId(),type:"REMOVE_RELATIONSHIP",scope:"document",timestampUtcMs:new Date().toISOString(),input:tr}}const byteToHex=[];for(let r=0;r<256;++r)byteToHex.push((r+256).toString(16).slice(1));function unsafeStringify(r,e=0){return(byteToHex[r[e+0]]+byteToHex[r[e+1]]+byteToHex[r[e+2]]+byteToHex[r[e+3]]+"-"+byteToHex[r[e+4]]+byteToHex[r[e+5]]+"-"+byteToHex[r[e+6]]+byteToHex[r[e+7]]+"-"+byteToHex[r[e+8]]+byteToHex[r[e+9]]+"-"+byteToHex[r[e+10]]+byteToHex[r[e+11]]+byteToHex[r[e+12]]+byteToHex[r[e+13]]+byteToHex[r[e+14]]+byteToHex[r[e+15]]).toLowerCase()}let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");getRandomValues=crypto.getRandomValues.bind(crypto)}return getRandomValues(rnds8)}const randomUUID=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),native={randomUUID};function v4(r,e,M){if(native.randomUUID&&!r)return native.randomUUID();r=r||{};const tr=r.random??r.rng?.()??rng();if(tr.length<16)throw new Error("Random bytes length must be >= 16");return tr[6]=tr[6]&15|64,tr[8]=tr[8]&63|128,unsafeStringify(tr)}function validateBatchStructure(r){const e=new Set;for(const ir of r){if(e.has(ir.key))throw new Error(`Duplicate plan key: ${ir.key}`);e.add(ir.key)}for(const ir of r)for(const lr of ir.dependsOn)if(!e.has(lr))throw new Error(`Job '${ir.key}' depends on non-existent key: ${lr}`);const M=new Set,tr=new Set,rr=ir=>{M.add(ir),tr.add(ir);const lr=r.find(dr=>dr.key===ir);if(lr){for(const dr of lr.dependsOn)if(M.has(dr)){if(tr.has(dr))return!0}else if(rr(dr))return!0}return tr.delete(ir),!1};for(const ir of r)if(!M.has(ir.key)&&rr(ir.key))throw new Error(`Dependency cycle detected involving key: ${ir.key}`)}function validateBatchRequest(r){validateBatchStructure(r);for(const e of r)if(e.actions.length===0)throw new Error(`Job '${e.key}' has empty actions array`)}function validateBatchLoadRequest(r){validateBatchStructure(r);for(const e of r)if(e.operations.length===0)throw new Error(`Job '${e.key}' has empty operations array`)}function validateActionScopes(r){for(const e of r.actions){const M=e.scope||"global";if(M!==r.scope)throw new Error(`Job '${r.key}' declares scope '${r.scope}' but action has scope '${M}'`)}}function validateOperationScopes(r){for(const e of r.operations){const M=e.action.scope||"global";if(M!==r.scope)throw new Error(`Job '${r.key}' declares scope '${r.scope}' but operation has scope '${M}'`)}}function topologicalSort(r){const e=[],M=new Set,tr=rr=>{if(M.has(rr))return;M.add(rr);const ir=r.find(lr=>lr.key===rr);if(ir)for(const lr of ir.dependsOn)tr(lr);e.push(rr)};for(const rr of r)tr(rr.key);return e}function toErrorInfo(r){return r instanceof Error?{message:r.message,stack:r.stack||new Error().stack||""}:{message:r,stack:new Error().stack||""}}function filterByType(r,e){return{results:r.results.filter(tr=>tr.header.documentType===e),options:r.options,nextCursor:r.nextCursor,next:r.next?async()=>{const tr=await r.next();return filterByType(tr,e)}:void 0}}function getSharedOperationScope(r){if(r.length===0)throw new Error("No operations provided");const e=r[0].action.scope;for(const[M,tr]of r.entries()){const rr=tr.action.scope;if(rr!==e)throw new Error(`All operations in load must share the same scope. Expected '${e}', received '${rr}' at position ${M}`)}return e}function getSharedActionScope(r){if(r.length===0)throw new Error("No actions provided");const e=r[0].scope;for(const M of r)if(M.scope!==e)throw new Error(`All actions must share the same scope. Expected '${e}', received '${M.scope}'`);return e}const signAction=async(r,e,M)=>{const tr=r.context?.signer?.signatures;if(tr&&tr.length>0)return r;const rr=await e.signAction(r,M);return{...r,context:{...r.context,signer:{user:{address:e.user?.address||"",networkId:e.user?.networkId||"",chainId:e.user?.chainId||0},app:{name:e.app?.name||"",key:e.app?.key||""},signatures:[rr]}}}},signActions=async(r,e,M)=>Promise.all(r.map(tr=>signAction(tr,e,M)));function buildSingleJobMeta(r,e){return{...e,batchId:v4(),batchJobIds:[r]}}class EventBusAggregateError extends Error{errors;constructor(e){const M=`EventBus emit failed with ${e.length} error(s): ${e.map(tr=>tr&&typeof tr=="object"&&"message"in tr?tr.message:String(tr)).join("; ")}`;super(M),this.name="EventBusAggregateError",this.errors=e}}const ReactorEventTypes={JOB_PENDING:10001,JOB_RUNNING:10002,JOB_WRITE_READY:10003,JOB_READ_READY:10004,JOB_FAILED:10005};var PropagationMode;(function(r){r.None="none",r.Cascade="cascade"})(PropagationMode||(PropagationMode={}));var RelationshipChangeType;(function(r){r.Added="added",r.Removed="removed"})(RelationshipChangeType||(RelationshipChangeType={}));var JobStatus;(function(r){r.PENDING="PENDING",r.RUNNING="RUNNING",r.WRITE_READY="WRITE_READY",r.READ_READY="READ_READY",r.FAILED="FAILED"})(JobStatus||(JobStatus={}));function isTerminalStatus(r){return r===JobStatus.READ_READY||r===JobStatus.FAILED}class JobAwaiter{eventBus;getJobStatus;pendingJobs=new Map;unsubscribers=[];constructor(e,M){this.eventBus=e,this.getJobStatus=M,this.subscribeToEvents()}subscribeToEvents(){this.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY,async(e,M)=>{await this.handleWriteReady(M)})),this.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_READ_READY,async(e,M)=>{await this.handleReadReady(M)})),this.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_FAILED,async(e,M)=>{await this.handleJobFailed(M)}))}shutdown(){for(const e of this.unsubscribers)e();this.unsubscribers=[];for(const[,e]of this.pendingJobs)for(const M of e)M.reject(new Error("JobAwaiter destroyed"));this.pendingJobs.clear()}async waitForJob(e,M){if(M?.aborted)throw new Error("Operation aborted");const tr=await this.getJobStatus(e,M);return isTerminalStatus(tr.status)?tr:new Promise((ir,lr)=>{const dr={resolve:ir,reject:lr,signal:M},hr=this.pendingJobs.get(e)||[];if(hr.push(dr),this.pendingJobs.set(e,hr),M){const fr=()=>{const mr=this.pendingJobs.get(e);if(mr){const _r=mr.indexOf(dr);_r!==-1&&(mr.splice(_r,1),mr.length===0&&this.pendingJobs.delete(e),dr.reject(new Error("Operation aborted")))}};M.addEventListener("abort",fr,{once:!0})}})}async handleWriteReady(e){const M=e.jobId;await this.checkAndResolveWaiters(M)}async handleReadReady(e){const M=e.jobId;await this.checkAndResolveWaiters(M)}async handleJobFailed(e){await this.checkAndResolveWaiters(e.jobId)}async checkAndResolveWaiters(e){const M=this.pendingJobs.get(e);if(!(!M||M.length===0))try{const tr=M.filter(ir=>!ir.signal?.aborted);if(tr.length===0){this.pendingJobs.delete(e);return}const rr=await this.getJobStatus(e,tr[0].signal);if(isTerminalStatus(rr.status)){this.pendingJobs.delete(e);for(const ir of tr)ir.resolve(rr);for(const ir of M)ir.signal?.aborted&&ir.reject(new Error("Operation aborted"))}}catch(tr){this.pendingJobs.delete(e);for(const rr of M)rr.reject(tr instanceof Error?tr:new Error(String(tr)))}}}var DocumentChangeType;(function(r){r.Created="created",r.Deleted="deleted",r.Updated="updated",r.ParentAdded="parent_added",r.ParentRemoved="parent_removed",r.ChildAdded="child_added",r.ChildRemoved="child_removed"})(DocumentChangeType||(DocumentChangeType={}));class ReactorClient{logger;reactor;signer;subscriptionManager;jobAwaiter;documentIndexer;documentView;constructor(e,M,tr,rr,ir,lr,dr){this.logger=e,this.reactor=M,this.signer=tr,this.subscriptionManager=rr,this.jobAwaiter=ir,this.documentIndexer=lr,this.documentView=dr,this.logger.verbose("ReactorClient initialized")}async getDocumentModelModules(e,M,tr){return this.logger.verbose("getDocumentModels(@namespace, @paging)",e,M),this.reactor.getDocumentModels(e,M,tr)}async getDocumentModelModule(e){const tr=(await this.reactor.getDocumentModels()).results.find(rr=>rr.documentModel.global.id===e);if(!tr)throw new Error(`Document model module not found for type: ${e}`);return tr}async get(e,M,tr){return this.logger.verbose("get(@identifier, @view)",e,M),await this.reactor.getByIdOrSlug(e,M,void 0,tr)}async getOperations(e,M,tr,rr,ir){this.logger.verbose("getOperations(@documentIdentifier, @view, @filter, @paging)",e,M,tr,rr);const lr=await this.documentView.resolveIdOrSlug(e,M,void 0,ir),dr=await this.reactor.getOperations(lr,M,tr,rr,void 0,ir),hr=[];for(const mr of Object.values(dr))hr.push(...mr.results);return hr.sort((mr,_r)=>mr.index-_r.index),{results:hr,options:rr||{cursor:"0",limit:100}}}async getChildren(e,M,tr,rr){this.logger.verbose("getChildren(@parentIdentifier, @view, @paging)",e,M,tr);const ir=await this.documentView.resolveIdOrSlug(e,M,void 0,rr),dr=(await this.documentIndexer.getOutgoing(ir,void 0,void 0,void 0,rr)).results.map(hr=>hr.targetId);return dr.length===0?{results:[],options:tr||{cursor:"0",limit:0}}:this.reactor.find({ids:dr},M,tr,void 0,rr)}async getParents(e,M,tr,rr){this.logger.verbose("getParents(@childIdentifier, @view, @paging)",e,M,tr);const ir=await this.documentView.resolveIdOrSlug(e,M,void 0,rr),dr=(await this.documentIndexer.getIncoming(ir,void 0,void 0,void 0,rr)).results.map(hr=>hr.sourceId);return dr.length===0?{results:[],options:tr||{cursor:"0",limit:0}}:this.reactor.find({ids:dr},M,tr,void 0,rr)}async find(e,M,tr,rr){return this.logger.verbose("find(@search, @view, @paging)",e,M,tr),this.reactor.find(e,M,tr,void 0,rr)}async create(e,M,tr){this.logger.verbose("create(@id, @parentIdentifier)",e.header.id,M);const rr=e.header.id,ir={model:e.header.documentType,version:0,documentId:rr,signing:{signature:rr,publicKey:e.header.sig.publicKey,nonce:e.header.sig.nonce,createdAtUtcIso:e.header.createdAtUtcIso,documentType:e.header.documentType},slug:e.header.slug,name:e.header.name,branch:e.header.branch,meta:e.header.meta,protocolVersions:e.header.protocolVersions??{"base-reducer":2}},lr=await signActions([createDocumentAction(ir),upgradeDocumentAction({documentId:rr,model:e.header.documentType,fromVersion:0,toVersion:e.state.document.version,initialState:e.state})],this.signer,tr),dr=[{key:"create",documentId:rr,scope:getSharedActionScope(lr),branch:"main",actions:lr,dependsOn:[]}];if(M){const mr=await signActions([addRelationshipAction(M,rr,"child")],this.signer,tr);dr.push({key:"parent",documentId:M,scope:getSharedActionScope(mr),branch:"main",actions:mr,dependsOn:["create"]})}const hr=await this.reactor.executeBatch({jobs:dr},tr),fr=await Promise.all(Object.values(hr.jobs).map(mr=>this.waitForJob(mr,tr)));for(const mr of fr)if(mr.status===JobStatus.FAILED)throw new Error(mr.error?.message);return await this.reactor.get(rr)}async createEmpty(e,M,tr){this.logger.verbose("createEmpty(@documentModelType, @options)",e,M);const ir=(await this.reactor.getDocumentModels(void 0,void 0,tr)).results.filter(hr=>hr.documentModel.global.id===e);let lr;if(M?.documentModelVersion!==void 0){if(lr=ir.find(hr=>hr.version===M.documentModelVersion),!lr)throw new Error(`Document model not found for type: ${e} with version: ${M.documentModelVersion}`)}else if(lr=ir.reduce((hr,fr)=>{if(hr===void 0)return fr;const mr=fr.version??0,_r=hr.version??0;return mr>_r?fr:hr},void 0),!lr)throw new Error(`Document model not found for type: ${e}`);const dr=lr.utils.createDocument();return dr.state.document.version=lr.version??1,this.create(dr,M?.parentIdentifier,tr)}async createDocumentInDrive(e,M,tr,rr){this.logger.verbose("createDocumentInDrive(@driveId, @document, @parentFolder)",e,M,tr);const ir=M.header.id,lr={model:M.header.documentType,version:0,documentId:M.header.id,signing:{signature:M.header.id,publicKey:M.header.sig.publicKey,nonce:M.header.sig.nonce,createdAtUtcIso:M.header.createdAtUtcIso,documentType:M.header.documentType},slug:M.header.slug,name:M.header.name,branch:M.header.branch,meta:M.header.meta,protocolVersions:M.header.protocolVersions??{"base-reducer":2}},dr=await signActions([createDocumentAction(lr),upgradeDocumentAction({documentId:M.header.id,model:M.header.documentType,fromVersion:0,toVersion:1,initialState:M.state}),addRelationshipAction(e,ir,"child")],this.signer,rr),hr=await signActions([addFile$1({id:ir,name:M.header.name,documentType:M.header.documentType,parentFolder:tr})],this.signer,rr),fr=await this.reactor.executeBatch({jobs:[{key:"document",documentId:ir,scope:getSharedActionScope(dr),branch:"main",actions:dr,dependsOn:[]},{key:"drive",documentId:e,scope:getSharedActionScope(hr),branch:"main",actions:hr,dependsOn:["document"]}]},rr),mr=await Promise.all(Object.values(fr.jobs).map(_r=>this.waitForJob(_r,rr)));for(const _r of mr)if(_r.status===JobStatus.FAILED)throw new Error(_r.error?.message);return await this.reactor.get(ir)}async execute(e,M,tr,rr){this.logger.verbose("execute(@documentIdentifier, @branch, @count actions)",e,M,tr.length);const ir=await signActions(tr,this.signer,rr),lr=await this.reactor.execute(e,M,ir,rr),dr=await this.waitForJob(lr,rr);if(dr.status===JobStatus.FAILED)throw new Error(dr.error?.message);const hr={branch:M};return await this.reactor.getByIdOrSlug(e,hr,dr.consistencyToken,rr)}async executeAsync(e,M,tr,rr){this.logger.verbose("executeAsync(@documentIdentifier, @branch, @count actions)",e,M,tr.length);const ir=await signActions(tr,this.signer,rr);return this.reactor.execute(e,M,ir,rr)}async rename(e,M,tr="main",rr){return this.logger.verbose("rename(@documentIdentifier, @name, @branch)",e,M,tr),this.execute(e,tr,[actions.setName(M)],rr)}async addChildren(e,M,tr="main",rr){this.logger.verbose("addChildren(@parentIdentifier, @count children, @branch)",e,M.length,tr);const ir=await this.reactor.addChildren(e,M,tr,this.signer,rr),lr=await this.waitForJob(ir,rr);if(lr.status===JobStatus.FAILED)throw new Error(lr.error?.message);return await this.reactor.getByIdOrSlug(e,{branch:tr},lr.consistencyToken,rr)}async removeChildren(e,M,tr="main",rr){this.logger.verbose("removeChildren(@parentIdentifier, @count children, @branch)",e,M.length,tr);const ir=await this.reactor.removeChildren(e,M,tr,this.signer,rr),lr=await this.waitForJob(ir,rr);if(lr.status===JobStatus.FAILED)throw new Error(lr.error?.message);return await this.reactor.getByIdOrSlug(e,{branch:tr},lr.consistencyToken,rr)}async moveChildren(e,M,tr,rr="main",ir){this.logger.verbose("moveChildren(@sourceParentIdentifier, @targetParentIdentifier, @count children, @branch)",e,M,tr.length,rr);const lr=await this.reactor.removeChildren(e,tr,rr,this.signer,ir),dr=await this.waitForJob(lr,ir);if(dr.status===JobStatus.FAILED)throw new Error(dr.error?.message);const hr=await this.reactor.addChildren(M,tr,rr,this.signer,ir),fr=await this.waitForJob(hr,ir);if(fr.status===JobStatus.FAILED)throw new Error(fr.error?.message);const mr=await this.reactor.getByIdOrSlug(e,{branch:rr},dr.consistencyToken,ir),_r=await this.reactor.getByIdOrSlug(M,{branch:rr},fr.consistencyToken,ir);return{source:mr,target:_r}}async loadBatch(e,M){this.logger.verbose("loadBatch(@count jobs)",e.jobs.length);const tr=await this.reactor.loadBatch(e,M),rr=await Promise.all(Object.entries(tr.jobs).map(async([ir,lr])=>{const dr=await this.waitForJob(lr,M);return[ir,dr]}));for(const[,ir]of rr)if(ir.status===JobStatus.FAILED)throw new Error(ir.error?.message);return{jobs:Object.fromEntries(rr)}}async deleteDocument(e,M,tr){this.logger.verbose("deleteDocument(@identifier, @propagate)",e,M);const rr=[];if(M===PropagationMode.Cascade){const dr=[],hr=[e],fr=new Set;for(;hr.length>0;){const mr=hr.shift();if(fr.has(mr))continue;if(fr.add(mr),tr?.aborted)throw new Error("Operation aborted");const _r=await this.documentIndexer.getOutgoing(mr,["child"],void 0,void 0,tr);for(const gr of _r.results)fr.has(gr.targetId)||(dr.push(gr.targetId),hr.push(gr.targetId))}for(const mr of dr){const _r=await this.reactor.deleteDocument(mr,this.signer,tr);rr.push(_r)}}const ir=await this.reactor.deleteDocument(e,this.signer,tr);rr.push(ir);const lr=await Promise.all(rr.map(dr=>this.waitForJob(dr,tr)));for(const dr of lr)if(dr.status===JobStatus.FAILED)throw new Error(dr.error?.message)}async deleteDocuments(e,M,tr){this.logger.verbose("deleteDocuments(@count identifiers, @propagate)",e.length,M);const rr=e.map(ir=>this.deleteDocument(ir,M,tr));await Promise.all(rr)}async getJobStatus(e,M){return this.logger.verbose("getJobStatus(@jobId)",e),this.reactor.getJobStatus(e,M)}async waitForJob(e,M){const tr=typeof e=="string"?e:e.id;return this.logger.verbose("waitForJob(@id)",tr),this.jobAwaiter.waitForJob(tr,M)}subscribe(e,M,tr){this.logger.verbose("subscribe(@search, @view)",e,tr);const rr=this.subscriptionManager.onDocumentCreated(hr=>{(async()=>{try{const fr=await Promise.all(hr.results.map(mr=>this.reactor.get(mr,tr,void 0,void 0)));M({type:DocumentChangeType.Created,documents:fr})}catch{}})()},e),ir=this.subscriptionManager.onDocumentDeleted(hr=>{M({type:DocumentChangeType.Deleted,documents:[],context:{childId:hr[0]}})},e),lr=this.subscriptionManager.onDocumentStateUpdated(hr=>{M({type:DocumentChangeType.Updated,documents:hr.results})},e,tr),dr=this.subscriptionManager.onRelationshipChanged((hr,fr,mr)=>{M({type:mr===RelationshipChangeType.Added?DocumentChangeType.ChildAdded:DocumentChangeType.ChildRemoved,documents:[],context:{parentId:hr,childId:fr}})},e);return()=>{rr(),ir(),lr(),dr()}}}var p$1=Object.create,i=Object.defineProperty,c=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,l$2=Object.getPrototypeOf,s$2=Object.prototype.hasOwnProperty,a=r=>{throw TypeError(r)},_$1=(r,e,M)=>e in r?i(r,e,{enumerable:!0,configurable:!0,writable:!0,value:M}):r[e]=M,d=(r,e)=>()=>(r&&(e=r(r=0)),e),D$1=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),F$1=(r,e)=>{for(var M in e)i(r,M,{get:e[M],enumerable:!0})},g$3=(r,e,M,tr)=>{if(e&&typeof e=="object"||typeof e=="function")for(let rr of f(e))!s$2.call(r,rr)&&rr!==M&&i(r,rr,{get:()=>e[rr],enumerable:!(tr=c(e,rr))||tr.enumerable});return r},L$3=(r,e,M)=>(M=r!=null?p$1(l$2(r)):{},g$3(i(M,"default",{value:r,enumerable:!0}),r)),P$1=(r,e,M)=>_$1(r,typeof e!="symbol"?e+"":e,M),n$1=(r,e,M)=>e.has(r)||a("Cannot "+M),h$1=(r,e,M)=>(n$1(r,e,"read from private field"),M?M.call(r):e.get(r)),R$1=(r,e,M)=>e.has(r)?a("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,M),x$3=(r,e,M,tr)=>(n$1(r,e,"write to private field"),e.set(r,M),M),T$2=(r,e,M)=>(n$1(r,e,"access private method"),M),U$1=(r,e,M,tr)=>({set _(rr){x$3(r,e,rr)},get _(){return h$1(r,e,tr)}}),u=d(()=>{}),hn={};F$1(hn,{ABSTIME:()=>Et,ACLITEM:()=>Vt,BIT:()=>jt,BOOL:()=>be,BPCHAR:()=>_e$1,BYTEA:()=>ge$1,CHAR:()=>gt,CID:()=>St,CIDR:()=>Tt,CIRCLE:()=>Ut,DATE:()=>He$1,FLOAT4:()=>Qe,FLOAT8:()=>We$1,GTSVECTOR:()=>rn,INET:()=>kt,INT2:()=>ve,INT4:()=>Ge$1,INT8:()=>we$1,INTERVAL:()=>vt,JSON:()=>Ae,JSONB:()=>Ye$1,MACADDR:()=>Ot,MACADDR8:()=>Nt,MONEY:()=>Lt,NUMERIC:()=>Wt,OID:()=>je$1,PATH:()=>Mt,PG_DEPENDENCIES:()=>en,PG_LSN:()=>Xt,PG_NDISTINCT:()=>Zt,PG_NODE_TREE:()=>Bt,POLYGON:()=>Rt,REFCURSOR:()=>_t$1,REGCLASS:()=>Yt,REGCONFIG:()=>sn,REGDICTIONARY:()=>an,REGNAMESPACE:()=>on,REGOPER:()=>Ht,REGOPERATOR:()=>qt,REGPROC:()=>wt,REGPROCEDURE:()=>zt,REGROLE:()=>un,REGTYPE:()=>$t,RELTIME:()=>Ct,SMGR:()=>It,TEXT:()=>V,TID:()=>At,TIME:()=>Ft,TIMESTAMP:()=>qe,TIMESTAMPTZ:()=>xe$1,TIMETZ:()=>Gt,TINTERVAL:()=>Pt,TSQUERY:()=>nn,TSVECTOR:()=>tn,TXID_SNAPSHOT:()=>Jt,UUID:()=>Kt,VARBIT:()=>Qt,VARCHAR:()=>ze,XID:()=>xt,XML:()=>Dt,arrayParser:()=>yn,arraySerializer:()=>Ke$1,parseType:()=>ue$1,parsers:()=>ln,serializers:()=>cn,types:()=>$e});u();var ht=globalThis.JSON.parse,bt=globalThis.JSON.stringify,be=16,ge$1=17,gt=18,we$1=20,ve=21,Ge$1=23,wt=24,V=25,je$1=26,At=27,xt=28,St=29,Ae=114,Dt=142,Bt=194,It=210,Mt=602,Rt=604,Tt=650,Qe=700,We$1=701,Et=702,Ct=703,Pt=704,Ut=718,Nt=774,Lt=790,Ot=829,kt=869,Vt=1033,_e$1=1042,ze=1043,He$1=1082,Ft=1083,qe=1114,xe$1=1184,vt=1186,Gt=1266,jt=1560,Qt=1562,Wt=1700,_t$1=1790,zt=2202,Ht=2203,qt=2204,Yt=2205,$t=2206,Kt=2950,Jt=2970,Xt=3220,Zt=3361,en=3402,tn=3614,nn=3615,rn=3642,sn=3734,an=3769,Ye$1=3802,on=4089,un=4096,$e={string:{to:V,from:[V,ze,_e$1],serialize:r=>{if(typeof r=="string")return r;if(typeof r=="number")return r.toString();throw new Error("Invalid input for string type")},parse:r=>r},number:{to:0,from:[ve,Ge$1,je$1,Qe,We$1],serialize:r=>r.toString(),parse:r=>+r},bigint:{to:we$1,from:[we$1],serialize:r=>r.toString(),parse:r=>{let e=BigInt(r);return e<Number.MIN_SAFE_INTEGER||e>Number.MAX_SAFE_INTEGER?e:Number(e)}},json:{to:Ae,from:[Ae,Ye$1],serialize:r=>typeof r=="string"?r:bt(r),parse:r=>ht(r)},boolean:{to:be,from:[be],serialize:r=>{if(typeof r!="boolean")throw new Error("Invalid input for boolean type");return r?"t":"f"},parse:r=>r==="t"},date:{to:xe$1,from:[He$1,qe,xe$1],serialize:r=>{if(typeof r=="string")return r;if(typeof r=="number")return new Date(r).toISOString();if(r instanceof Date)return r.toISOString();throw new Error("Invalid input for date type")},parse:r=>new Date(r)},bytea:{to:ge$1,from:[ge$1],serialize:r=>{if(!(r instanceof Uint8Array))throw new Error("Invalid input for bytea type");return"\\x"+Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")},parse:r=>{let e=r.slice(2);return Uint8Array.from({length:e.length/2},(M,tr)=>parseInt(e.substring(tr*2,(tr+1)*2),16))}}},Se$1=pn($e),ln=Se$1.parsers,cn=Se$1.serializers;function ue$1(r,e,M){if(r===null)return null;let tr=M?.[e]??Se$1.parsers[e];return tr?tr(r,e):r}function pn(r){return Object.keys(r).reduce(({parsers:e,serializers:M},tr)=>{let{to:rr,from:ir,serialize:lr,parse:dr}=r[tr];return M[rr]=lr,M[tr]=lr,e[tr]=dr,Array.isArray(ir)?ir.forEach(hr=>{e[hr]=dr,M[hr]=lr}):(e[ir]=dr,M[ir]=lr),{parsers:e,serializers:M}},{parsers:{},serializers:{}})}var dn=/\\/g,fn=/"/g;function mn(r){return r.replace(dn,"\\\\").replace(fn,'\\"')}function Ke$1(r,e,M){if(Array.isArray(r)===!1)return r;if(!r.length)return"{}";let tr=r[0],rr=M===1020?";":",";return Array.isArray(tr)?`{${r.map(ir=>Ke$1(ir,e,M)).join(rr)}}`:`{${r.map(ir=>(ir===void 0&&(ir=null),ir===null?"null":'"'+mn(e?e(ir):ir.toString())+'"')).join(rr)}}`}var he$1={i:0,char:null,str:"",quoted:!1,last:0,p:null};function yn(r,e,M){return he$1.i=he$1.last=0,Je(he$1,r,e,M)[0]}function Je(r,e,M,tr){let rr=[],ir=tr===1020?";":",";for(;r.i<e.length;r.i++){if(r.char=e[r.i],r.quoted)r.char==="\\"?r.str+=e[++r.i]:r.char==='"'?(rr.push(M?M(r.str):r.str),r.str="",r.quoted=e[r.i+1]==='"',r.last=r.i+2):r.str+=r.char;else if(r.char==='"')r.quoted=!0;else if(r.char==="{")r.last=++r.i,rr.push(Je(r,e,M,tr));else if(r.char==="}"){r.quoted=!1,r.last<r.i&&rr.push(M?M(e.slice(r.last,r.i)):e.slice(r.last,r.i)),r.last=r.i+1;break}else r.char===ir&&r.p!=="}"&&r.p!=='"'&&(rr.push(M?M(e.slice(r.last,r.i)):e.slice(r.last,r.i)),r.last=r.i+1);r.p=r.char}return r.last<r.i&&rr.push(M?M(e.slice(r.last,r.i+1)):e.slice(r.last,r.i+1)),rr}var wn={};F$1(wn,{parseDescribeStatementResults:()=>De,parseResults:()=>bn});u();function bn(r,e,M,tr){let rr=[],ir={rows:[],fields:[]},lr=0,dr={...e,...M?.parsers};return r.forEach(hr=>{switch(hr.name){case"rowDescription":{let fr=hr;ir.fields=fr.fields.map(mr=>({name:mr.name,dataTypeID:mr.dataTypeID}));break}case"dataRow":{if(!ir)break;let fr=hr;M?.rowMode==="array"?ir.rows.push(fr.fields.map((mr,_r)=>ue$1(mr,ir.fields[_r].dataTypeID,dr))):ir.rows.push(Object.fromEntries(fr.fields.map((mr,_r)=>[ir.fields[_r].name,ue$1(mr,ir.fields[_r].dataTypeID,dr)])));break}case"commandComplete":{lr+=gn(hr),rr.push({...ir,affectedRows:lr,...tr?{blob:tr}:{}}),ir={rows:[],fields:[]};break}}}),rr.length===0&&rr.push({affectedRows:0,rows:[],fields:[]}),rr}function gn(r){let e=r.text.split(" ");switch(e[0]){case"INSERT":return parseInt(e[2],10);case"UPDATE":case"DELETE":case"COPY":case"MERGE":return parseInt(e[1],10);default:return 0}}function De(r){let e=r.find(M=>M.name==="parameterDescription");return e?e.dataTypeIDs:[]}var Ue$1={};F$1(Ue$1,{AuthenticationCleartextPassword:()=>v,AuthenticationMD5Password:()=>G$1,AuthenticationOk:()=>F,AuthenticationSASL:()=>j,AuthenticationSASLContinue:()=>Q$1,AuthenticationSASLFinal:()=>W,BackendKeyDataMessage:()=>K$1,CommandCompleteMessage:()=>Z$1,CopyDataMessage:()=>_,CopyResponse:()=>z,DataRowMessage:()=>ee,DatabaseError:()=>C$2,Field:()=>H$1,NoticeMessage:()=>te$1,NotificationResponseMessage:()=>J$1,ParameterDescriptionMessage:()=>Y$1,ParameterStatusMessage:()=>$$1,ReadyForQueryMessage:()=>X,RowDescriptionMessage:()=>q$1,bindComplete:()=>Ie,closeComplete:()=>Me,copyDone:()=>Pe,emptyQuery:()=>Ce,noData:()=>Re,parseComplete:()=>Be$1,portalSuspended:()=>Te,replicationStart:()=>Ee});u();var Be$1={name:"parseComplete",length:5},Ie={name:"bindComplete",length:5},Me={name:"closeComplete",length:5},Re={name:"noData",length:5},Te={name:"portalSuspended",length:5},Ee={name:"replicationStart",length:4},Ce={name:"emptyQuery",length:4},Pe={name:"copyDone",length:4},F=class{constructor(r){this.length=r,this.name="authenticationOk"}},v=class{constructor(r){this.length=r,this.name="authenticationCleartextPassword"}},G$1=class{constructor(e,M){this.length=e,this.salt=M,this.name="authenticationMD5Password"}},j=class{constructor(r,e){this.length=r,this.mechanisms=e,this.name="authenticationSASL"}},Q$1=class{constructor(e,M){this.length=e,this.data=M,this.name="authenticationSASLContinue"}},W=class{constructor(r,e){this.length=r,this.data=e,this.name="authenticationSASLFinal"}},C$2=class extends Error{constructor(e,M,tr){super(e),this.length=M,this.name=tr}},_=class{constructor(r,e){this.length=r,this.chunk=e,this.name="copyData"}},z=class{constructor(r,e,M,tr){this.length=r,this.name=e,this.binary=M,this.columnTypes=new Array(tr)}},H$1=class{constructor(e,M,tr,rr,ir,lr,dr){this.name=e,this.tableID=M,this.columnID=tr,this.dataTypeID=rr,this.dataTypeSize=ir,this.dataTypeModifier=lr,this.format=dr}},q$1=class{constructor(e,M){this.length=e,this.fieldCount=M,this.name="rowDescription",this.fields=new Array(this.fieldCount)}},Y$1=class{constructor(e,M){this.length=e,this.parameterCount=M,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}},$$1=class{constructor(e,M,tr){this.length=e,this.parameterName=M,this.parameterValue=tr,this.name="parameterStatus"}},K$1=class{constructor(e,M,tr){this.length=e,this.processID=M,this.secretKey=tr,this.name="backendKeyData"}},J$1=class{constructor(e,M,tr,rr){this.length=e,this.processId=M,this.channel=tr,this.payload=rr,this.name="notification"}},X=class{constructor(r,e){this.length=r,this.status=e,this.name="readyForQuery"}},Z$1=class{constructor(e,M){this.length=e,this.text=M,this.name="commandComplete"}},ee=class{constructor(r,e){this.length=r,this.fields=e,this.name="dataRow",this.fieldCount=e.length}},te$1=class{constructor(e,M){this.length=e,this.message=M,this.name="notice"}},zn={};F$1(zn,{Parser:()=>ye$1,messages:()=>Ue$1,serialize:()=>k$1});u();u();u();u();function P(r){let e=r.length;for(let M=r.length-1;M>=0;M--){let tr=r.charCodeAt(M);tr>127&&tr<=2047?e++:tr>2047&&tr<=65535&&(e+=2),tr>=56320&&tr<=57343&&M--}return e}var b,g$2,N,ce$2,L$2,x$2,le$1,U,Xe$1,T$1=class{constructor(e=256){this.size=e,R$1(this,x$2),R$1(this,b),R$1(this,g$2,5),R$1(this,N,!1),R$1(this,ce$2,new TextEncoder),R$1(this,L$2,0),x$3(this,b,T$2(this,x$2,le$1).call(this,e))}addInt32(e){return T$2(this,x$2,U).call(this,4),h$1(this,b).setInt32(h$1(this,g$2),e,h$1(this,N)),x$3(this,g$2,h$1(this,g$2)+4),this}addInt16(e){return T$2(this,x$2,U).call(this,2),h$1(this,b).setInt16(h$1(this,g$2),e,h$1(this,N)),x$3(this,g$2,h$1(this,g$2)+2),this}addCString(e){return e&&this.addString(e),T$2(this,x$2,U).call(this,1),h$1(this,b).setUint8(h$1(this,g$2),0),U$1(this,g$2)._++,this}addString(e=""){let M=P(e);return T$2(this,x$2,U).call(this,M),h$1(this,ce$2).encodeInto(e,new Uint8Array(h$1(this,b).buffer,h$1(this,g$2))),x$3(this,g$2,h$1(this,g$2)+M),this}add(e){return T$2(this,x$2,U).call(this,e.byteLength),new Uint8Array(h$1(this,b).buffer).set(new Uint8Array(e),h$1(this,g$2)),x$3(this,g$2,h$1(this,g$2)+e.byteLength),this}flush(e){let M=T$2(this,x$2,Xe$1).call(this,e);return x$3(this,g$2,5),x$3(this,b,T$2(this,x$2,le$1).call(this,this.size)),new Uint8Array(M)}};b=new WeakMap,g$2=new WeakMap,N=new WeakMap,ce$2=new WeakMap,L$2=new WeakMap,x$2=new WeakSet,le$1=function(r){return new DataView(new ArrayBuffer(r))},U=function(r){if(h$1(this,b).byteLength-h$1(this,g$2)<r){let e=h$1(this,b).buffer,M=e.byteLength+(e.byteLength>>1)+r;x$3(this,b,T$2(this,x$2,le$1).call(this,M)),new Uint8Array(h$1(this,b).buffer).set(new Uint8Array(e))}},Xe$1=function(r){if(r){h$1(this,b).setUint8(h$1(this,L$2),r);let e=h$1(this,g$2)-(h$1(this,L$2)+1);h$1(this,b).setInt32(h$1(this,L$2)+1,e,h$1(this,N))}return h$1(this,b).buffer.slice(r?0:5,h$1(this,g$2))};var m=new T$1,An=r=>{m.addInt16(3).addInt16(0);for(let tr of Object.keys(r))m.addCString(tr).addCString(r[tr]);m.addCString("client_encoding").addCString("UTF8");let e=m.addCString("").flush(),M=e.byteLength+4;return new T$1().addInt32(M).add(e).flush()},xn=()=>{let r=new DataView(new ArrayBuffer(8));return r.setInt32(0,8,!1),r.setInt32(4,80877103,!1),new Uint8Array(r.buffer)},Sn=r=>m.addCString(r).flush(112),Dn=(r,e)=>(m.addCString(r).addInt32(P(e)).addString(e),m.flush(112)),Bn=r=>m.addString(r).flush(112),In=r=>m.addCString(r).flush(81),Mn=[],Rn=r=>{let e=r.name??"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let M=m.addCString(e).addCString(r.text).addInt16(r.types?.length??0);return r.types?.forEach(tr=>M.addInt32(tr)),m.flush(80)},O$2=new T$1,Tn=(r,e)=>{for(let M=0;M<r.length;M++){let tr=e?e(r[M],M):r[M];if(tr===null)m.addInt16(0),O$2.addInt32(-1);else if(tr instanceof ArrayBuffer||ArrayBuffer.isView(tr)){let rr=ArrayBuffer.isView(tr)?tr.buffer.slice(tr.byteOffset,tr.byteOffset+tr.byteLength):tr;m.addInt16(1),O$2.addInt32(rr.byteLength),O$2.add(rr)}else m.addInt16(0),O$2.addInt32(P(tr)),O$2.addString(tr)}},En=(r={})=>{let e=r.portal??"",M=r.statement??"",tr=r.binary??!1,rr=r.values??Mn,ir=rr.length;return m.addCString(e).addCString(M),m.addInt16(ir),Tn(rr,r.valueMapper),m.addInt16(ir),m.add(O$2.flush()),m.addInt16(tr?1:0),m.flush(66)},Cn=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Pn=r=>{if(!r||!r.portal&&!r.rows)return Cn;let e=r.portal??"",M=r.rows??0,tr=P(e),rr=4+tr+1+4,ir=new DataView(new ArrayBuffer(1+rr));return ir.setUint8(0,69),ir.setInt32(1,rr,!1),new TextEncoder().encodeInto(e,new Uint8Array(ir.buffer,5)),ir.setUint8(tr+5,0),ir.setUint32(ir.byteLength-4,M,!1),new Uint8Array(ir.buffer)},Un=(r,e)=>{let M=new DataView(new ArrayBuffer(16));return M.setInt32(0,16,!1),M.setInt16(4,1234,!1),M.setInt16(6,5678,!1),M.setInt32(8,r,!1),M.setInt32(12,e,!1),new Uint8Array(M.buffer)},Ne=(r,e)=>{let M=new T$1;return M.addCString(e),M.flush(r)},Nn=m.addCString("P").flush(68),Ln=m.addCString("S").flush(68),On=r=>r.name?Ne(68,`${r.type}${r.name??""}`):r.type==="P"?Nn:Ln,kn=r=>{let e=`${r.type}${r.name??""}`;return Ne(67,e)},Vn=r=>m.add(r).flush(100),Fn=r=>Ne(102,r),pe$1=r=>new Uint8Array([r,0,0,0,4]),vn=pe$1(72),Gn=pe$1(83),jn=pe$1(88),Qn=pe$1(99),k$1={startup:An,password:Sn,requestSsl:xn,sendSASLInitialResponseMessage:Dn,sendSCRAMClientFinalMessage:Bn,query:In,parse:Rn,bind:En,execute:Pn,describe:On,close:kn,flush:()=>vn,sync:()=>Gn,end:()=>jn,copyData:Vn,copyDone:()=>Qn,copyFail:Fn,cancel:Un};u();u();var Le$1={text:0,binary:1};u();var Wn=new ArrayBuffer(0),R,w$1,fe$1,me$1,ne$1,de$1=class{constructor(e=0){R$1(this,R,new DataView(Wn)),R$1(this,w$1),R$1(this,fe$1,"utf-8"),R$1(this,me$1,new TextDecoder(h$1(this,fe$1))),R$1(this,ne$1,!1),x$3(this,w$1,e)}setBuffer(e,M){x$3(this,w$1,e),x$3(this,R,new DataView(M))}int16(){let e=h$1(this,R).getInt16(h$1(this,w$1),h$1(this,ne$1));return x$3(this,w$1,h$1(this,w$1)+2),e}byte(){let e=h$1(this,R).getUint8(h$1(this,w$1));return U$1(this,w$1)._++,e}int32(){let e=h$1(this,R).getInt32(h$1(this,w$1),h$1(this,ne$1));return x$3(this,w$1,h$1(this,w$1)+4),e}string(e){return h$1(this,me$1).decode(this.bytes(e))}cstring(){let e=h$1(this,w$1),M=e;for(;h$1(this,R).getUint8(M++)!==0;);let tr=this.string(M-e-1);return x$3(this,w$1,M),tr}bytes(e){let M=h$1(this,R).buffer.slice(h$1(this,w$1),h$1(this,w$1)+e);return x$3(this,w$1,h$1(this,w$1)+e),new Uint8Array(M)}};R=new WeakMap,w$1=new WeakMap,fe$1=new WeakMap,me$1=new WeakMap,ne$1=new WeakMap;var Oe=1,_n=4,Ze=Oe+_n,et=new ArrayBuffer(0),A,S,D,o$1,l$1,tt,nt$1,rt,st$1,it$1,at,ot,ke$1,ut,lt$1,ct,pt$1,dt,ft,mt,yt,Ve$1,ye$1=class{constructor(){R$1(this,l$1),R$1(this,A,new DataView(et)),R$1(this,S,0),R$1(this,D,0),R$1(this,o$1,new de$1)}parse(e,M){T$2(this,l$1,tt).call(this,ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e);let tr=h$1(this,D)+h$1(this,S),rr=h$1(this,D);for(;rr+Ze<=tr;){let ir=h$1(this,A).getUint8(rr),lr=h$1(this,A).getUint32(rr+Oe,!1),dr=Oe+lr;if(dr+rr<=tr&&lr>0){let hr=T$2(this,l$1,nt$1).call(this,rr+Ze,ir,lr,h$1(this,A).buffer);M(hr),rr+=dr}else break}rr===tr?(x$3(this,A,new DataView(et)),x$3(this,S,0),x$3(this,D,0)):(x$3(this,S,tr-rr),x$3(this,D,rr))}};A=new WeakMap,S=new WeakMap,D=new WeakMap,o$1=new WeakMap,l$1=new WeakSet,tt=function(r){if(h$1(this,S)>0){let e=h$1(this,S)+r.byteLength;if(e+h$1(this,D)>h$1(this,A).byteLength){let M;if(e<=h$1(this,A).byteLength&&h$1(this,D)>=h$1(this,S))M=h$1(this,A).buffer;else{let tr=h$1(this,A).byteLength*2;for(;e>=tr;)tr*=2;M=new ArrayBuffer(tr)}new Uint8Array(M).set(new Uint8Array(h$1(this,A).buffer,h$1(this,D),h$1(this,S))),x$3(this,A,new DataView(M)),x$3(this,D,0)}new Uint8Array(h$1(this,A).buffer).set(new Uint8Array(r),h$1(this,D)+h$1(this,S)),x$3(this,S,e)}else x$3(this,A,new DataView(r)),x$3(this,D,0),x$3(this,S,r.byteLength)},nt$1=function(r,e,M,tr){switch(e){case 50:return Ie;case 49:return Be$1;case 51:return Me;case 110:return Re;case 115:return Te;case 99:return Pe;case 87:return Ee;case 73:return Ce;case 68:return T$2(this,l$1,dt).call(this,r,M,tr);case 67:return T$2(this,l$1,st$1).call(this,r,M,tr);case 90:return T$2(this,l$1,rt).call(this,r,M,tr);case 65:return T$2(this,l$1,ut).call(this,r,M,tr);case 82:return T$2(this,l$1,yt).call(this,r,M,tr);case 83:return T$2(this,l$1,ft).call(this,r,M,tr);case 75:return T$2(this,l$1,mt).call(this,r,M,tr);case 69:return T$2(this,l$1,Ve$1).call(this,r,M,tr,"error");case 78:return T$2(this,l$1,Ve$1).call(this,r,M,tr,"notice");case 84:return T$2(this,l$1,lt$1).call(this,r,M,tr);case 116:return T$2(this,l$1,pt$1).call(this,r,M,tr);case 71:return T$2(this,l$1,at).call(this,r,M,tr);case 72:return T$2(this,l$1,ot).call(this,r,M,tr);case 100:return T$2(this,l$1,it$1).call(this,r,M,tr);default:return new C$2("received invalid response: "+e.toString(16),M,"error")}},rt=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).string(1);return new X(e,tr)},st$1=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).cstring();return new Z$1(e,tr)},it$1=function(r,e,M){let tr=M.slice(r,r+(e-4));return new _(e,new Uint8Array(tr))},at=function(r,e,M){return T$2(this,l$1,ke$1).call(this,r,e,M,"copyInResponse")},ot=function(r,e,M){return T$2(this,l$1,ke$1).call(this,r,e,M,"copyOutResponse")},ke$1=function(r,e,M,tr){h$1(this,o$1).setBuffer(r,M);let rr=h$1(this,o$1).byte()!==0,ir=h$1(this,o$1).int16(),lr=new z(e,tr,rr,ir);for(let dr=0;dr<ir;dr++)lr.columnTypes[dr]=h$1(this,o$1).int16();return lr},ut=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).int32(),rr=h$1(this,o$1).cstring(),ir=h$1(this,o$1).cstring();return new J$1(e,tr,rr,ir)},lt$1=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).int16(),rr=new q$1(e,tr);for(let ir=0;ir<tr;ir++)rr.fields[ir]=T$2(this,l$1,ct).call(this);return rr},ct=function(){let r=h$1(this,o$1).cstring(),e=h$1(this,o$1).int32(),M=h$1(this,o$1).int16(),tr=h$1(this,o$1).int32(),rr=h$1(this,o$1).int16(),ir=h$1(this,o$1).int32(),lr=h$1(this,o$1).int16()===0?Le$1.text:Le$1.binary;return new H$1(r,e,M,tr,rr,ir,lr)},pt$1=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).int16(),rr=new Y$1(e,tr);for(let ir=0;ir<tr;ir++)rr.dataTypeIDs[ir]=h$1(this,o$1).int32();return rr},dt=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).int16(),rr=new Array(tr);for(let ir=0;ir<tr;ir++){let lr=h$1(this,o$1).int32();rr[ir]=lr===-1?null:h$1(this,o$1).string(lr)}return new ee(e,rr)},ft=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).cstring(),rr=h$1(this,o$1).cstring();return new $$1(e,tr,rr)},mt=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).int32(),rr=h$1(this,o$1).int32();return new K$1(e,tr,rr)},yt=function(r,e,M){h$1(this,o$1).setBuffer(r,M);let tr=h$1(this,o$1).int32();switch(tr){case 0:return new F(e);case 3:return new v(e);case 5:return new G$1(e,h$1(this,o$1).bytes(4));case 10:{let rr=[];for(;;){let ir=h$1(this,o$1).cstring();if(ir.length===0)return new j(e,rr);rr.push(ir)}}case 11:return new Q$1(e,h$1(this,o$1).string(e-8));case 12:return new W(e,h$1(this,o$1).string(e-8));default:throw new Error("Unknown authenticationOk message type "+tr)}},Ve$1=function(r,e,M,tr){h$1(this,o$1).setBuffer(r,M);let rr={},ir=h$1(this,o$1).string(1);for(;ir!=="\0";)rr[ir]=h$1(this,o$1).cstring(),ir=h$1(this,o$1).string(1);let lr=rr.M,dr=tr==="notice"?new te$1(e,lr):new C$2(lr,e,tr);return dr.severity=rr.S,dr.code=rr.C,dr.detail=rr.D,dr.hint=rr.H,dr.position=rr.P,dr.internalPosition=rr.p,dr.internalQuery=rr.q,dr.where=rr.W,dr.schema=rr.s,dr.table=rr.t,dr.column=rr.c,dr.dataType=rr.d,dr.constraint=rr.n,dr.file=rr.F,dr.line=rr.L,dr.routine=rr.R,dr};u();var Fe$1=typeof process$1=="object"&&typeof process$1.versions=="object"&&typeof process$1.versions.node=="string",se$1;async function Rr(){if(Fe$1||se$1)return;let r=new URL("/assets/pglite-CeYkvzd0.wasm",import.meta.url);se$1=fetch(r)}var re$1;async function Tr(r,e){if(e||re$1)return{instance:await WebAssembly.instantiate(e||re$1,r),module:e||re$1};let M=new URL("/assets/pglite-CeYkvzd0.wasm",import.meta.url);if(Fe$1){let tr=await(await __vitePreload(async()=>{const{readFile:lr}=await Promise.resolve().then(()=>__viteBrowserExternal$1);return{readFile:lr}},void 0)).readFile(M),{module:rr,instance:ir}=await WebAssembly.instantiate(tr,r);return re$1=rr,{instance:ir,module:rr}}else{se$1||(se$1=fetch(M));let tr=await se$1,{module:rr,instance:ir}=await WebAssembly.instantiateStreaming(tr,r);return re$1=rr,{instance:ir,module:rr}}}async function Er(){let r=new URL("/assets/pglite-COscPi1Y.data",import.meta.url);return Fe$1?(await(await __vitePreload(async()=>{const{readFile:e}=await Promise.resolve().then(()=>__viteBrowserExternal$1);return{readFile:e}},void 0)).readFile(r)).buffer:(await fetch(r)).arrayBuffer()}var Cr=()=>{if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let r=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(r);else for(let M=0;M<r.length;M++)r[M]=Math.floor(Math.random()*256);r[6]=r[6]&15|64,r[8]=r[8]&63|128;let e=[];return r.forEach(M=>{e.push(M.toString(16).padStart(2,"0"))}),e.slice(0,4).join("")+"-"+e.slice(4,6).join("")+"-"+e.slice(6,8).join("")+"-"+e.slice(8,10).join("")+"-"+e.slice(10).join("")};async function Pr(r,e,M,tr){if(!M||M.length===0)return e;tr=tr??r;let rr=[];try{await r.execProtocol(k$1.parse({text:e}),{syncToFs:!1}),rr.push(...(await r.execProtocol(k$1.describe({type:"S"}),{syncToFs:!1})).messages)}finally{rr.push(...(await r.execProtocol(k$1.sync(),{syncToFs:!1})).messages)}let ir=De(rr),lr=e.replace(/\$([0-9]+)/g,(dr,hr)=>"%"+hr+"L");return(await tr.query(`SELECT format($1, ${M.map((dr,hr)=>`$${hr+2}`).join(", ")}) as query`,[lr,...M],{paramTypes:[V,...ir]})).rows[0].query}function Ur(r){let e,M=!1,tr=async()=>{if(!e){M=!1;return}M=!0;let{args:rr,resolve:ir,reject:lr}=e;e=void 0;try{let dr=await r(...rr);ir(dr)}catch(dr){lr(dr)}finally{tr()}};return async(...rr)=>{e&&e.resolve(void 0);let ir=new Promise((lr,dr)=>{e={args:rr,resolve:lr,reject:dr}});return M||tr(),ir}}function Nr(r){let e;return r.startsWith('"')&&r.endsWith('"')?e=r.substring(1,r.length-1):e=r.toLowerCase(),e}u();var o={part:"part",container:"container"};function s$1(r,e,...M){let tr=r.length-1,rr=M.length-1;if(rr!==-1){if(rr===0){r[tr]=r[tr]+M[0]+e;return}r[tr]=r[tr]+M[0],r.push(...M.slice(1,rr)),r.push(M[rr]+e)}}function y$1(r,...e){let M=[r[0]];M.raw=[r.raw[0]];let tr=[];for(let rr=0;rr<e.length;rr++){let ir=e[rr],lr=rr+1;if(ir?._templateType===o.part){s$1(M,r[lr],ir.str),s$1(M.raw,r.raw[lr],ir.str);continue}if(ir?._templateType===o.container){s$1(M,r[lr],...ir.strings),s$1(M.raw,r.raw[lr],...ir.strings.raw),tr.push(...ir.values);continue}M.push(r[lr]),M.raw.push(r.raw[lr]),tr.push(ir)}return{_templateType:"container",strings:M,values:tr}}function g$1(r,...e){let{strings:M,values:tr}=y$1(r,...e);return{query:[M[0],...tr.flatMap((rr,ir)=>[`$${ir+1}`,M[ir+1]])].join(""),params:tr}}u();u();function E(r){let e=r.e;return e.query=r.query,e.params=r.params,e.queryOptions=r.options,e}var T,p,t,y,x$1,h,O$1,k=class{constructor(){R$1(this,t),this.serializers={...cn},this.parsers={...ln},R$1(this,T,!1),R$1(this,p,!1)}async _initArrayTypes({force:r=!1}={}){if(h$1(this,T)&&!r)return;x$3(this,T,!0);let e=await this.query(`
3
+ SELECT b.oid, b.typarray
4
+ FROM pg_catalog.pg_type a
5
+ LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem
6
+ WHERE a.typcategory = 'A'
7
+ GROUP BY b.oid, b.typarray
8
+ ORDER BY b.oid
9
+ `);for(let M of e.rows)this.serializers[M.typarray]=tr=>Ke$1(tr,this.serializers[M.oid],M.typarray),this.parsers[M.typarray]=tr=>yn(tr,this.parsers[M.oid],M.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(r,e,M){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await T$2(this,t,x$1).call(this,r,e,M))}async sql(r,...e){let{query:M,params:tr}=g$1(r,...e);return await this.query(M,tr)}async exec(r,e){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await T$2(this,t,h).call(this,r,e))}async describeQuery(r,e){let M=[];try{await T$2(this,t,y).call(this,k$1.parse({text:r,types:e?.paramTypes}),e),M=await T$2(this,t,y).call(this,k$1.describe({type:"S"}),e)}catch(dr){throw dr instanceof C$2?E({e:dr,options:e,params:void 0,query:r}):dr}finally{M.push(...await T$2(this,t,y).call(this,k$1.sync(),e))}let tr=M.find(dr=>dr.name==="parameterDescription"),rr=M.find(dr=>dr.name==="rowDescription"),ir=tr?.dataTypeIDs.map(dr=>({dataTypeID:dr,serializer:this.serializers[dr]}))??[],lr=rr?.fields.map(dr=>({name:dr.name,dataTypeID:dr.dataTypeID,parser:this.parsers[dr.dataTypeID]}))??[];return{queryParams:ir,resultFields:lr}}async transaction(r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>{await T$2(this,t,h).call(this,"BEGIN"),x$3(this,p,!0);let e=!1,M=()=>{if(e)throw new Error("Transaction is closed")},tr={query:async(rr,ir,lr)=>(M(),await T$2(this,t,x$1).call(this,rr,ir,lr)),sql:async(rr,...ir)=>{let{query:lr,params:dr}=g$1(rr,...ir);return await T$2(this,t,x$1).call(this,lr,dr)},exec:async(rr,ir)=>(M(),await T$2(this,t,h).call(this,rr,ir)),rollback:async()=>{M(),await T$2(this,t,h).call(this,"ROLLBACK"),e=!0},listen:async(rr,ir)=>(M(),await this.listen(rr,ir,tr)),get closed(){return e}};try{let rr=await r(tr);return e||(e=!0,await T$2(this,t,h).call(this,"COMMIT")),x$3(this,p,!1),rr}catch(rr){throw e||await T$2(this,t,h).call(this,"ROLLBACK"),x$3(this,p,!1),rr}})}async runExclusive(r){return await this._runExclusiveQuery(r)}};T=new WeakMap,p=new WeakMap,t=new WeakSet,y=async function(r,e={}){return await this.execProtocolStream(r,{...e,syncToFs:!1})},x$1=async function(r,e=[],M){return await this._runExclusiveQuery(async()=>{T$2(this,t,O$1).call(this,"runQuery",r,e,M),await this._handleBlob(M?.blob);let tr=[];try{let ir=await T$2(this,t,y).call(this,k$1.parse({text:r,types:M?.paramTypes}),M),lr=De(await T$2(this,t,y).call(this,k$1.describe({type:"S"}),M)),dr=e.map((hr,fr)=>{let mr=lr[fr];if(hr==null)return null;let _r=M?.serializers?.[mr]??this.serializers[mr];return _r?_r(hr):hr.toString()});tr=[...ir,...await T$2(this,t,y).call(this,k$1.bind({values:dr}),M),...await T$2(this,t,y).call(this,k$1.describe({type:"P"}),M),...await T$2(this,t,y).call(this,k$1.execute({}),M)]}catch(ir){throw ir instanceof C$2?E({e:ir,options:M,params:e,query:r}):ir}finally{tr.push(...await T$2(this,t,y).call(this,k$1.sync(),M))}await this._cleanupBlob(),h$1(this,p)||await this.syncToFs();let rr=await this._getWrittenBlob();return bn(tr,this.parsers,M,rr)[0]})},h=async function(r,e){return await this._runExclusiveQuery(async()=>{T$2(this,t,O$1).call(this,"runExec",r,e),await this._handleBlob(e?.blob);let M=[];try{M=await T$2(this,t,y).call(this,k$1.query(r),e)}catch(rr){throw rr instanceof C$2?E({e:rr,options:e,params:void 0,query:r}):rr}finally{M.push(...await T$2(this,t,y).call(this,k$1.sync(),e))}this._cleanupBlob(),h$1(this,p)||await this.syncToFs();let tr=await this._getWrittenBlob();return bn(M,this.parsers,e,tr)})},O$1=function(...r){this.debug>0&&console.log(...r)};var w=D$1((r,e)=>{u();var M=9007199254740991,tr=(function(vr){return vr})();function rr(vr){return vr===tr}function ir(vr){return typeof vr=="string"||Object.prototype.toString.call(vr)=="[object String]"}function lr(vr){return Object.prototype.toString.call(vr)=="[object Date]"}function dr(vr){return vr!==null&&typeof vr=="object"}function hr(vr){return typeof vr=="function"}function fr(vr){return typeof vr=="number"&&vr>-1&&vr%1==0&&vr<=M}function mr(vr){return Object.prototype.toString.call(vr)=="[object Array]"}function _r(vr){return dr(vr)&&!hr(vr)&&fr(vr.length)}function gr(vr){return Object.prototype.toString.call(vr)=="[object ArrayBuffer]"}function wr(vr,Sr){return Array.prototype.map.call(vr,Sr)}function yr(vr,Sr){var xr=tr;return hr(Sr)&&Array.prototype.every.call(vr,function(Ar,Dr,Ir){var kr=Sr(Ar,Dr,Ir);return kr&&(xr=Ar),!kr}),xr}function br(vr){return Object.assign.apply(null,arguments)}function Mr(vr){var Sr,xr,Ar;if(ir(vr)){for(xr=vr.length,Ar=new Uint8Array(xr),Sr=0;Sr<xr;Sr++)Ar[Sr]=vr.charCodeAt(Sr)&255;return Ar}return gr(vr)?new Uint8Array(vr):dr(vr)&&gr(vr.buffer)?new Uint8Array(vr.buffer):_r(vr)?new Uint8Array(vr):dr(vr)&&hr(vr.toString)?Mr(vr.toString()):new Uint8Array}e.exports.MAX_SAFE_INTEGER=M,e.exports.isUndefined=rr,e.exports.isString=ir,e.exports.isObject=dr,e.exports.isDateTime=lr,e.exports.isFunction=hr,e.exports.isArray=mr,e.exports.isArrayLike=_r,e.exports.isArrayBuffer=gr,e.exports.map=wr,e.exports.find=yr,e.exports.extend=br,e.exports.toUint8Array=Mr}),x=D$1((r,e)=>{u();var M="\0";e.exports={NULL_CHAR:M,TMAGIC:"ustar"+M+"00",OLDGNU_MAGIC:"ustar "+M,REGTYPE:0,LNKTYPE:1,SYMTYPE:2,CHRTYPE:3,BLKTYPE:4,DIRTYPE:5,FIFOTYPE:6,CONTTYPE:7,TSUID:parseInt("4000",8),TSGID:parseInt("2000",8),TSVTX:parseInt("1000",8),TUREAD:parseInt("0400",8),TUWRITE:parseInt("0200",8),TUEXEC:parseInt("0100",8),TGREAD:parseInt("0040",8),TGWRITE:parseInt("0020",8),TGEXEC:parseInt("0010",8),TOREAD:parseInt("0004",8),TOWRITE:parseInt("0002",8),TOEXEC:parseInt("0001",8),TPERMALL:parseInt("0777",8),TPERMMASK:parseInt("0777",8)}}),L$1=D$1((r,e)=>{u();var M=w(),tr=x(),rr=512,ir=tr.TPERMALL,lr=0,dr=0,hr=[["name",100,0,function(Sr,xr){return _r(Sr[xr[0]],xr[1])},function(Sr,xr,Ar){return yr(Sr.slice(xr,xr+Ar[1]))}],["mode",8,100,function(Sr,xr){var Ar=Sr[xr[0]]||ir;return Ar=Ar&tr.TPERMMASK,gr(Ar,xr[1],ir)},function(Sr,xr,Ar){var Dr=br(Sr.slice(xr,xr+Ar[1]));return Dr&=tr.TPERMMASK,Dr}],["uid",8,108,function(Sr,xr){return gr(Sr[xr[0]],xr[1],lr)},function(Sr,xr,Ar){return br(Sr.slice(xr,xr+Ar[1]))}],["gid",8,116,function(Sr,xr){return gr(Sr[xr[0]],xr[1],dr)},function(Sr,xr,Ar){return br(Sr.slice(xr,xr+Ar[1]))}],["size",12,124,function(Sr,xr){return gr(Sr.data.length,xr[1])},function(Sr,xr,Ar){return br(Sr.slice(xr,xr+Ar[1]))}],["modifyTime",12,136,function(Sr,xr){return wr(Sr[xr[0]],xr[1])},function(Sr,xr,Ar){return Mr(Sr.slice(xr,xr+Ar[1]))}],["checksum",8,148,function(Sr,xr){return" "},function(Sr,xr,Ar){return br(Sr.slice(xr,xr+Ar[1]))}],["type",1,156,function(Sr,xr){return""+(parseInt(Sr[xr[0]],10)||0)%8},function(Sr,xr,Ar){return(parseInt(String.fromCharCode(Sr[xr]),10)||0)%8}],["linkName",100,157,function(Sr,xr){return""},function(Sr,xr,Ar){return yr(Sr.slice(xr,xr+Ar[1]))}],["ustar",8,257,function(Sr,xr){return tr.TMAGIC},function(Sr,xr,Ar){return mr(yr(Sr.slice(xr,xr+Ar[1]),!0))},function(Sr,xr){return Sr[xr[0]]==tr.TMAGIC||Sr[xr[0]]==tr.OLDGNU_MAGIC}],["owner",32,265,function(Sr,xr){return _r(Sr[xr[0]],xr[1])},function(Sr,xr,Ar){return yr(Sr.slice(xr,xr+Ar[1]))}],["group",32,297,function(Sr,xr){return _r(Sr[xr[0]],xr[1])},function(Sr,xr,Ar){return yr(Sr.slice(xr,xr+Ar[1]))}],["majorNumber",8,329,function(Sr,xr){return""},function(Sr,xr,Ar){return br(Sr.slice(xr,xr+Ar[1]))}],["minorNumber",8,337,function(Sr,xr){return""},function(Sr,xr,Ar){return br(Sr.slice(xr,xr+Ar[1]))}],["prefix",131,345,function(Sr,xr){return _r(Sr[xr[0]],xr[1])},function(Sr,xr,Ar){return yr(Sr.slice(xr,xr+Ar[1]))}],["accessTime",12,476,function(Sr,xr){return wr(Sr[xr[0]],xr[1])},function(Sr,xr,Ar){return Mr(Sr.slice(xr,xr+Ar[1]))}],["createTime",12,488,function(Sr,xr){return wr(Sr[xr[0]],xr[1])},function(Sr,xr,Ar){return Mr(Sr.slice(xr,xr+Ar[1]))}]],fr=(function(Sr){var xr=Sr[Sr.length-1];return xr[2]+xr[1]})(hr);function mr(Sr){if(Sr.length==8){var xr=Sr.split("");if(xr[5]==tr.NULL_CHAR)return(xr[6]==" "||xr[6]==tr.NULL_CHAR)&&(xr[6]="0"),(xr[7]==" "||xr[7]==tr.NULL_CHAR)&&(xr[7]="0"),xr=xr.join(""),xr==tr.TMAGIC?xr:Sr;if(xr[7]==tr.NULL_CHAR)return xr[5]==tr.NULL_CHAR&&(xr[5]=" "),xr[6]==tr.NULL_CHAR&&(xr[6]=" "),xr==tr.OLDGNU_MAGIC?xr:Sr}return Sr}function _r(Sr,xr){return xr-=1,M.isUndefined(Sr)&&(Sr=""),Sr=(""+Sr).substr(0,xr),Sr+tr.NULL_CHAR}function gr(Sr,xr,Ar){for(Ar=parseInt(Ar)||0,xr-=1,Sr=(parseInt(Sr)||Ar).toString(8).substr(-xr,xr);Sr.length<xr;)Sr="0"+Sr;return Sr+tr.NULL_CHAR}function wr(Sr,xr){if(M.isDateTime(Sr))Sr=Math.floor(1*Sr/1e3);else if(Sr=parseInt(Sr,10),isFinite(Sr)){if(Sr<=0)return""}else Sr=Math.floor(1*new Date/1e3);return gr(Sr,xr,0)}function yr(Sr,xr){var Ar=String.fromCharCode.apply(null,Sr);if(xr)return Ar;var Dr=Ar.indexOf(tr.NULL_CHAR);return Dr>=0?Ar.substr(0,Dr):Ar}function br(Sr){var xr=String.fromCharCode.apply(null,Sr);return parseInt(xr.replace(/^0+$/g,""),8)||0}function Mr(Sr){return Sr.length==0||Sr[0]==0?null:new Date(1e3*br(Sr))}function vr(Sr,xr,Ar){var Dr=parseInt(xr,10)||0,Ir=Math.min(Dr+fr,Sr.length),kr=0,Or=0,Fr=0;Ar&&hr.every(function(Lr){return Lr[0]=="checksum"?(Or=Dr+Lr[2],Fr=Or+Lr[1],!1):!0});for(var Jr=32,$n=Dr;$n<Ir;$n++){var Gr=$n>=Or&&$n<Fr?Jr:Sr[$n];kr=(kr+Gr)%262144}return kr}e.exports.recordSize=rr,e.exports.defaultFileMode=ir,e.exports.defaultUid=lr,e.exports.defaultGid=dr,e.exports.posixHeader=hr,e.exports.effectiveHeaderSize=fr,e.exports.calculateChecksum=vr,e.exports.formatTarString=_r,e.exports.formatTarNumber=gr,e.exports.formatTarDateTime=wr,e.exports.parseTarString=yr,e.exports.parseTarNumber=br,e.exports.parseTarDateTime=Mr}),er=D$1((r,e)=>{u();var M=x(),tr=w(),rr=L$1();function ir(_r){return rr.recordSize}function lr(_r){return Math.ceil(_r.data.length/rr.recordSize)*rr.recordSize}function dr(_r){var gr=0;return _r.forEach(function(wr){gr+=ir()+lr(wr)}),gr+=rr.recordSize*2,new Uint8Array(gr)}function hr(_r,gr,wr){wr=parseInt(wr)||0;var yr=wr;rr.posixHeader.forEach(function(xr){for(var Ar=xr[3](gr,xr),Dr=Ar.length,Ir=0;Ir<Dr;Ir+=1)_r[yr+Ir]=Ar.charCodeAt(Ir)&255;yr+=xr[1]});var br=tr.find(rr.posixHeader,function(xr){return xr[0]=="checksum"});if(br){var Mr=rr.calculateChecksum(_r,wr,!0),vr=rr.formatTarNumber(Mr,br[1]-2)+M.NULL_CHAR+" ";yr=wr+br[2];for(var Sr=0;Sr<vr.length;Sr+=1)_r[yr]=vr.charCodeAt(Sr)&255,yr++}return wr+ir()}function fr(_r,gr,wr){return wr=parseInt(wr,10)||0,_r.set(gr.data,wr),wr+lr(gr)}function mr(_r){_r=tr.map(_r,function(yr){return tr.extend({},yr,{data:tr.toUint8Array(yr.data)})});var gr=dr(_r),wr=0;return _r.forEach(function(yr){wr=hr(gr,yr,wr),wr=fr(gr,yr,wr)}),gr}e.exports.tar=mr}),nr=D$1((r,e)=>{u();var M=x(),tr=w(),rr=L$1(),ir={extractData:!0,checkHeader:!0,checkChecksum:!0,checkFileSize:!0},lr={size:!0,checksum:!0,ustar:!0},dr={unexpectedEndOfFile:"Unexpected end of file.",fileCorrupted:"File is corrupted.",checksumCheckFailed:"Checksum check failed."};function hr(br){return rr.recordSize}function fr(br){return Math.ceil(br/rr.recordSize)*rr.recordSize}function mr(br,Mr){for(var vr=Mr,Sr=Math.min(br.length,Mr+rr.recordSize*2),xr=vr;xr<Sr;xr++)if(br[xr]!=0)return!1;return!0}function _r(br,Mr,vr){if(br.length-Mr<rr.recordSize){if(vr.checkFileSize)throw new Error(dr.unexpectedEndOfFile);return null}Mr=parseInt(Mr)||0;var Sr={},xr=Mr;if(rr.posixHeader.forEach(function(Ir){Sr[Ir[0]]=Ir[4](br,xr,Ir),xr+=Ir[1]}),Sr.type!=0&&(Sr.size=0),vr.checkHeader&&rr.posixHeader.forEach(function(Ir){if(tr.isFunction(Ir[5])&&!Ir[5](Sr,Ir)){var kr=new Error(dr.fileCorrupted);throw kr.data={offset:Mr+Ir[2],field:Ir[0]},kr}}),vr.checkChecksum){var Ar=rr.calculateChecksum(br,Mr,!0);if(Ar!=Sr.checksum){var Dr=new Error(dr.checksumCheckFailed);throw Dr.data={offset:Mr,header:Sr,checksum:Ar},Dr}}return Sr}function gr(br,Mr,vr,Sr){return Sr.extractData?vr.size<=0?new Uint8Array:br.slice(Mr,Mr+vr.size):null}function wr(br,Mr){var vr={};return rr.posixHeader.forEach(function(Sr){var xr=Sr[0];lr[xr]||(vr[xr]=br[xr])}),vr.isOldGNUFormat=br.ustar==M.OLDGNU_MAGIC,Mr&&(vr.data=Mr),vr}function yr(br,Mr){Mr=tr.extend({},ir,Mr);for(var vr=[],Sr=0,xr=br.length;xr-Sr>=rr.recordSize;){br=tr.toUint8Array(br);var Ar=_r(br,Sr,Mr);if(!Ar)break;Sr+=hr();var Dr=gr(br,Sr,Ar,Mr);if(vr.push(wr(Ar,Dr)),Sr+=fr(Ar.size),mr(br,Sr))break}return vr}e.exports.untar=yr}),or$2=D$1((r,e)=>{u();var M=w(),tr=x(),rr=er(),ir=nr();M.extend(e.exports,rr,ir,tr)});u();u();var g=L$3(or$2());async function H(r,e,M="pgdata",tr="auto"){let rr=Br(r,e),[ir,lr]=await qr(rr,tr),dr=M+(lr?".tar.gz":".tar"),hr=lr?"application/x-gzip":"application/x-tar";return typeof File<"u"?new File([ir],dr,{type:hr}):new Blob([ir],{type:hr})}var Hr=["application/x-gtar","application/x-tar+gzip","application/x-gzip","application/gzip"];async function ce$1(r,e,M){let tr=new Uint8Array(await e.arrayBuffer()),rr=typeof File<"u"&&e instanceof File?e.name:void 0;(Hr.includes(e.type)||rr?.endsWith(".tgz")||rr?.endsWith(".tar.gz"))&&(tr=await ar(tr));let ir;try{ir=(0,g.untar)(tr)}catch(lr){if(lr instanceof Error&&lr.message.includes("File is corrupted"))tr=await ar(tr),ir=(0,g.untar)(tr);else throw lr}for(let lr of ir){let dr=M+lr.name,hr=dr.split("/").slice(0,-1);for(let fr=1;fr<=hr.length;fr++){let mr=hr.slice(0,fr).join("/");r.analyzePath(mr).exists||r.mkdir(mr)}lr.type===g.REGTYPE?(r.writeFile(dr,lr.data),r.utime(dr,sr(lr.modifyTime),sr(lr.modifyTime))):lr.type===g.DIRTYPE&&r.mkdir(dr)}}function jr(r,e){let M=[],tr=rr=>{r.readdir(rr).forEach(ir=>{if(ir==="."||ir==="..")return;let lr=rr+"/"+ir,dr=r.stat(lr),hr=r.isFile(dr.mode)?r.readFile(lr,{encoding:"binary"}):new Uint8Array(0);M.push({name:lr.substring(e.length),mode:dr.mode,size:dr.size,type:r.isFile(dr.mode)?g.REGTYPE:g.DIRTYPE,modifyTime:dr.mtime,data:hr}),r.isDir(dr.mode)&&tr(lr)})};return tr(e),M}function Br(r,e){let M=jr(r,e);return(0,g.tar)(M)}async function qr(r,e="auto"){if(e==="none")return[r,!1];if(typeof CompressionStream<"u")return[await Yr(r),!0];if(typeof process$1<"u"&&process$1.versions&&process$1.versions.node)return[await Wr(r),!0];if(e==="auto")return[r,!1];throw new Error("Compression not supported in this environment")}async function Yr(r){let e=new CompressionStream("gzip"),M=e.writable.getWriter(),tr=e.readable.getReader();M.write(r),M.close();let rr=[];for(;;){let{value:dr,done:hr}=await tr.read();if(hr)break;dr&&rr.push(dr)}let ir=new Uint8Array(rr.reduce((dr,hr)=>dr+hr.length,0)),lr=0;return rr.forEach(dr=>{ir.set(dr,lr),lr+=dr.length}),ir}async function Wr(r){let{promisify:e}=await __vitePreload(()=>Promise.resolve().then(()=>__viteBrowserExternal$1),void 0),{gzip:M}=await __vitePreload(async()=>{const{gzip:tr}=await Promise.resolve().then(()=>__viteBrowserExternal$1);return{gzip:tr}},void 0);return await e(M)(r)}async function ar(r){if(typeof CompressionStream<"u")return await Xr(r);if(typeof process$1<"u"&&process$1.versions&&process$1.versions.node)return await Kr(r);throw new Error("Unsupported environment for decompression")}async function Xr(r){let e=new DecompressionStream("gzip"),M=e.writable.getWriter(),tr=e.readable.getReader();M.write(r),M.close();let rr=[];for(;;){let{value:dr,done:hr}=await tr.read();if(hr)break;dr&&rr.push(dr)}let ir=new Uint8Array(rr.reduce((dr,hr)=>dr+hr.length,0)),lr=0;return rr.forEach(dr=>{ir.set(dr,lr),lr+=dr.length}),ir}async function Kr(r){let{promisify:e}=await __vitePreload(()=>Promise.resolve().then(()=>__viteBrowserExternal$1),void 0),{gunzip:M}=await __vitePreload(async()=>{const{gunzip:tr}=await Promise.resolve().then(()=>__viteBrowserExternal$1);return{gunzip:tr}},void 0);return await e(M)(r)}function sr(r){return r?typeof r=="number"?r:Math.floor(r.getTime()/1e3):Math.floor(Date.now()/1e3)}var Vr="/tmp/pglite",C$1=Vr+"/base",ur=class{constructor(r){this.dataDir=r}async init(r,e){return this.pg=r,{emscriptenOpts:e}}async syncToFs(r){}async initialSyncFs(){}async closeFs(){}async dumpTar(r,e){return H(this.pg.Module.FS,C$1,r,e)}},cr=class{constructor(r,{debug:e=!1}={}){this.dataDir=r,this.debug=e}async syncToFs(r){}async initialSyncFs(){}async closeFs(){}async dumpTar(r,e){return H(this.pg.Module.FS,C$1,r,e)}async init(r,e){return this.pg=r,{emscriptenOpts:{...e,preRun:[...e.preRun||[],M=>{let tr=Zr(M,this);M.FS.mkdir(C$1),M.FS.mount(tr,{},C$1)}]}}}},pr={EBADF:8,EBADFD:127,EEXIST:20,EINVAL:28,EISDIR:31,ENODEV:43,ENOENT:44,ENOTDIR:54,ENOTEMPTY:55},Zr=(r,e)=>{let M=r.FS,tr=e.debug?console.log:null,rr={tryFSOperation(ir){try{return ir()}catch(lr){throw lr.code?lr.code==="UNKNOWN"?new M.ErrnoError(pr.EINVAL):new M.ErrnoError(lr.code):lr}},mount(ir){return rr.createNode(null,"/",16895,0)},syncfs(ir,lr,dr){},createNode(ir,lr,dr,hr){if(!M.isDir(dr)&&!M.isFile(dr))throw new M.ErrnoError(28);let fr=M.createNode(ir,lr,dr);return fr.node_ops=rr.node_ops,fr.stream_ops=rr.stream_ops,fr},getMode:function(ir){return tr?.("getMode",ir),rr.tryFSOperation(()=>e.lstat(ir).mode)},realPath:function(ir){let lr=[];for(;ir.parent!==ir;)lr.push(ir.name),ir=ir.parent;return lr.push(ir.mount.opts.root),lr.reverse(),lr.join("/")},node_ops:{getattr(ir){tr?.("getattr",rr.realPath(ir));let lr=rr.realPath(ir);return rr.tryFSOperation(()=>{let dr=e.lstat(lr);return{...dr,dev:0,ino:ir.id,nlink:1,rdev:ir.rdev,atime:new Date(dr.atime),mtime:new Date(dr.mtime),ctime:new Date(dr.ctime)}})},setattr(ir,lr){tr?.("setattr",rr.realPath(ir),lr);let dr=rr.realPath(ir);rr.tryFSOperation(()=>{lr.mode!==void 0&&e.chmod(dr,lr.mode),lr.size!==void 0&&e.truncate(dr,lr.size),lr.timestamp!==void 0&&e.utimes(dr,lr.timestamp,lr.timestamp),lr.size!==void 0&&e.truncate(dr,lr.size)})},lookup(ir,lr){tr?.("lookup",rr.realPath(ir),lr);let dr=[rr.realPath(ir),lr].join("/"),hr=rr.getMode(dr);return rr.createNode(ir,lr,hr)},mknod(ir,lr,dr,hr){tr?.("mknod",rr.realPath(ir),lr,dr,hr);let fr=rr.createNode(ir,lr,dr,hr),mr=rr.realPath(fr);return rr.tryFSOperation(()=>(M.isDir(fr.mode)?e.mkdir(mr,{mode:dr}):e.writeFile(mr,"",{mode:dr}),fr))},rename(ir,lr,dr){tr?.("rename",rr.realPath(ir),rr.realPath(lr),dr);let hr=rr.realPath(ir),fr=[rr.realPath(lr),dr].join("/");rr.tryFSOperation(()=>{e.rename(hr,fr)}),ir.name=dr},unlink(ir,lr){tr?.("unlink",rr.realPath(ir),lr);let dr=[rr.realPath(ir),lr].join("/");try{e.unlink(dr)}catch{}},rmdir(ir,lr){tr?.("rmdir",rr.realPath(ir),lr);let dr=[rr.realPath(ir),lr].join("/");return rr.tryFSOperation(()=>{e.rmdir(dr)})},readdir(ir){tr?.("readdir",rr.realPath(ir));let lr=rr.realPath(ir);return rr.tryFSOperation(()=>e.readdir(lr))},symlink(ir,lr,dr){throw tr?.("symlink",rr.realPath(ir),lr,dr),new M.ErrnoError(63)},readlink(ir){throw tr?.("readlink",rr.realPath(ir)),new M.ErrnoError(63)}},stream_ops:{open(ir){tr?.("open stream",rr.realPath(ir.node));let lr=rr.realPath(ir.node);return rr.tryFSOperation(()=>{M.isFile(ir.node.mode)&&(ir.shared.refcount=1,ir.nfd=e.open(lr))})},close(ir){return tr?.("close stream",rr.realPath(ir.node)),rr.tryFSOperation(()=>{M.isFile(ir.node.mode)&&ir.nfd&&--ir.shared.refcount===0&&e.close(ir.nfd)})},dup(ir){tr?.("dup stream",rr.realPath(ir.node)),ir.shared.refcount++},read(ir,lr,dr,hr,fr){return tr?.("read stream",rr.realPath(ir.node),dr,hr,fr),hr===0?0:rr.tryFSOperation(()=>e.read(ir.nfd,lr,dr,hr,fr))},write(ir,lr,dr,hr,fr){return tr?.("write stream",rr.realPath(ir.node),dr,hr,fr),rr.tryFSOperation(()=>e.write(ir.nfd,lr.buffer,dr,hr,fr))},llseek(ir,lr,dr){tr?.("llseek stream",rr.realPath(ir.node),lr,dr);let hr=lr;if(dr===1?hr+=ir.position:dr===2&&M.isFile(ir.node.mode)&&rr.tryFSOperation(()=>{let fr=e.fstat(ir.nfd);hr+=fr.size}),hr<0)throw new M.ErrnoError(28);return hr},mmap(ir,lr,dr,hr,fr){if(tr?.("mmap stream",rr.realPath(ir.node),lr,dr,hr,fr),!M.isFile(ir.node.mode))throw new M.ErrnoError(pr.ENODEV);let mr=r.mmapAlloc(lr);return rr.stream_ops.read(ir,r.HEAP8,mr,lr,dr),{ptr:mr,allocated:!0}},msync(ir,lr,dr,hr,fr){return tr?.("msync stream",rr.realPath(ir.node),dr,hr,fr),rr.stream_ops.write(ir,lr,0,hr,dr),0}}};return rr};u();u();u();var st=new Error("request for lock canceled"),nt=function(r,e,M,tr){function rr(ir){return ir instanceof M?ir:new M(function(lr){lr(ir)})}return new(M||(M=Promise))(function(ir,lr){function dr(mr){try{fr(tr.next(mr))}catch(_r){lr(_r)}}function hr(mr){try{fr(tr.throw(mr))}catch(_r){lr(_r)}}function fr(mr){mr.done?ir(mr.value):rr(mr.value).then(dr,hr)}fr((tr=tr.apply(r,[])).next())})},Fe=class{constructor(r,e=st){this._value=r,this._cancelError=e,this._weightedQueues=[],this._weightedWaiters=[]}acquire(r=1){if(r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise((e,M)=>{this._weightedQueues[r-1]||(this._weightedQueues[r-1]=[]),this._weightedQueues[r-1].push({resolve:e,reject:M}),this._dispatch()})}runExclusive(r,e=1){return nt(this,void 0,void 0,function*(){let[M,tr]=yield this.acquire(e);try{return yield r(M)}finally{tr()}})}waitForUnlock(r=1){if(r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise(e=>{this._weightedWaiters[r-1]||(this._weightedWaiters[r-1]=[]),this._weightedWaiters[r-1].push(e),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(r){this._value=r,this._dispatch()}release(r=1){if(r<=0)throw new Error(`invalid weight ${r}: must be positive`);this._value+=r,this._dispatch()}cancel(){this._weightedQueues.forEach(r=>r.forEach(e=>e.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var r;for(let e=this._value;e>0;e--){let M=(r=this._weightedQueues[e-1])===null||r===void 0?void 0:r.shift();if(!M)continue;let tr=this._value,rr=e;this._value-=e,e=this._value+1,M.resolve([tr,this._newReleaser(rr)])}this._drainUnlockWaiters()}_newReleaser(r){let e=!1;return()=>{e||(e=!0,this.release(r))}}_drainUnlockWaiters(){for(let r=this._value;r>0;r--)this._weightedWaiters[r-1]&&(this._weightedWaiters[r-1].forEach(e=>e()),this._weightedWaiters[r-1]=[])}},it=function(r,e,M,tr){function rr(ir){return ir instanceof M?ir:new M(function(lr){lr(ir)})}return new(M||(M=Promise))(function(ir,lr){function dr(mr){try{fr(tr.next(mr))}catch(_r){lr(_r)}}function hr(mr){try{fr(tr.throw(mr))}catch(_r){lr(_r)}}function fr(mr){mr.done?ir(mr.value):rr(mr.value).then(dr,hr)}fr((tr=tr.apply(r,[])).next())})},Y=class{constructor(r){this._semaphore=new Fe(1,r)}acquire(){return it(this,void 0,void 0,function*(){let[,r]=yield this._semaphore.acquire();return r})}runExclusive(r){return this._semaphore.runExclusive(()=>r())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};u();var Le=L$3(or$2());async function ke(r){if(Fe$1){let e=await __vitePreload(()=>Promise.resolve().then(()=>__viteBrowserExternal$1),void 0),M=await __vitePreload(()=>Promise.resolve().then(()=>__viteBrowserExternal$1),void 0),{Writable:tr}=await __vitePreload(async()=>{const{Writable:dr}=await Promise.resolve().then(()=>__viteBrowserExternal$1);return{Writable:dr}},void 0),{pipeline:rr}=await __vitePreload(async()=>{const{pipeline:dr}=await Promise.resolve().then(()=>__viteBrowserExternal$1);return{pipeline:dr}},void 0);if(!e.existsSync(r))throw new Error(`Extension bundle not found: ${r}`);let ir=M.createGunzip(),lr=[];return await rr(e.createReadStream(r),ir,new tr({write(dr,hr,fr){lr.push(dr),fr()}})),new Blob(lr)}else{let e=await fetch(r.toString());if(!e.ok||!e.body)return null;if(e.headers.get("Content-Encoding")==="gzip")return e.blob();{let M=new DecompressionStream("gzip");return new Response(e.body.pipeThrough(M)).blob()}}}async function Be(r,e){for(let M in r.pg_extensions){let tr;try{tr=await r.pg_extensions[M]}catch(rr){console.error("Failed to fetch extension:",M,rr);continue}if(tr){let rr=new Uint8Array(await tr.arrayBuffer());_t(r,M,rr,e)}else console.error("Could not get binary data for extension:",M)}}function _t(r,e,M,tr){Le.default.untar(M).forEach(rr=>{if(!rr.name.startsWith(".")){let ir=r.WASM_PREFIX+"/"+rr.name;if(rr.name.endsWith(".so")){let lr=(...hr)=>{tr("pgfs:ext OK",ir,hr)},dr=(...hr)=>{tr("pgfs:ext FAIL",ir,hr)};r.FS.createPreloadedFile(lt(ir),rr.name.split("/").pop().slice(0,-3),rr.data,!0,!0,lr,dr,!1)}else try{let lr=ir.substring(0,ir.lastIndexOf("/"));r.FS.analyzePath(lr).exists===!1&&r.FS.mkdirTree(lr),r.FS.writeFile(ir,rr.data)}catch(lr){console.error(`Error writing file ${ir}`,lr)}}})}function lt(r){let e=r.lastIndexOf("/");return e>0?r.slice(0,e):r}u();u();var ce=class extends ur{async init(r,e){return this.pg=r,{emscriptenOpts:{...e,preRun:[...e.preRun||[],M=>{let tr=M.FS.filesystems.IDBFS;M.FS.mkdir("/pglite"),M.FS.mkdir(`/pglite/${this.dataDir}`),M.FS.mount(tr,{},`/pglite/${this.dataDir}`),M.FS.symlink(`/pglite/${this.dataDir}`,C$1)}]}}}initialSyncFs(){return new Promise((r,e)=>{this.pg.Module.FS.syncfs(!0,M=>{M?e(M):r()})})}syncToFs(r){return new Promise((e,M)=>{this.pg.Module.FS.syncfs(!1,tr=>{tr?M(tr):e()})})}async closeFs(){let r=this.pg.Module.FS.filesystems.IDBFS.dbs[this.dataDir];r&&r.close(),this.pg.Module.FS.quit()}};u();var ge=class extends ur{async closeFs(){this.pg.Module.FS.quit()}};function Ge(r){let e;if(r?.startsWith("file://")){if(r=r.slice(7),!r)throw new Error("Invalid dataDir, must be a valid path");e="nodefs"}else r?.startsWith("idb://")?(r=r.slice(6),e="idbfs"):r?.startsWith("opfs-ahp://")?(r=r.slice(11),e="opfs-ahp"):!r||r?.startsWith("memory://")?e="memoryfs":e="nodefs";return{dataDir:r,fsType:e}}async function Ue(r,e){let M;if(r&&e==="nodefs"){let{NodeFS:tr}=await __vitePreload(()=>import("./nodefs-BDOJRpNU.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]));M=new tr(r)}else if(r&&e==="idbfs")M=new ce(r);else if(r&&e==="opfs-ahp"){let{OpfsAhpFS:tr}=await __vitePreload(()=>import("./opfs-ahp-gToYnU-E.js"),__vite__mapDeps([16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]));M=new tr(r)}else M=new ge;return M}u();u();var pt=(()=>{var _scriptName=import.meta.url;return async function(moduleArg={}){var moduleRtn,Module=moduleArg,readyPromiseResolve,readyPromiseReject,readyPromise=new Promise((r,e)=>{readyPromiseResolve=r,readyPromiseReject=e}),ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof process$1=="object"&&typeof process$1.versions=="object"&&typeof process$1.versions.node=="string"&&process$1.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:r}=await __vitePreload(()=>Promise.resolve().then(()=>__viteBrowserExternal$1),void 0),e=import.meta.url;e.startsWith("data:")&&(e="/");var require=r(e)}Module.expectedDataFileDownloads??(Module.expectedDataFileDownloads=0),Module.expectedDataFileDownloads++,(()=>{var r=typeof ENVIRONMENT_IS_PTHREAD<"u"&&ENVIRONMENT_IS_PTHREAD,e=typeof ENVIRONMENT_IS_WASM_WORKER<"u"&&ENVIRONMENT_IS_WASM_WORKER;if(r||e)return;var M=typeof process$1=="object"&&typeof process$1.versions=="object"&&typeof process$1.versions.node=="string";function tr(rr){typeof window=="object"?window.encodeURIComponent(window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/"))+"/"):typeof process$1>"u"&&typeof location<"u"&&encodeURIComponent(location.pathname.substring(0,location.pathname.lastIndexOf("/"))+"/");var ir="pglite.data",lr="pglite.data",dr=Module.locateFile?Module.locateFile(lr,""):lr,hr=rr.remote_package_size;function fr(yr,br,Mr,vr){if(M){require("fs").readFile(yr,(Sr,xr)=>{Sr?vr(Sr):Mr(xr.buffer)});return}Module.dataFileDownloads??(Module.dataFileDownloads={}),fetch(yr).catch(Sr=>Promise.reject(new Error(`Network Error: ${yr}`,{cause:Sr}))).then(Sr=>{if(!Sr.ok)return Promise.reject(new Error(`${Sr.status}: ${Sr.url}`));if(!Sr.body&&Sr.arrayBuffer)return Sr.arrayBuffer().then(Mr);let xr=Sr.body.getReader(),Ar=()=>xr.read().then(Fr).catch(Jr=>Promise.reject(new Error(`Unexpected error while handling : ${Sr.url} ${Jr}`,{cause:Jr}))),Dr=[],Ir=Sr.headers,kr=Number(Ir.get("Content-Length")??br),Or=0,Fr=({done:Jr,value:$n})=>{if(Jr){let Gr=new Uint8Array(Dr.map($r=>$r.length).reduce(($r,zr)=>$r+zr,0)),Lr=0;for(let $r of Dr)Gr.set($r,Lr),Lr+=$r.length;Mr(Gr.buffer)}else{Dr.push($n),Or+=$n.length,Module.dataFileDownloads[yr]={loaded:Or,total:kr};let Gr=0,Lr=0;for(let $r of Object.values(Module.dataFileDownloads))Gr+=$r.loaded,Lr+=$r.total;return Module.setStatus?.(`Downloading data... (${Gr}/${Lr})`),Ar()}};return Module.setStatus?.("Downloading data..."),Ar()})}function mr(yr){console.error("package error:",yr)}var _r=null,gr=Module.getPreloadedPackage?Module.getPreloadedPackage(dr,hr):null;gr||fr(dr,hr,yr=>{_r?(_r(yr),_r=null):gr=yr},mr);function wr(yr){function br(Ar,Dr){if(!Ar)throw Dr+new Error().stack}yr.FS_createPath("/","home",!0,!0),yr.FS_createPath("/home","web_user",!0,!0),yr.FS_createPath("/","tmp",!0,!0),yr.FS_createPath("/tmp","pglite",!0,!0),yr.FS_createPath("/tmp/pglite","bin",!0,!0),yr.FS_createPath("/tmp/pglite","lib",!0,!0),yr.FS_createPath("/tmp/pglite/lib","postgresql",!0,!0),yr.FS_createPath("/tmp/pglite/lib/postgresql","pgxs",!0,!0),yr.FS_createPath("/tmp/pglite/lib/postgresql/pgxs","config",!0,!0),yr.FS_createPath("/tmp/pglite/lib/postgresql/pgxs","src",!0,!0),yr.FS_createPath("/tmp/pglite/lib/postgresql/pgxs/src","makefiles",!0,!0),yr.FS_createPath("/tmp/pglite","share",!0,!0),yr.FS_createPath("/tmp/pglite/share","postgresql",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql","extension",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql","timezone",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Africa",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","America",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","Argentina",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","Indiana",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","Kentucky",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","North_Dakota",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Antarctica",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Arctic",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Asia",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Atlantic",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Australia",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Brazil",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Canada",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Chile",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Etc",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Europe",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Indian",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Mexico",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","Pacific",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql/timezone","US",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql","timezonesets",!0,!0),yr.FS_createPath("/tmp/pglite/share/postgresql","tsearch_data",!0,!0);function Mr(Ar,Dr,Ir){this.start=Ar,this.end=Dr,this.audio=Ir}Mr.prototype={requests:{},open:function(Ar,Dr){this.name=Dr,this.requests[Dr]=this,yr.addRunDependency(`fp ${this.name}`)},send:function(){},onload:function(){var Ar=this.byteArray.subarray(this.start,this.end);this.finish(Ar)},finish:function(Ar){var Dr=this;yr.FS_createDataFile(this.name,null,Ar,!0,!0,!0),yr.removeRunDependency(`fp ${Dr.name}`),this.requests[this.name]=null}};for(var vr=rr.files,Sr=0;Sr<vr.length;++Sr)new Mr(vr[Sr].start,vr[Sr].end,vr[Sr].audio||0).open("GET",vr[Sr].filename);function xr(Ar){br(Ar,"Loading data file failed."),br(Ar.constructor.name===ArrayBuffer.name,"bad input to processPackageData");var Dr=new Uint8Array(Ar);Mr.prototype.byteArray=Dr;for(var Ir=rr.files,kr=0;kr<Ir.length;++kr)Mr.prototype.requests[Ir[kr].filename].onload();yr.removeRunDependency("datafile_pglite.data")}yr.addRunDependency("datafile_pglite.data"),yr.preloadResults??(yr.preloadResults={}),yr.preloadResults[ir]={fromCache:!1},gr?(xr(gr),gr=null):_r=xr}Module.calledRun?wr(Module):(Module.preRun??(Module.preRun=[])).push(wr)}tr({files:[{filename:"/home/web_user/.pgpass",start:0,end:204},{filename:"/tmp/pglite/bin/initdb",start:204,end:223},{filename:"/tmp/pglite/bin/postgres",start:223,end:242},{filename:"/tmp/pglite/lib/postgresql/cyrillic_and_mic.so",start:242,end:4736},{filename:"/tmp/pglite/lib/postgresql/dict_snowball.so",start:4736,end:577939},{filename:"/tmp/pglite/lib/postgresql/euc2004_sjis2004.so",start:577939,end:580012},{filename:"/tmp/pglite/lib/postgresql/euc_cn_and_mic.so",start:580012,end:580953},{filename:"/tmp/pglite/lib/postgresql/euc_jp_and_sjis.so",start:580953,end:588213},{filename:"/tmp/pglite/lib/postgresql/euc_kr_and_mic.so",start:588213,end:589164},{filename:"/tmp/pglite/lib/postgresql/euc_tw_and_big5.so",start:589164,end:593722},{filename:"/tmp/pglite/lib/postgresql/latin2_and_win1250.so",start:593722,end:595128},{filename:"/tmp/pglite/lib/postgresql/latin_and_mic.so",start:595128,end:596149},{filename:"/tmp/pglite/lib/postgresql/libpqwalreceiver.so",start:596149,end:717020},{filename:"/tmp/pglite/lib/postgresql/pgoutput.so",start:717020,end:730469},{filename:"/tmp/pglite/lib/postgresql/pgxs/config/install-sh",start:730469,end:744466},{filename:"/tmp/pglite/lib/postgresql/pgxs/config/missing",start:744466,end:745814},{filename:"/tmp/pglite/lib/postgresql/pgxs/src/Makefile.global",start:745814,end:782478},{filename:"/tmp/pglite/lib/postgresql/pgxs/src/Makefile.port",start:782478,end:783331},{filename:"/tmp/pglite/lib/postgresql/pgxs/src/Makefile.shlib",start:783331,end:798759},{filename:"/tmp/pglite/lib/postgresql/pgxs/src/makefiles/pgxs.mk",start:798759,end:814724},{filename:"/tmp/pglite/lib/postgresql/pgxs/src/nls-global.mk",start:814724,end:821592},{filename:"/tmp/pglite/lib/postgresql/plpgsql.so",start:821592,end:973259},{filename:"/tmp/pglite/lib/postgresql/utf8_and_big5.so",start:973259,end:1088007},{filename:"/tmp/pglite/lib/postgresql/utf8_and_cyrillic.so",start:1088007,end:1093981},{filename:"/tmp/pglite/lib/postgresql/utf8_and_euc2004.so",start:1093981,end:1298913},{filename:"/tmp/pglite/lib/postgresql/utf8_and_euc_cn.so",start:1298913,end:1374093},{filename:"/tmp/pglite/lib/postgresql/utf8_and_euc_jp.so",start:1374093,end:1525321},{filename:"/tmp/pglite/lib/postgresql/utf8_and_euc_kr.so",start:1525321,end:1628177},{filename:"/tmp/pglite/lib/postgresql/utf8_and_euc_tw.so",start:1628177,end:1827733},{filename:"/tmp/pglite/lib/postgresql/utf8_and_gb18030.so",start:1827733,end:2090110},{filename:"/tmp/pglite/lib/postgresql/utf8_and_gbk.so",start:2090110,end:2236642},{filename:"/tmp/pglite/lib/postgresql/utf8_and_iso8859.so",start:2236642,end:2260217},{filename:"/tmp/pglite/lib/postgresql/utf8_and_iso8859_1.so",start:2260217,end:2261189},{filename:"/tmp/pglite/lib/postgresql/utf8_and_johab.so",start:2261189,end:2422893},{filename:"/tmp/pglite/lib/postgresql/utf8_and_sjis.so",start:2422893,end:2504553},{filename:"/tmp/pglite/lib/postgresql/utf8_and_sjis2004.so",start:2504553,end:2631185},{filename:"/tmp/pglite/lib/postgresql/utf8_and_uhc.so",start:2631185,end:2798457},{filename:"/tmp/pglite/lib/postgresql/utf8_and_win.so",start:2798457,end:2824959},{filename:"/tmp/pglite/password",start:2824959,end:2824968},{filename:"/tmp/pglite/share/postgresql/errcodes.txt",start:2824968,end:2858360},{filename:"/tmp/pglite/share/postgresql/extension/plpgsql--1.0.sql",start:2858360,end:2859018},{filename:"/tmp/pglite/share/postgresql/extension/plpgsql.control",start:2859018,end:2859211},{filename:"/tmp/pglite/share/postgresql/information_schema.sql",start:2859211,end:2974734},{filename:"/tmp/pglite/share/postgresql/pg_hba.conf.sample",start:2974734,end:2980359},{filename:"/tmp/pglite/share/postgresql/pg_ident.conf.sample",start:2980359,end:2982999},{filename:"/tmp/pglite/share/postgresql/pg_service.conf.sample",start:2982999,end:2983603},{filename:"/tmp/pglite/share/postgresql/postgres.bki",start:2983603,end:3936871},{filename:"/tmp/pglite/share/postgresql/postgresql.conf.sample",start:3936871,end:3967533},{filename:"/tmp/pglite/share/postgresql/psqlrc.sample",start:3967533,end:3967811},{filename:"/tmp/pglite/share/postgresql/snowball_create.sql",start:3967811,end:4011987},{filename:"/tmp/pglite/share/postgresql/sql_features.txt",start:4011987,end:4047720},{filename:"/tmp/pglite/share/postgresql/system_constraints.sql",start:4047720,end:4056615},{filename:"/tmp/pglite/share/postgresql/system_functions.sql",start:4056615,end:4080918},{filename:"/tmp/pglite/share/postgresql/system_views.sql",start:4080918,end:4132612},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Abidjan",start:4132612,end:4132760},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Accra",start:4132760,end:4132908},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Addis_Ababa",start:4132908,end:4133173},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Algiers",start:4133173,end:4133908},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Asmara",start:4133908,end:4134173},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Asmera",start:4134173,end:4134438},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Bamako",start:4134438,end:4134586},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Bangui",start:4134586,end:4134821},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Banjul",start:4134821,end:4134969},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Bissau",start:4134969,end:4135163},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Blantyre",start:4135163,end:4135312},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Brazzaville",start:4135312,end:4135547},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Bujumbura",start:4135547,end:4135696},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Cairo",start:4135696,end:4138095},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Casablanca",start:4138095,end:4140524},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Ceuta",start:4140524,end:4142576},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Conakry",start:4142576,end:4142724},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Dakar",start:4142724,end:4142872},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Dar_es_Salaam",start:4142872,end:4143137},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Djibouti",start:4143137,end:4143402},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Douala",start:4143402,end:4143637},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/El_Aaiun",start:4143637,end:4145932},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Freetown",start:4145932,end:4146080},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Gaborone",start:4146080,end:4146229},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Harare",start:4146229,end:4146378},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Johannesburg",start:4146378,end:4146624},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Juba",start:4146624,end:4147303},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Kampala",start:4147303,end:4147568},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Khartoum",start:4147568,end:4148247},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Kigali",start:4148247,end:4148396},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Kinshasa",start:4148396,end:4148631},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Lagos",start:4148631,end:4148866},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Libreville",start:4148866,end:4149101},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Lome",start:4149101,end:4149249},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Luanda",start:4149249,end:4149484},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Lubumbashi",start:4149484,end:4149633},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Lusaka",start:4149633,end:4149782},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Malabo",start:4149782,end:4150017},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Maputo",start:4150017,end:4150166},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Maseru",start:4150166,end:4150412},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Mbabane",start:4150412,end:4150658},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Mogadishu",start:4150658,end:4150923},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Monrovia",start:4150923,end:4151131},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Nairobi",start:4151131,end:4151396},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Ndjamena",start:4151396,end:4151595},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Niamey",start:4151595,end:4151830},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Nouakchott",start:4151830,end:4151978},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Ouagadougou",start:4151978,end:4152126},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Porto-Novo",start:4152126,end:4152361},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Sao_Tome",start:4152361,end:4152615},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Timbuktu",start:4152615,end:4152763},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Tripoli",start:4152763,end:4153388},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Tunis",start:4153388,end:4154077},{filename:"/tmp/pglite/share/postgresql/timezone/Africa/Windhoek",start:4154077,end:4155032},{filename:"/tmp/pglite/share/postgresql/timezone/America/Adak",start:4155032,end:4157388},{filename:"/tmp/pglite/share/postgresql/timezone/America/Anchorage",start:4157388,end:4159759},{filename:"/tmp/pglite/share/postgresql/timezone/America/Anguilla",start:4159759,end:4160005},{filename:"/tmp/pglite/share/postgresql/timezone/America/Antigua",start:4160005,end:4160251},{filename:"/tmp/pglite/share/postgresql/timezone/America/Araguaina",start:4160251,end:4161135},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Buenos_Aires",start:4161135,end:4162211},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Catamarca",start:4162211,end:4163287},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/ComodRivadavia",start:4163287,end:4164363},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Cordoba",start:4164363,end:4165439},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Jujuy",start:4165439,end:4166487},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/La_Rioja",start:4166487,end:4167577},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Mendoza",start:4167577,end:4168653},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Rio_Gallegos",start:4168653,end:4169729},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Salta",start:4169729,end:4170777},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/San_Juan",start:4170777,end:4171867},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/San_Luis",start:4171867,end:4172969},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Tucuman",start:4172969,end:4174073},{filename:"/tmp/pglite/share/postgresql/timezone/America/Argentina/Ushuaia",start:4174073,end:4175149},{filename:"/tmp/pglite/share/postgresql/timezone/America/Aruba",start:4175149,end:4175395},{filename:"/tmp/pglite/share/postgresql/timezone/America/Asuncion",start:4175395,end:4177053},{filename:"/tmp/pglite/share/postgresql/timezone/America/Atikokan",start:4177053,end:4177235},{filename:"/tmp/pglite/share/postgresql/timezone/America/Atka",start:4177235,end:4179591},{filename:"/tmp/pglite/share/postgresql/timezone/America/Bahia",start:4179591,end:4180615},{filename:"/tmp/pglite/share/postgresql/timezone/America/Bahia_Banderas",start:4180615,end:4181715},{filename:"/tmp/pglite/share/postgresql/timezone/America/Barbados",start:4181715,end:4182151},{filename:"/tmp/pglite/share/postgresql/timezone/America/Belem",start:4182151,end:4182727},{filename:"/tmp/pglite/share/postgresql/timezone/America/Belize",start:4182727,end:4184341},{filename:"/tmp/pglite/share/postgresql/timezone/America/Blanc-Sablon",start:4184341,end:4184587},{filename:"/tmp/pglite/share/postgresql/timezone/America/Boa_Vista",start:4184587,end:4185219},{filename:"/tmp/pglite/share/postgresql/timezone/America/Bogota",start:4185219,end:4185465},{filename:"/tmp/pglite/share/postgresql/timezone/America/Boise",start:4185465,end:4187875},{filename:"/tmp/pglite/share/postgresql/timezone/America/Buenos_Aires",start:4187875,end:4188951},{filename:"/tmp/pglite/share/postgresql/timezone/America/Cambridge_Bay",start:4188951,end:4191205},{filename:"/tmp/pglite/share/postgresql/timezone/America/Campo_Grande",start:4191205,end:4192649},{filename:"/tmp/pglite/share/postgresql/timezone/America/Cancun",start:4192649,end:4193513},{filename:"/tmp/pglite/share/postgresql/timezone/America/Caracas",start:4193513,end:4193777},{filename:"/tmp/pglite/share/postgresql/timezone/America/Catamarca",start:4193777,end:4194853},{filename:"/tmp/pglite/share/postgresql/timezone/America/Cayenne",start:4194853,end:4195051},{filename:"/tmp/pglite/share/postgresql/timezone/America/Cayman",start:4195051,end:4195233},{filename:"/tmp/pglite/share/postgresql/timezone/America/Chicago",start:4195233,end:4198825},{filename:"/tmp/pglite/share/postgresql/timezone/America/Chihuahua",start:4198825,end:4199927},{filename:"/tmp/pglite/share/postgresql/timezone/America/Ciudad_Juarez",start:4199927,end:4201465},{filename:"/tmp/pglite/share/postgresql/timezone/America/Coral_Harbour",start:4201465,end:4201647},{filename:"/tmp/pglite/share/postgresql/timezone/America/Cordoba",start:4201647,end:4202723},{filename:"/tmp/pglite/share/postgresql/timezone/America/Costa_Rica",start:4202723,end:4203039},{filename:"/tmp/pglite/share/postgresql/timezone/America/Coyhaique",start:4203039,end:4205179},{filename:"/tmp/pglite/share/postgresql/timezone/America/Creston",start:4205179,end:4205539},{filename:"/tmp/pglite/share/postgresql/timezone/America/Cuiaba",start:4205539,end:4206955},{filename:"/tmp/pglite/share/postgresql/timezone/America/Curacao",start:4206955,end:4207201},{filename:"/tmp/pglite/share/postgresql/timezone/America/Danmarkshavn",start:4207201,end:4207899},{filename:"/tmp/pglite/share/postgresql/timezone/America/Dawson",start:4207899,end:4209513},{filename:"/tmp/pglite/share/postgresql/timezone/America/Dawson_Creek",start:4209513,end:4210563},{filename:"/tmp/pglite/share/postgresql/timezone/America/Denver",start:4210563,end:4213023},{filename:"/tmp/pglite/share/postgresql/timezone/America/Detroit",start:4213023,end:4215253},{filename:"/tmp/pglite/share/postgresql/timezone/America/Dominica",start:4215253,end:4215499},{filename:"/tmp/pglite/share/postgresql/timezone/America/Edmonton",start:4215499,end:4217831},{filename:"/tmp/pglite/share/postgresql/timezone/America/Eirunepe",start:4217831,end:4218487},{filename:"/tmp/pglite/share/postgresql/timezone/America/El_Salvador",start:4218487,end:4218711},{filename:"/tmp/pglite/share/postgresql/timezone/America/Ensenada",start:4218711,end:4221169},{filename:"/tmp/pglite/share/postgresql/timezone/America/Fort_Nelson",start:4221169,end:4223409},{filename:"/tmp/pglite/share/postgresql/timezone/America/Fort_Wayne",start:4223409,end:4225091},{filename:"/tmp/pglite/share/postgresql/timezone/America/Fortaleza",start:4225091,end:4225807},{filename:"/tmp/pglite/share/postgresql/timezone/America/Glace_Bay",start:4225807,end:4227999},{filename:"/tmp/pglite/share/postgresql/timezone/America/Godthab",start:4227999,end:4229902},{filename:"/tmp/pglite/share/postgresql/timezone/America/Goose_Bay",start:4229902,end:4233112},{filename:"/tmp/pglite/share/postgresql/timezone/America/Grand_Turk",start:4233112,end:4234946},{filename:"/tmp/pglite/share/postgresql/timezone/America/Grenada",start:4234946,end:4235192},{filename:"/tmp/pglite/share/postgresql/timezone/America/Guadeloupe",start:4235192,end:4235438},{filename:"/tmp/pglite/share/postgresql/timezone/America/Guatemala",start:4235438,end:4235718},{filename:"/tmp/pglite/share/postgresql/timezone/America/Guayaquil",start:4235718,end:4235964},{filename:"/tmp/pglite/share/postgresql/timezone/America/Guyana",start:4235964,end:4236226},{filename:"/tmp/pglite/share/postgresql/timezone/America/Halifax",start:4236226,end:4239650},{filename:"/tmp/pglite/share/postgresql/timezone/America/Havana",start:4239650,end:4242066},{filename:"/tmp/pglite/share/postgresql/timezone/America/Hermosillo",start:4242066,end:4242454},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Indianapolis",start:4242454,end:4244136},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Knox",start:4244136,end:4246580},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Marengo",start:4246580,end:4248318},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Petersburg",start:4248318,end:4250238},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Tell_City",start:4250238,end:4251938},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Vevay",start:4251938,end:4253368},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Vincennes",start:4253368,end:4255078},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indiana/Winamac",start:4255078,end:4256872},{filename:"/tmp/pglite/share/postgresql/timezone/America/Indianapolis",start:4256872,end:4258554},{filename:"/tmp/pglite/share/postgresql/timezone/America/Inuvik",start:4258554,end:4260628},{filename:"/tmp/pglite/share/postgresql/timezone/America/Iqaluit",start:4260628,end:4262830},{filename:"/tmp/pglite/share/postgresql/timezone/America/Jamaica",start:4262830,end:4263312},{filename:"/tmp/pglite/share/postgresql/timezone/America/Jujuy",start:4263312,end:4264360},{filename:"/tmp/pglite/share/postgresql/timezone/America/Juneau",start:4264360,end:4266713},{filename:"/tmp/pglite/share/postgresql/timezone/America/Kentucky/Louisville",start:4266713,end:4269501},{filename:"/tmp/pglite/share/postgresql/timezone/America/Kentucky/Monticello",start:4269501,end:4271869},{filename:"/tmp/pglite/share/postgresql/timezone/America/Knox_IN",start:4271869,end:4274313},{filename:"/tmp/pglite/share/postgresql/timezone/America/Kralendijk",start:4274313,end:4274559},{filename:"/tmp/pglite/share/postgresql/timezone/America/La_Paz",start:4274559,end:4274791},{filename:"/tmp/pglite/share/postgresql/timezone/America/Lima",start:4274791,end:4275197},{filename:"/tmp/pglite/share/postgresql/timezone/America/Los_Angeles",start:4275197,end:4278049},{filename:"/tmp/pglite/share/postgresql/timezone/America/Louisville",start:4278049,end:4280837},{filename:"/tmp/pglite/share/postgresql/timezone/America/Lower_Princes",start:4280837,end:4281083},{filename:"/tmp/pglite/share/postgresql/timezone/America/Maceio",start:4281083,end:4281827},{filename:"/tmp/pglite/share/postgresql/timezone/America/Managua",start:4281827,end:4282257},{filename:"/tmp/pglite/share/postgresql/timezone/America/Manaus",start:4282257,end:4282861},{filename:"/tmp/pglite/share/postgresql/timezone/America/Marigot",start:4282861,end:4283107},{filename:"/tmp/pglite/share/postgresql/timezone/America/Martinique",start:4283107,end:4283339},{filename:"/tmp/pglite/share/postgresql/timezone/America/Matamoros",start:4283339,end:4284757},{filename:"/tmp/pglite/share/postgresql/timezone/America/Mazatlan",start:4284757,end:4285817},{filename:"/tmp/pglite/share/postgresql/timezone/America/Mendoza",start:4285817,end:4286893},{filename:"/tmp/pglite/share/postgresql/timezone/America/Menominee",start:4286893,end:4289167},{filename:"/tmp/pglite/share/postgresql/timezone/America/Merida",start:4289167,end:4290171},{filename:"/tmp/pglite/share/postgresql/timezone/America/Metlakatla",start:4290171,end:4291594},{filename:"/tmp/pglite/share/postgresql/timezone/America/Mexico_City",start:4291594,end:4292816},{filename:"/tmp/pglite/share/postgresql/timezone/America/Miquelon",start:4292816,end:4294482},{filename:"/tmp/pglite/share/postgresql/timezone/America/Moncton",start:4294482,end:4297636},{filename:"/tmp/pglite/share/postgresql/timezone/America/Monterrey",start:4297636,end:4298750},{filename:"/tmp/pglite/share/postgresql/timezone/America/Montevideo",start:4298750,end:4300260},{filename:"/tmp/pglite/share/postgresql/timezone/America/Montreal",start:4300260,end:4303754},{filename:"/tmp/pglite/share/postgresql/timezone/America/Montserrat",start:4303754,end:4304e3},{filename:"/tmp/pglite/share/postgresql/timezone/America/Nassau",start:4304e3,end:4307494},{filename:"/tmp/pglite/share/postgresql/timezone/America/New_York",start:4307494,end:4311046},{filename:"/tmp/pglite/share/postgresql/timezone/America/Nipigon",start:4311046,end:4314540},{filename:"/tmp/pglite/share/postgresql/timezone/America/Nome",start:4314540,end:4316907},{filename:"/tmp/pglite/share/postgresql/timezone/America/Noronha",start:4316907,end:4317623},{filename:"/tmp/pglite/share/postgresql/timezone/America/North_Dakota/Beulah",start:4317623,end:4320019},{filename:"/tmp/pglite/share/postgresql/timezone/America/North_Dakota/Center",start:4320019,end:4322415},{filename:"/tmp/pglite/share/postgresql/timezone/America/North_Dakota/New_Salem",start:4322415,end:4324811},{filename:"/tmp/pglite/share/postgresql/timezone/America/Nuuk",start:4324811,end:4326714},{filename:"/tmp/pglite/share/postgresql/timezone/America/Ojinaga",start:4326714,end:4328238},{filename:"/tmp/pglite/share/postgresql/timezone/America/Panama",start:4328238,end:4328420},{filename:"/tmp/pglite/share/postgresql/timezone/America/Pangnirtung",start:4328420,end:4330622},{filename:"/tmp/pglite/share/postgresql/timezone/America/Paramaribo",start:4330622,end:4330884},{filename:"/tmp/pglite/share/postgresql/timezone/America/Phoenix",start:4330884,end:4331244},{filename:"/tmp/pglite/share/postgresql/timezone/America/Port-au-Prince",start:4331244,end:4332678},{filename:"/tmp/pglite/share/postgresql/timezone/America/Port_of_Spain",start:4332678,end:4332924},{filename:"/tmp/pglite/share/postgresql/timezone/America/Porto_Acre",start:4332924,end:4333552},{filename:"/tmp/pglite/share/postgresql/timezone/America/Porto_Velho",start:4333552,end:4334128},{filename:"/tmp/pglite/share/postgresql/timezone/America/Puerto_Rico",start:4334128,end:4334374},{filename:"/tmp/pglite/share/postgresql/timezone/America/Punta_Arenas",start:4334374,end:4336290},{filename:"/tmp/pglite/share/postgresql/timezone/America/Rainy_River",start:4336290,end:4339158},{filename:"/tmp/pglite/share/postgresql/timezone/America/Rankin_Inlet",start:4339158,end:4341224},{filename:"/tmp/pglite/share/postgresql/timezone/America/Recife",start:4341224,end:4341940},{filename:"/tmp/pglite/share/postgresql/timezone/America/Regina",start:4341940,end:4342920},{filename:"/tmp/pglite/share/postgresql/timezone/America/Resolute",start:4342920,end:4344986},{filename:"/tmp/pglite/share/postgresql/timezone/America/Rio_Branco",start:4344986,end:4345614},{filename:"/tmp/pglite/share/postgresql/timezone/America/Rosario",start:4345614,end:4346690},{filename:"/tmp/pglite/share/postgresql/timezone/America/Santa_Isabel",start:4346690,end:4349148},{filename:"/tmp/pglite/share/postgresql/timezone/America/Santarem",start:4349148,end:4349750},{filename:"/tmp/pglite/share/postgresql/timezone/America/Santiago",start:4349750,end:4352279},{filename:"/tmp/pglite/share/postgresql/timezone/America/Santo_Domingo",start:4352279,end:4352737},{filename:"/tmp/pglite/share/postgresql/timezone/America/Sao_Paulo",start:4352737,end:4354181},{filename:"/tmp/pglite/share/postgresql/timezone/America/Scoresbysund",start:4354181,end:4356130},{filename:"/tmp/pglite/share/postgresql/timezone/America/Shiprock",start:4356130,end:4358590},{filename:"/tmp/pglite/share/postgresql/timezone/America/Sitka",start:4358590,end:4360919},{filename:"/tmp/pglite/share/postgresql/timezone/America/St_Barthelemy",start:4360919,end:4361165},{filename:"/tmp/pglite/share/postgresql/timezone/America/St_Johns",start:4361165,end:4364820},{filename:"/tmp/pglite/share/postgresql/timezone/America/St_Kitts",start:4364820,end:4365066},{filename:"/tmp/pglite/share/postgresql/timezone/America/St_Lucia",start:4365066,end:4365312},{filename:"/tmp/pglite/share/postgresql/timezone/America/St_Thomas",start:4365312,end:4365558},{filename:"/tmp/pglite/share/postgresql/timezone/America/St_Vincent",start:4365558,end:4365804},{filename:"/tmp/pglite/share/postgresql/timezone/America/Swift_Current",start:4365804,end:4366364},{filename:"/tmp/pglite/share/postgresql/timezone/America/Tegucigalpa",start:4366364,end:4366616},{filename:"/tmp/pglite/share/postgresql/timezone/America/Thule",start:4366616,end:4368118},{filename:"/tmp/pglite/share/postgresql/timezone/America/Thunder_Bay",start:4368118,end:4371612},{filename:"/tmp/pglite/share/postgresql/timezone/America/Tijuana",start:4371612,end:4374070},{filename:"/tmp/pglite/share/postgresql/timezone/America/Toronto",start:4374070,end:4377564},{filename:"/tmp/pglite/share/postgresql/timezone/America/Tortola",start:4377564,end:4377810},{filename:"/tmp/pglite/share/postgresql/timezone/America/Vancouver",start:4377810,end:4380702},{filename:"/tmp/pglite/share/postgresql/timezone/America/Virgin",start:4380702,end:4380948},{filename:"/tmp/pglite/share/postgresql/timezone/America/Whitehorse",start:4380948,end:4382562},{filename:"/tmp/pglite/share/postgresql/timezone/America/Winnipeg",start:4382562,end:4385430},{filename:"/tmp/pglite/share/postgresql/timezone/America/Yakutat",start:4385430,end:4387735},{filename:"/tmp/pglite/share/postgresql/timezone/America/Yellowknife",start:4387735,end:4390067},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Casey",start:4390067,end:4390504},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Davis",start:4390504,end:4390801},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/DumontDUrville",start:4390801,end:4390987},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Macquarie",start:4390987,end:4393247},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Mawson",start:4393247,end:4393446},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/McMurdo",start:4393446,end:4395883},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Palmer",start:4395883,end:4397301},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Rothera",start:4397301,end:4397465},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/South_Pole",start:4397465,end:4399902},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Syowa",start:4399902,end:4400067},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Troll",start:4400067,end:4401229},{filename:"/tmp/pglite/share/postgresql/timezone/Antarctica/Vostok",start:4401229,end:4401456},{filename:"/tmp/pglite/share/postgresql/timezone/Arctic/Longyearbyen",start:4401456,end:4403754},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Aden",start:4403754,end:4403919},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Almaty",start:4403919,end:4404916},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Amman",start:4404916,end:4406363},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Anadyr",start:4406363,end:4407551},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Aqtau",start:4407551,end:4408534},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Aqtobe",start:4408534,end:4409545},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Ashgabat",start:4409545,end:4410164},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Ashkhabad",start:4410164,end:4410783},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Atyrau",start:4410783,end:4411774},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Baghdad",start:4411774,end:4412757},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Bahrain",start:4412757,end:4412956},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Baku",start:4412956,end:4414183},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Bangkok",start:4414183,end:4414382},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Barnaul",start:4414382,end:4415603},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Beirut",start:4415603,end:4417757},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Bishkek",start:4417757,end:4418740},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Brunei",start:4418740,end:4419223},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Calcutta",start:4419223,end:4419508},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Chita",start:4419508,end:4420729},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Choibalsan",start:4420729,end:4421620},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Chongqing",start:4421620,end:4422181},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Chungking",start:4422181,end:4422742},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Colombo",start:4422742,end:4423114},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Dacca",start:4423114,end:4423451},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Damascus",start:4423451,end:4425338},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Dhaka",start:4425338,end:4425675},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Dili",start:4425675,end:4425946},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Dubai",start:4425946,end:4426111},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Dushanbe",start:4426111,end:4426702},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Famagusta",start:4426702,end:4428730},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Gaza",start:4428730,end:4432574},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Harbin",start:4432574,end:4433135},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Hebron",start:4433135,end:4437007},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Ho_Chi_Minh",start:4437007,end:4437358},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Hong_Kong",start:4437358,end:4438591},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Hovd",start:4438591,end:4439482},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Irkutsk",start:4439482,end:4440725},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Istanbul",start:4440725,end:4442672},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Jakarta",start:4442672,end:4443055},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Jayapura",start:4443055,end:4443276},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Jerusalem",start:4443276,end:4445664},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kabul",start:4445664,end:4445872},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kamchatka",start:4445872,end:4447038},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Karachi",start:4447038,end:4447417},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kashgar",start:4447417,end:4447582},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kathmandu",start:4447582,end:4447794},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Katmandu",start:4447794,end:4448006},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Khandyga",start:4448006,end:4449277},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kolkata",start:4449277,end:4449562},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Krasnoyarsk",start:4449562,end:4450769},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kuala_Lumpur",start:4450769,end:4451184},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kuching",start:4451184,end:4451667},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Kuwait",start:4451667,end:4451832},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Macao",start:4451832,end:4453059},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Macau",start:4453059,end:4454286},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Magadan",start:4454286,end:4455508},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Makassar",start:4455508,end:4455762},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Manila",start:4455762,end:4456184},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Muscat",start:4456184,end:4456349},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Nicosia",start:4456349,end:4458351},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Novokuznetsk",start:4458351,end:4459516},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Novosibirsk",start:4459516,end:4460737},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Omsk",start:4460737,end:4461944},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Oral",start:4461944,end:4462949},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Phnom_Penh",start:4462949,end:4463148},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Pontianak",start:4463148,end:4463501},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Pyongyang",start:4463501,end:4463738},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Qatar",start:4463738,end:4463937},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Qostanay",start:4463937,end:4464976},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Qyzylorda",start:4464976,end:4466001},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Rangoon",start:4466001,end:4466269},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Riyadh",start:4466269,end:4466434},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Saigon",start:4466434,end:4466785},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Sakhalin",start:4466785,end:4467987},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Samarkand",start:4467987,end:4468564},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Seoul",start:4468564,end:4469181},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Shanghai",start:4469181,end:4469742},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Singapore",start:4469742,end:4470157},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Srednekolymsk",start:4470157,end:4471365},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Taipei",start:4471365,end:4472126},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Tashkent",start:4472126,end:4472717},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Tbilisi",start:4472717,end:4473752},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Tehran",start:4473752,end:4475014},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Tel_Aviv",start:4475014,end:4477402},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Thimbu",start:4477402,end:4477605},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Thimphu",start:4477605,end:4477808},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Tokyo",start:4477808,end:4478117},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Tomsk",start:4478117,end:4479338},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Ujung_Pandang",start:4479338,end:4479592},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Ulaanbaatar",start:4479592,end:4480483},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Ulan_Bator",start:4480483,end:4481374},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Urumqi",start:4481374,end:4481539},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Ust-Nera",start:4481539,end:4482791},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Vientiane",start:4482791,end:4482990},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Vladivostok",start:4482990,end:4484198},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Yakutsk",start:4484198,end:4485405},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Yangon",start:4485405,end:4485673},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Yekaterinburg",start:4485673,end:4486916},{filename:"/tmp/pglite/share/postgresql/timezone/Asia/Yerevan",start:4486916,end:4488067},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Azores",start:4488067,end:4491523},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Bermuda",start:4491523,end:4493919},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Canary",start:4493919,end:4495816},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Cape_Verde",start:4495816,end:4496086},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Faeroe",start:4496086,end:4497901},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Faroe",start:4497901,end:4499716},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Jan_Mayen",start:4499716,end:4502014},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Madeira",start:4502014,end:4505391},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Reykjavik",start:4505391,end:4505539},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/South_Georgia",start:4505539,end:4505703},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/St_Helena",start:4505703,end:4505851},{filename:"/tmp/pglite/share/postgresql/timezone/Atlantic/Stanley",start:4505851,end:4507065},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/ACT",start:4507065,end:4509255},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Adelaide",start:4509255,end:4511463},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Brisbane",start:4511463,end:4511882},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Broken_Hill",start:4511882,end:4514111},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Canberra",start:4514111,end:4516301},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Currie",start:4516301,end:4518659},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Darwin",start:4518659,end:4518984},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Eucla",start:4518984,end:4519454},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Hobart",start:4519454,end:4521812},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/LHI",start:4521812,end:4523672},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Lindeman",start:4523672,end:4524147},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Lord_Howe",start:4524147,end:4526007},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Melbourne",start:4526007,end:4528197},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/NSW",start:4528197,end:4530387},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/North",start:4530387,end:4530712},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Perth",start:4530712,end:4531158},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Queensland",start:4531158,end:4531577},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/South",start:4531577,end:4533785},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Sydney",start:4533785,end:4535975},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Tasmania",start:4535975,end:4538333},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Victoria",start:4538333,end:4540523},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/West",start:4540523,end:4540969},{filename:"/tmp/pglite/share/postgresql/timezone/Australia/Yancowinna",start:4540969,end:4543198},{filename:"/tmp/pglite/share/postgresql/timezone/Brazil/Acre",start:4543198,end:4543826},{filename:"/tmp/pglite/share/postgresql/timezone/Brazil/DeNoronha",start:4543826,end:4544542},{filename:"/tmp/pglite/share/postgresql/timezone/Brazil/East",start:4544542,end:4545986},{filename:"/tmp/pglite/share/postgresql/timezone/Brazil/West",start:4545986,end:4546590},{filename:"/tmp/pglite/share/postgresql/timezone/CET",start:4546590,end:4549523},{filename:"/tmp/pglite/share/postgresql/timezone/CST6CDT",start:4549523,end:4553115},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Atlantic",start:4553115,end:4556539},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Central",start:4556539,end:4559407},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Eastern",start:4559407,end:4562901},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Mountain",start:4562901,end:4565233},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Newfoundland",start:4565233,end:4568888},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Pacific",start:4568888,end:4571780},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Saskatchewan",start:4571780,end:4572760},{filename:"/tmp/pglite/share/postgresql/timezone/Canada/Yukon",start:4572760,end:4574374},{filename:"/tmp/pglite/share/postgresql/timezone/Chile/Continental",start:4574374,end:4576903},{filename:"/tmp/pglite/share/postgresql/timezone/Chile/EasterIsland",start:4576903,end:4579136},{filename:"/tmp/pglite/share/postgresql/timezone/Cuba",start:4579136,end:4581552},{filename:"/tmp/pglite/share/postgresql/timezone/EET",start:4581552,end:4583814},{filename:"/tmp/pglite/share/postgresql/timezone/EST",start:4583814,end:4583996},{filename:"/tmp/pglite/share/postgresql/timezone/EST5EDT",start:4583996,end:4587548},{filename:"/tmp/pglite/share/postgresql/timezone/Egypt",start:4587548,end:4589947},{filename:"/tmp/pglite/share/postgresql/timezone/Eire",start:4589947,end:4593439},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT",start:4593439,end:4593553},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+0",start:4593553,end:4593667},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+1",start:4593667,end:4593783},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+10",start:4593783,end:4593900},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+11",start:4593900,end:4594017},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+12",start:4594017,end:4594134},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+2",start:4594134,end:4594250},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+3",start:4594250,end:4594366},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+4",start:4594366,end:4594482},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+5",start:4594482,end:4594598},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+6",start:4594598,end:4594714},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+7",start:4594714,end:4594830},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+8",start:4594830,end:4594946},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT+9",start:4594946,end:4595062},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-0",start:4595062,end:4595176},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-1",start:4595176,end:4595293},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-10",start:4595293,end:4595411},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-11",start:4595411,end:4595529},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-12",start:4595529,end:4595647},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-13",start:4595647,end:4595765},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-14",start:4595765,end:4595883},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-2",start:4595883,end:4596e3},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-3",start:4596e3,end:4596117},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-4",start:4596117,end:4596234},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-5",start:4596234,end:4596351},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-6",start:4596351,end:4596468},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-7",start:4596468,end:4596585},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-8",start:4596585,end:4596702},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT-9",start:4596702,end:4596819},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/GMT0",start:4596819,end:4596933},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/Greenwich",start:4596933,end:4597047},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/UCT",start:4597047,end:4597161},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/UTC",start:4597161,end:4597275},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/Universal",start:4597275,end:4597389},{filename:"/tmp/pglite/share/postgresql/timezone/Etc/Zulu",start:4597389,end:4597503},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Amsterdam",start:4597503,end:4600436},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Andorra",start:4600436,end:4602178},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Astrakhan",start:4602178,end:4603343},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Athens",start:4603343,end:4605605},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Belfast",start:4605605,end:4609269},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Belgrade",start:4609269,end:4611189},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Berlin",start:4611189,end:4613487},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Bratislava",start:4613487,end:4615788},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Brussels",start:4615788,end:4618721},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Bucharest",start:4618721,end:4620905},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Budapest",start:4620905,end:4623273},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Busingen",start:4623273,end:4625182},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Chisinau",start:4625182,end:4627572},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Copenhagen",start:4627572,end:4629870},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Dublin",start:4629870,end:4633362},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Gibraltar",start:4633362,end:4636430},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Guernsey",start:4636430,end:4640094},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Helsinki",start:4640094,end:4641994},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Isle_of_Man",start:4641994,end:4645658},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Istanbul",start:4645658,end:4647605},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Jersey",start:4647605,end:4651269},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Kaliningrad",start:4651269,end:4652762},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Kiev",start:4652762,end:4654882},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Kirov",start:4654882,end:4656067},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Kyiv",start:4656067,end:4658187},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Lisbon",start:4658187,end:4661714},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Ljubljana",start:4661714,end:4663634},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/London",start:4663634,end:4667298},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Luxembourg",start:4667298,end:4670231},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Madrid",start:4670231,end:4672845},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Malta",start:4672845,end:4675465},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Mariehamn",start:4675465,end:4677365},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Minsk",start:4677365,end:4678686},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Monaco",start:4678686,end:4681648},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Moscow",start:4681648,end:4683183},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Nicosia",start:4683183,end:4685185},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Oslo",start:4685185,end:4687483},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Paris",start:4687483,end:4690445},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Podgorica",start:4690445,end:4692365},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Prague",start:4692365,end:4694666},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Riga",start:4694666,end:4696864},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Rome",start:4696864,end:4699505},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Samara",start:4699505,end:4700720},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/San_Marino",start:4700720,end:4703361},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Sarajevo",start:4703361,end:4705281},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Saratov",start:4705281,end:4706464},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Simferopol",start:4706464,end:4707933},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Skopje",start:4707933,end:4709853},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Sofia",start:4709853,end:4711930},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Stockholm",start:4711930,end:4714228},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Tallinn",start:4714228,end:4716376},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Tirane",start:4716376,end:4718460},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Tiraspol",start:4718460,end:4720850},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Ulyanovsk",start:4720850,end:4722117},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Uzhgorod",start:4722117,end:4724237},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Vaduz",start:4724237,end:4726146},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Vatican",start:4726146,end:4728787},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Vienna",start:4728787,end:4730987},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Vilnius",start:4730987,end:4733149},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Volgograd",start:4733149,end:4734342},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Warsaw",start:4734342,end:4736996},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Zagreb",start:4736996,end:4738916},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Zaporozhye",start:4738916,end:4741036},{filename:"/tmp/pglite/share/postgresql/timezone/Europe/Zurich",start:4741036,end:4742945},{filename:"/tmp/pglite/share/postgresql/timezone/Factory",start:4742945,end:4743061},{filename:"/tmp/pglite/share/postgresql/timezone/GB",start:4743061,end:4746725},{filename:"/tmp/pglite/share/postgresql/timezone/GB-Eire",start:4746725,end:4750389},{filename:"/tmp/pglite/share/postgresql/timezone/GMT",start:4750389,end:4750503},{filename:"/tmp/pglite/share/postgresql/timezone/GMT+0",start:4750503,end:4750617},{filename:"/tmp/pglite/share/postgresql/timezone/GMT-0",start:4750617,end:4750731},{filename:"/tmp/pglite/share/postgresql/timezone/GMT0",start:4750731,end:4750845},{filename:"/tmp/pglite/share/postgresql/timezone/Greenwich",start:4750845,end:4750959},{filename:"/tmp/pglite/share/postgresql/timezone/HST",start:4750959,end:4751288},{filename:"/tmp/pglite/share/postgresql/timezone/Hongkong",start:4751288,end:4752521},{filename:"/tmp/pglite/share/postgresql/timezone/Iceland",start:4752521,end:4752669},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Antananarivo",start:4752669,end:4752934},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Chagos",start:4752934,end:4753133},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Christmas",start:4753133,end:4753332},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Cocos",start:4753332,end:4753600},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Comoro",start:4753600,end:4753865},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Kerguelen",start:4753865,end:4754064},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Mahe",start:4754064,end:4754229},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Maldives",start:4754229,end:4754428},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Mauritius",start:4754428,end:4754669},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Mayotte",start:4754669,end:4754934},{filename:"/tmp/pglite/share/postgresql/timezone/Indian/Reunion",start:4754934,end:4755099},{filename:"/tmp/pglite/share/postgresql/timezone/Iran",start:4755099,end:4756361},{filename:"/tmp/pglite/share/postgresql/timezone/Israel",start:4756361,end:4758749},{filename:"/tmp/pglite/share/postgresql/timezone/Jamaica",start:4758749,end:4759231},{filename:"/tmp/pglite/share/postgresql/timezone/Japan",start:4759231,end:4759540},{filename:"/tmp/pglite/share/postgresql/timezone/Kwajalein",start:4759540,end:4759856},{filename:"/tmp/pglite/share/postgresql/timezone/Libya",start:4759856,end:4760481},{filename:"/tmp/pglite/share/postgresql/timezone/MET",start:4760481,end:4763414},{filename:"/tmp/pglite/share/postgresql/timezone/MST",start:4763414,end:4763774},{filename:"/tmp/pglite/share/postgresql/timezone/MST7MDT",start:4763774,end:4766234},{filename:"/tmp/pglite/share/postgresql/timezone/Mexico/BajaNorte",start:4766234,end:4768692},{filename:"/tmp/pglite/share/postgresql/timezone/Mexico/BajaSur",start:4768692,end:4769752},{filename:"/tmp/pglite/share/postgresql/timezone/Mexico/General",start:4769752,end:4770974},{filename:"/tmp/pglite/share/postgresql/timezone/NZ",start:4770974,end:4773411},{filename:"/tmp/pglite/share/postgresql/timezone/NZ-CHAT",start:4773411,end:4775479},{filename:"/tmp/pglite/share/postgresql/timezone/Navajo",start:4775479,end:4777939},{filename:"/tmp/pglite/share/postgresql/timezone/PRC",start:4777939,end:4778500},{filename:"/tmp/pglite/share/postgresql/timezone/PST8PDT",start:4778500,end:4781352},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Apia",start:4781352,end:4781964},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Auckland",start:4781964,end:4784401},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Bougainville",start:4784401,end:4784669},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Chatham",start:4784669,end:4786737},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Chuuk",start:4786737,end:4786923},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Easter",start:4786923,end:4789156},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Efate",start:4789156,end:4789694},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Enderbury",start:4789694,end:4789928},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Fakaofo",start:4789928,end:4790128},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Fiji",start:4790128,end:4790706},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Funafuti",start:4790706,end:4790872},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Galapagos",start:4790872,end:4791110},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Gambier",start:4791110,end:4791274},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Guadalcanal",start:4791274,end:4791440},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Guam",start:4791440,end:4791934},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Honolulu",start:4791934,end:4792263},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Johnston",start:4792263,end:4792592},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Kanton",start:4792592,end:4792826},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Kiritimati",start:4792826,end:4793064},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Kosrae",start:4793064,end:4793415},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Kwajalein",start:4793415,end:4793731},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Majuro",start:4793731,end:4793897},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Marquesas",start:4793897,end:4794070},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Midway",start:4794070,end:4794245},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Nauru",start:4794245,end:4794497},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Niue",start:4794497,end:4794700},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Norfolk",start:4794700,end:4795580},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Noumea",start:4795580,end:4795884},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Pago_Pago",start:4795884,end:4796059},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Palau",start:4796059,end:4796239},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Pitcairn",start:4796239,end:4796441},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Pohnpei",start:4796441,end:4796607},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Ponape",start:4796607,end:4796773},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Port_Moresby",start:4796773,end:4796959},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Rarotonga",start:4796959,end:4797562},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Saipan",start:4797562,end:4798056},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Samoa",start:4798056,end:4798231},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Tahiti",start:4798231,end:4798396},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Tarawa",start:4798396,end:4798562},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Tongatapu",start:4798562,end:4798934},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Truk",start:4798934,end:4799120},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Wake",start:4799120,end:4799286},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Wallis",start:4799286,end:4799452},{filename:"/tmp/pglite/share/postgresql/timezone/Pacific/Yap",start:4799452,end:4799638},{filename:"/tmp/pglite/share/postgresql/timezone/Poland",start:4799638,end:4802292},{filename:"/tmp/pglite/share/postgresql/timezone/Portugal",start:4802292,end:4805819},{filename:"/tmp/pglite/share/postgresql/timezone/ROC",start:4805819,end:4806580},{filename:"/tmp/pglite/share/postgresql/timezone/ROK",start:4806580,end:4807197},{filename:"/tmp/pglite/share/postgresql/timezone/Singapore",start:4807197,end:4807612},{filename:"/tmp/pglite/share/postgresql/timezone/Turkey",start:4807612,end:4809559},{filename:"/tmp/pglite/share/postgresql/timezone/UCT",start:4809559,end:4809673},{filename:"/tmp/pglite/share/postgresql/timezone/US/Alaska",start:4809673,end:4812044},{filename:"/tmp/pglite/share/postgresql/timezone/US/Aleutian",start:4812044,end:4814400},{filename:"/tmp/pglite/share/postgresql/timezone/US/Arizona",start:4814400,end:4814760},{filename:"/tmp/pglite/share/postgresql/timezone/US/Central",start:4814760,end:4818352},{filename:"/tmp/pglite/share/postgresql/timezone/US/East-Indiana",start:4818352,end:4820034},{filename:"/tmp/pglite/share/postgresql/timezone/US/Eastern",start:4820034,end:4823586},{filename:"/tmp/pglite/share/postgresql/timezone/US/Hawaii",start:4823586,end:4823915},{filename:"/tmp/pglite/share/postgresql/timezone/US/Indiana-Starke",start:4823915,end:4826359},{filename:"/tmp/pglite/share/postgresql/timezone/US/Michigan",start:4826359,end:4828589},{filename:"/tmp/pglite/share/postgresql/timezone/US/Mountain",start:4828589,end:4831049},{filename:"/tmp/pglite/share/postgresql/timezone/US/Pacific",start:4831049,end:4833901},{filename:"/tmp/pglite/share/postgresql/timezone/US/Samoa",start:4833901,end:4834076},{filename:"/tmp/pglite/share/postgresql/timezone/UTC",start:4834076,end:4834190},{filename:"/tmp/pglite/share/postgresql/timezone/Universal",start:4834190,end:4834304},{filename:"/tmp/pglite/share/postgresql/timezone/W-SU",start:4834304,end:4835839},{filename:"/tmp/pglite/share/postgresql/timezone/WET",start:4835839,end:4839366},{filename:"/tmp/pglite/share/postgresql/timezone/Zulu",start:4839366,end:4839480},{filename:"/tmp/pglite/share/postgresql/timezonesets/Africa.txt",start:4839480,end:4846453},{filename:"/tmp/pglite/share/postgresql/timezonesets/America.txt",start:4846453,end:4857460},{filename:"/tmp/pglite/share/postgresql/timezonesets/Antarctica.txt",start:4857460,end:4858594},{filename:"/tmp/pglite/share/postgresql/timezonesets/Asia.txt",start:4858594,end:4866905},{filename:"/tmp/pglite/share/postgresql/timezonesets/Atlantic.txt",start:4866905,end:4870438},{filename:"/tmp/pglite/share/postgresql/timezonesets/Australia",start:4870438,end:4871573},{filename:"/tmp/pglite/share/postgresql/timezonesets/Australia.txt",start:4871573,end:4874957},{filename:"/tmp/pglite/share/postgresql/timezonesets/Default",start:4874957,end:4902171},{filename:"/tmp/pglite/share/postgresql/timezonesets/Etc.txt",start:4902171,end:4903421},{filename:"/tmp/pglite/share/postgresql/timezonesets/Europe.txt",start:4903421,end:4912167},{filename:"/tmp/pglite/share/postgresql/timezonesets/India",start:4912167,end:4912760},{filename:"/tmp/pglite/share/postgresql/timezonesets/Indian.txt",start:4912760,end:4914021},{filename:"/tmp/pglite/share/postgresql/timezonesets/Pacific.txt",start:4914021,end:4917789},{filename:"/tmp/pglite/share/postgresql/tsearch_data/danish.stop",start:4917789,end:4918213},{filename:"/tmp/pglite/share/postgresql/tsearch_data/dutch.stop",start:4918213,end:4918666},{filename:"/tmp/pglite/share/postgresql/tsearch_data/english.stop",start:4918666,end:4919288},{filename:"/tmp/pglite/share/postgresql/tsearch_data/finnish.stop",start:4919288,end:4920867},{filename:"/tmp/pglite/share/postgresql/tsearch_data/french.stop",start:4920867,end:4921672},{filename:"/tmp/pglite/share/postgresql/tsearch_data/german.stop",start:4921672,end:4923021},{filename:"/tmp/pglite/share/postgresql/tsearch_data/hungarian.stop",start:4923021,end:4924248},{filename:"/tmp/pglite/share/postgresql/tsearch_data/hunspell_sample.affix",start:4924248,end:4924491},{filename:"/tmp/pglite/share/postgresql/tsearch_data/hunspell_sample_long.affix",start:4924491,end:4925124},{filename:"/tmp/pglite/share/postgresql/tsearch_data/hunspell_sample_long.dict",start:4925124,end:4925222},{filename:"/tmp/pglite/share/postgresql/tsearch_data/hunspell_sample_num.affix",start:4925222,end:4925684},{filename:"/tmp/pglite/share/postgresql/tsearch_data/hunspell_sample_num.dict",start:4925684,end:4925813},{filename:"/tmp/pglite/share/postgresql/tsearch_data/ispell_sample.affix",start:4925813,end:4926278},{filename:"/tmp/pglite/share/postgresql/tsearch_data/ispell_sample.dict",start:4926278,end:4926359},{filename:"/tmp/pglite/share/postgresql/tsearch_data/italian.stop",start:4926359,end:4928013},{filename:"/tmp/pglite/share/postgresql/tsearch_data/nepali.stop",start:4928013,end:4932274},{filename:"/tmp/pglite/share/postgresql/tsearch_data/norwegian.stop",start:4932274,end:4933125},{filename:"/tmp/pglite/share/postgresql/tsearch_data/portuguese.stop",start:4933125,end:4934392},{filename:"/tmp/pglite/share/postgresql/tsearch_data/russian.stop",start:4934392,end:4935627},{filename:"/tmp/pglite/share/postgresql/tsearch_data/spanish.stop",start:4935627,end:4937805},{filename:"/tmp/pglite/share/postgresql/tsearch_data/swedish.stop",start:4937805,end:4938364},{filename:"/tmp/pglite/share/postgresql/tsearch_data/synonym_sample.syn",start:4938364,end:4938437},{filename:"/tmp/pglite/share/postgresql/tsearch_data/thesaurus_sample.ths",start:4938437,end:4938910},{filename:"/tmp/pglite/share/postgresql/tsearch_data/turkish.stop",start:4938910,end:4939170}],remote_package_size:4939170})})();var moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(r,e)=>{throw e},scriptDirectory="";function locateFile(r){return Module.locateFile?Module.locateFile(r,scriptDirectory):scriptDirectory+r}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs"),nodePath=require("path");import.meta.url.startsWith("data:")||(scriptDirectory=nodePath.dirname(require("url").fileURLToPath(import.meta.url))+"/"),readBinary=r=>{r=isFileURI(r)?new URL(r):r;var e=fs.readFileSync(r);return e},readAsync=async(r,e=!0)=>{r=isFileURI(r)?new URL(r):r;var M=fs.readFileSync(r,e?void 0:"utf8");return M},!Module.thisProgram&&process$1.argv.length>1&&(thisProgram=process$1.argv[1].replace(/\\/g,"/")),arguments_=process$1.argv.slice(2),quit_=(r,e)=>{throw process$1.exitCode=r,e}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),_scriptName&&(scriptDirectory=_scriptName),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=r=>{var e=new XMLHttpRequest;return e.open("GET",r,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),readAsync=async r=>{var e=await fetch(r,{credentials:"same-origin"});if(e.ok)return e.arrayBuffer();throw new Error(e.status+" : "+e.url)});var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary=Module.wasmBinary,wasmMemory,ABORT=!1,EXITSTATUS;function assert(r,e){r||abort(e)}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPF64;function updateMemoryViews(){var r=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(r),Module.HEAP16=HEAP16=new Int16Array(r),Module.HEAPU8=HEAPU8=new Uint8Array(r),Module.HEAPU16=HEAPU16=new Uint16Array(r),Module.HEAP32=HEAP32=new Int32Array(r),Module.HEAPU32=HEAPU32=new Uint32Array(r),Module.HEAPF32=HEAPF32=new Float32Array(r),Module.HEAPF64=HEAPF64=new Float64Array(r),Module.HEAP64=HEAP64=new BigInt64Array(r),Module.HEAPU64=new BigUint64Array(r)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||16777216;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:32768})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),!Module.noFSInit&&!FS.initialized&&FS.init(),FS.ignorePermissions=!1,SOCKFS.root=FS.mount(SOCKFS,{},null),PIPEFS.root=FS.mount(PIPEFS,{},null),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(r){__ATPRERUN__.unshift(r)}function addOnInit(r){__ATINIT__.unshift(r)}function addOnPostRun(r){__ATPOSTRUN__.unshift(r)}var runDependencies=0,dependenciesFulfilled=null;function addRunDependency(r){runDependencies++,Module.monitorRunDependencies?.(runDependencies)}function removeRunDependency(r){if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&dependenciesFulfilled){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}function abort(r){Module.onAbort?.(r),r="Aborted("+r+")",err(r),ABORT=!0,r+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(r);throw readyPromiseReject(e),e}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=r=>r.startsWith(dataURIPrefix),isFileURI=r=>r.startsWith("file://");function findWasmBinary(){if(Module.locateFile){var r="pglite.wasm";return isDataURI(r)?r:locateFile(r)}return new URL("/assets/pglite-CeYkvzd0.wasm",import.meta.url).href}var wasmBinaryFile;function getBinarySync(r){if(r==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(r);throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(r){if(!wasmBinary)try{var e=await readAsync(r);return new Uint8Array(e)}catch{}return getBinarySync(r)}async function instantiateArrayBuffer(r,e){try{var M=await getWasmBinary(r),tr=await WebAssembly.instantiate(M,e);return tr}catch(rr){err(`failed to asynchronously prepare wasm: ${rr}`),abort(rr)}}async function instantiateAsync(r,e,M){if(!r&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(e)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function")try{var tr=fetch(e,{credentials:"same-origin"}),rr=await WebAssembly.instantiateStreaming(tr,M);return rr}catch(ir){err(`wasm streaming compile failed: ${ir}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(e,M)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}async function createWasm(){function r(rr,ir){wasmExports=rr.exports,wasmExports=relocateExports(wasmExports,1024);var lr=getDylinkMetadata(ir);return lr.neededDynlibs&&(dynamicLibraries=lr.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency(),wasmExports}addRunDependency();function e(rr){r(rr.instance,rr.module)}var M=getWasmImports();if(Module.instantiateWasm)try{return Module.instantiateWasm(M,r)}catch(rr){err(`Module.instantiateWasm callback failed with error: ${rr}`),readyPromiseReject(rr)}wasmBinaryFile??(wasmBinaryFile=findWasmBinary());try{var tr=await instantiateAsync(wasmBinary,wasmBinaryFile,M);return e(tr),tr}catch(rr){readyPromiseReject(rr);return}}var ASM_CONSTS={2537480:r=>{Module.is_worker=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Module.FD_BUFFER_MAX=r,Module.emscripten_copy_to=console.warn},2537652:()=>{Module.postMessage=function(r){console.log("# pg_main_emsdk.c:544: onCustomMessage:",r)}},2537781:()=>{if(Module.is_worker){let r=function(e){console.log("onCustomMessage:",e)};Module.onCustomMessage=r}else Module.postMessage=function(r){switch(r.type){case"raw":break;case"stdin":{stringToUTF8(r.data,1,Module.FD_BUFFER_MAX);break}case"rcon":break;default:console.warn("custom_postMessage?",r)}}}};class ExitStatus{constructor(e){P$1(this,"name","ExitStatus"),this.message=`Program terminated with exit(${e})`,this.status=e}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(r,e){var M=GOT[e];return M||(M=GOT[e]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(e)||(M.required=!0),M}},callRuntimeCallbacks=r=>{for(;r.length>0;)r.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(r,e=0,M=NaN)=>{for(var tr=e+M,rr=e;r[rr]&&!(rr>=tr);)++rr;if(rr-e>16&&r.buffer&&UTF8Decoder)return UTF8Decoder.decode(r.subarray(e,rr));for(var ir="";e<rr;){var lr=r[e++];if(!(lr&128)){ir+=String.fromCharCode(lr);continue}var dr=r[e++]&63;if((lr&224)==192){ir+=String.fromCharCode((lr&31)<<6|dr);continue}var hr=r[e++]&63;if((lr&240)==224?lr=(lr&15)<<12|dr<<6|hr:lr=(lr&7)<<18|dr<<12|hr<<6|r[e++]&63,lr<65536)ir+=String.fromCharCode(lr);else{var fr=lr-65536;ir+=String.fromCharCode(55296|fr>>10,56320|fr&1023)}}return ir},getDylinkMetadata=r=>{var e=0,M=0;function tr(){return r[e++]}function rr(){for(var Gr=0,Lr=1;;){var $r=r[e++];if(Gr+=($r&127)*Lr,Lr*=128,!($r&128))break}return Gr}function ir(){var Gr=rr();return e+=Gr,UTF8ArrayToString(r,e-Gr,Gr)}function lr(Gr,Lr){if(Gr)throw new Error(Lr)}var dr="dylink.0";if(r instanceof WebAssembly.Module){var hr=WebAssembly.Module.customSections(r,dr);hr.length===0&&(dr="dylink",hr=WebAssembly.Module.customSections(r,dr)),lr(hr.length===0,"need dylink section"),r=new Uint8Array(hr[0]),M=r.length}else{var fr=new Uint32Array(new Uint8Array(r.subarray(0,24)).buffer),mr=fr[0]==1836278016;lr(!mr,"need to see wasm magic number"),lr(r[8]!==0,"need the dylink section to be first"),e=9;var _r=rr();M=e+_r,dr=ir()}var gr={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(dr=="dylink"){gr.memorySize=rr(),gr.memoryAlign=rr(),gr.tableSize=rr(),gr.tableAlign=rr();for(var wr=rr(),yr=0;yr<wr;++yr){var br=ir();gr.neededDynlibs.push(br)}}else{lr(dr!=="dylink.0");for(var Mr=1,vr=2,Sr=3,xr=4,Ar=256,Dr=3,Ir=1;e<M;){var kr=tr(),Or=rr();if(kr===Mr)gr.memorySize=rr(),gr.memoryAlign=rr(),gr.tableSize=rr(),gr.tableAlign=rr();else if(kr===vr)for(var wr=rr(),yr=0;yr<wr;++yr)br=ir(),gr.neededDynlibs.push(br);else if(kr===Sr)for(var Fr=rr();Fr--;){var Jr=ir(),$n=rr();$n&Ar&&gr.tlsExports.add(Jr)}else if(kr===xr)for(var Fr=rr();Fr--;){ir();var Jr=ir(),$n=rr();($n&Dr)==Ir&&gr.weakImports.add(Jr)}else e+=Or}}return gr};function getValue(r,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":return HEAP8[r];case"i8":return HEAP8[r];case"i16":return HEAP16[r>>1];case"i32":return HEAP32[r>>2];case"i64":return HEAP64[r>>3];case"float":return HEAPF32[r>>2];case"double":return HEAPF64[r>>3];case"*":return HEAPU32[r>>2];default:abort(`invalid type for getValue: ${e}`)}}var newDSO=(r,e,M)=>{var tr={refcount:1/0,name:r,exports:M,global:!0};return LDSO.loadedLibsByName[r]=tr,e!=null&&(LDSO.loadedLibsByHandle[e]=tr),tr},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=2765600,alignMemory=(r,e)=>Math.ceil(r/e)*e,getMemory=r=>{if(runtimeInitialized)return _calloc(r,1);var e=___heap_base,M=e+alignMemory(r,16);return ___heap_base=M,GOT.__heap_base.value=M,e},isInternalSym=r=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(r)||r.startsWith("__em_js__"),uleb128Encode=(r,e)=>{r<128?e.push(r):e.push(r%128|128,r>>7)},sigToWasmTypes=r=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},M={parameters:[],results:r[0]=="v"?[]:[e[r[0]]]},tr=1;tr<r.length;++tr)M.parameters.push(e[r[tr]]);return M},generateFuncType=(r,e)=>{var M=r.slice(0,1),tr=r.slice(1),rr={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),uleb128Encode(tr.length,e);for(var ir=0;ir<tr.length;++ir)e.push(rr[tr[ir]]);M=="v"?e.push(0):e.push(1,rr[M])},convertJsFunctionToWasm=(r,e)=>{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(e),r);var M=[1];generateFuncType(e,M);var tr=[0,97,115,109,1,0,0,0,1];uleb128Encode(M.length,tr),tr.push(...M),tr.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var rr=new WebAssembly.Module(new Uint8Array(tr)),ir=new WebAssembly.Instance(rr,{e:{f:r}}),lr=ir.exports.f;return lr},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:5610,element:"anyfunc"}),getWasmTableEntry=r=>{var e=wasmTableMirror[r];return e||(r>=wasmTableMirror.length&&(wasmTableMirror.length=r+1),wasmTableMirror[r]=e=wasmTable.get(r)),e},updateTableMap=(r,e)=>{if(functionsInTableMap)for(var M=r;M<r+e;M++){var tr=getWasmTableEntry(M);tr&&functionsInTableMap.set(tr,M)}},functionsInTableMap,getFunctionAddress=r=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(r)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(r){throw r instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":r}return wasmTable.length-1},setWasmTableEntry=(r,e)=>{wasmTable.set(r,e),wasmTableMirror[r]=wasmTable.get(r)},addFunction=(r,e)=>{var M=getFunctionAddress(r);if(M)return M;var tr=getEmptyTableSlot();try{setWasmTableEntry(tr,r)}catch(ir){if(!(ir instanceof TypeError))throw ir;var rr=convertJsFunctionToWasm(r,e);setWasmTableEntry(tr,rr)}return functionsInTableMap.set(r,tr),tr},updateGOT=(r,e)=>{for(var M in r)if(!isInternalSym(M)){var tr=r[M];GOT[M]||(GOT[M]=new WebAssembly.Global({value:"i32",mutable:!0})),GOT[M].value==0&&(typeof tr=="function"?GOT[M].value=addFunction(tr):typeof tr=="number"?GOT[M].value=tr:err(`unhandled export type for '${M}': ${typeof tr}`))}},relocateExports=(r,e,M)=>{var tr={};for(var rr in r){var ir=r[rr];typeof ir=="object"&&(ir=ir.value),typeof ir=="number"&&(ir+=e),tr[rr]=ir}return updateGOT(tr),tr},isSymbolDefined=r=>{var e=wasmImports[r];return!(!e||e.stub)},dynCall=(r,e,M=[])=>{var tr=getWasmTableEntry(e)(...M);return tr},stackSave=()=>_emscripten_stack_get_current(),stackRestore=r=>__emscripten_stack_restore(r),createInvokeFunction=r=>(e,...M)=>{var tr=stackSave();try{return dynCall(r,e,M)}catch(rr){if(stackRestore(tr),rr!==rr+0)throw rr;if(_setThrew(1,0),r[0]=="j")return 0n}},resolveGlobalSymbol=(r,e=!1)=>{var M;return isSymbolDefined(r)?M=wasmImports[r]:r.startsWith("invoke_")&&(M=wasmImports[r]=createInvokeFunction(r.split("_")[1])),{sym:M,name:r}},UTF8ToString=(r,e)=>r?UTF8ArrayToString(HEAPU8,r,e):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,HEAPU32[handle+12>>2]=memoryBase,HEAP32[handle+16>>2]=metadata.memorySize,HEAPU32[handle+20>>2]=tableBase,HEAP32[handle+24>>2]=metadata.tableSize)}else memoryBase=HEAPU32[handle+12>>2],tableBase=HEAPU32[handle+20>>2];var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(r){var e=resolveGlobalSymbol(r).sym;return!e&&localScope&&(e=localScope[r]),e||(e=moduleExports[r]),e}var proxyHandler={get(r,e){switch(e){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(e in wasmImports&&!wasmImports[e].stub)return wasmImports[e];if(!(e in r)){var M;r[e]=(...tr)=>(M||(M=resolveSymbol(e)),M(...tr))}return r[e]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(r=>postInstantiation(r.module,r.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(r=>loadDynamicLibrary(r,flags,localScope)),loadModule())},mergeLibSymbols=(r,e)=>{for(var[M,tr]of Object.entries(r)){let rr=lr=>{isSymbolDefined(lr)||(wasmImports[lr]=tr)};rr(M);let ir="__main_argc_argv";M=="main"&&rr(ir),M==ir&&rr("main")}},asyncLoad=async r=>{var e=await readAsync(r);return new Uint8Array(e)},preloadPlugins=Module.preloadPlugins||[],registerWasmPlugin=()=>{var r={promiseChainEnd:Promise.resolve(),canHandle:e=>!Module.noWasmDecoding&&e.endsWith(".so"),handle:(e,M,tr,rr)=>{r.promiseChainEnd=r.promiseChainEnd.then(()=>loadWebAssemblyModule(e,{loadAsync:!0,nodelete:!0},M,{})).then(ir=>{preloadedWasm[M]=ir,tr(e)},ir=>{err(`failed to instantiate wasm: ${M}: ${ir}`),rr()})}};preloadPlugins.push(r)},preloadedWasm={};function loadDynamicLibrary(r,e={global:!0,nodelete:!0},M,tr){var rr=LDSO.loadedLibsByName[r];if(rr)return e.global?rr.global||(rr.global=!0,mergeLibSymbols(rr.exports)):M&&Object.assign(M,rr.exports),e.nodelete&&rr.refcount!==1/0&&(rr.refcount=1/0),rr.refcount++,tr&&(LDSO.loadedLibsByHandle[tr]=rr),e.loadAsync?Promise.resolve(!0):!0;rr=newDSO(r,tr,"loading"),rr.refcount=e.nodelete?1/0:1,rr.global=e.global;function ir(){if(tr){var hr=HEAPU32[tr+28>>2],fr=HEAPU32[tr+32>>2];if(hr&&fr){var mr=HEAP8.slice(hr,hr+fr);return e.loadAsync?Promise.resolve(mr):mr}}var _r=locateFile(r);if(e.loadAsync)return asyncLoad(_r);if(!readBinary)throw new Error(`${_r}: file not found, and synchronous loading of external files is not available`);return readBinary(_r)}function lr(){var hr=preloadedWasm[r];return hr?e.loadAsync?Promise.resolve(hr):hr:e.loadAsync?ir().then(fr=>loadWebAssemblyModule(fr,e,r,M,tr)):loadWebAssemblyModule(ir(),e,r,M,tr)}function dr(hr){rr.global?mergeLibSymbols(hr):M&&Object.assign(M,hr),rr.exports=hr}return e.loadAsync?lr().then(hr=>(dr(hr),!0)):(dr(lr()),!0)}var reportUndefinedSymbols=()=>{for(var[r,e]of Object.entries(GOT))if(e.value==0){var M=resolveGlobalSymbol(r,!0).sym;if(!M&&!e.required)continue;if(typeof M=="function")e.value=addFunction(M,M.sig);else if(typeof M=="number")e.value=M;else throw new Error(`bad export type for '${r}': ${typeof M}`)}},loadDylibs=()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency(),dynamicLibraries.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0})),Promise.resolve()).then(()=>{reportUndefinedSymbols(),removeRunDependency()})},noExitRuntime=Module.noExitRuntime||!0;function setValue(r,e,M="i8"){switch(M.endsWith("*")&&(M="*"),M){case"i1":HEAP8[r]=e;break;case"i8":HEAP8[r]=e;break;case"i16":HEAP16[r>>1]=e;break;case"i32":HEAP32[r>>2]=e;break;case"i64":HEAP64[r>>3]=BigInt(e);break;case"float":HEAPF32[r>>2]=e;break;case"double":HEAPF64[r>>3]=e;break;case"*":HEAPU32[r>>2]=e;break;default:abort(`invalid type for setValue: ${M}`)}}var ___assert_fail=(r,e,M,tr)=>abort(`Assertion failed: ${UTF8ToString(r)}, at: `+[e?UTF8ToString(e):"unknown filename",M,tr?UTF8ToString(tr):"unknown function"]);___assert_fail.sig="vppip";var ___call_sighandler=(r,e)=>getWasmTableEntry(r)(e);___call_sighandler.sig="vpi";var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024);Module.___memory_base=___memory_base;var ___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},2765600);Module.___stack_pointer=___stack_pointer;var PATH={isAbs:r=>r.charAt(0)==="/",splitPath:r=>{var e=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return e.exec(r).slice(1)},normalizeArray:(r,e)=>{for(var M=0,tr=r.length-1;tr>=0;tr--){var rr=r[tr];rr==="."?r.splice(tr,1):rr===".."?(r.splice(tr,1),M++):M&&(r.splice(tr,1),M--)}if(e)for(;M;M--)r.unshift("..");return r},normalize:r=>{var e=PATH.isAbs(r),M=r.substr(-1)==="/";return r=PATH.normalizeArray(r.split("/").filter(tr=>!!tr),!e).join("/"),!r&&!e&&(r="."),r&&M&&(r+="/"),(e?"/":"")+r},dirname:r=>{var e=PATH.splitPath(r),M=e[0],tr=e[1];return!M&&!tr?".":(tr&&(tr=tr.substr(0,tr.length-1)),M+tr)},basename:r=>{if(r==="/")return"/";r=PATH.normalize(r),r=r.replace(/\/$/,"");var e=r.lastIndexOf("/");return e===-1?r:r.substr(e+1)},join:(...r)=>PATH.normalize(r.join("/")),join2:(r,e)=>PATH.normalize(r+"/"+e)},initRandomFill=()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return tr=>crypto.getRandomValues(tr);if(ENVIRONMENT_IS_NODE)try{var r=require("crypto"),e=r.randomFillSync;if(e)return tr=>r.randomFillSync(tr);var M=r.randomBytes;return tr=>(tr.set(M(tr.byteLength)),tr)}catch{}abort("initRandomDevice")},randomFill=r=>(randomFill=initRandomFill())(r),PATH_FS={resolve:(...r)=>{for(var e="",M=!1,tr=r.length-1;tr>=-1&&!M;tr--){var rr=tr>=0?r[tr]:FS.cwd();if(typeof rr!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!rr)return"";e=rr+"/"+e,M=PATH.isAbs(rr)}return e=PATH.normalizeArray(e.split("/").filter(ir=>!!ir),!M).join("/"),(M?"/":"")+e||"."},relative:(r,e)=>{r=PATH_FS.resolve(r).substr(1),e=PATH_FS.resolve(e).substr(1);function M(fr){for(var mr=0;mr<fr.length&&fr[mr]==="";mr++);for(var _r=fr.length-1;_r>=0&&fr[_r]==="";_r--);return mr>_r?[]:fr.slice(mr,_r-mr+1)}for(var tr=M(r.split("/")),rr=M(e.split("/")),ir=Math.min(tr.length,rr.length),lr=ir,dr=0;dr<ir;dr++)if(tr[dr]!==rr[dr]){lr=dr;break}for(var hr=[],dr=lr;dr<tr.length;dr++)hr.push("..");return hr=hr.concat(rr.slice(lr)),hr.join("/")}},FS_stdin_getChar_buffer=[],lengthBytesUTF8=r=>{for(var e=0,M=0;M<r.length;++M){var tr=r.charCodeAt(M);tr<=127?e++:tr<=2047?e+=2:tr>=55296&&tr<=57343?(e+=4,++M):e+=3}return e},stringToUTF8Array=(r,e,M,tr)=>{if(!(tr>0))return 0;for(var rr=M,ir=M+tr-1,lr=0;lr<r.length;++lr){var dr=r.charCodeAt(lr);if(dr>=55296&&dr<=57343){var hr=r.charCodeAt(++lr);dr=65536+((dr&1023)<<10)|hr&1023}if(dr<=127){if(M>=ir)break;e[M++]=dr}else if(dr<=2047){if(M+1>=ir)break;e[M++]=192|dr>>6,e[M++]=128|dr&63}else if(dr<=65535){if(M+2>=ir)break;e[M++]=224|dr>>12,e[M++]=128|dr>>6&63,e[M++]=128|dr&63}else{if(M+3>=ir)break;e[M++]=240|dr>>18,e[M++]=128|dr>>12&63,e[M++]=128|dr>>6&63,e[M++]=128|dr&63}}return e[M]=0,M-rr};function intArrayFromString(r,e,M){var tr=lengthBytesUTF8(r)+1,rr=new Array(tr),ir=stringToUTF8Array(r,rr,0,rr.length);return rr.length=ir,rr}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var r=null;if(ENVIRONMENT_IS_NODE){var e=256,M=Buffer.alloc(e),tr=0,rr=process$1.stdin.fd;try{tr=fs.readSync(rr,M,0,e)}catch(ir){if(ir.toString().includes("EOF"))tr=0;else throw ir}tr>0&&(r=M.slice(0,tr).toString("utf-8"))}else typeof window<"u"&&typeof window.prompt=="function"&&(r=window.prompt("Input: "),r!==null&&(r+=`
10
+ `));if(!r)return null;FS_stdin_getChar_buffer=intArrayFromString(r)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(r,e){TTY.ttys[r]={input:[],output:[],ops:e},FS.registerDevice(r,TTY.stream_ops)},stream_ops:{open(r){var e=TTY.ttys[r.node.rdev];if(!e)throw new FS.ErrnoError(43);r.tty=e,r.seekable=!1},close(r){r.tty.ops.fsync(r.tty)},fsync(r){r.tty.ops.fsync(r.tty)},read(r,e,M,tr,rr){if(!r.tty||!r.tty.ops.get_char)throw new FS.ErrnoError(60);for(var ir=0,lr=0;lr<tr;lr++){var dr;try{dr=r.tty.ops.get_char(r.tty)}catch{throw new FS.ErrnoError(29)}if(dr===void 0&&ir===0)throw new FS.ErrnoError(6);if(dr==null)break;ir++,e[M+lr]=dr}return ir&&(r.node.atime=Date.now()),ir},write(r,e,M,tr,rr){if(!r.tty||!r.tty.ops.put_char)throw new FS.ErrnoError(60);try{for(var ir=0;ir<tr;ir++)r.tty.ops.put_char(r.tty,e[M+ir])}catch{throw new FS.ErrnoError(29)}return tr&&(r.node.mtime=r.node.ctime=Date.now()),ir}},default_tty_ops:{get_char(r){return FS_stdin_getChar()},put_char(r,e){e===null||e===10?(out(UTF8ArrayToString(r.output)),r.output=[]):e!=0&&r.output.push(e)},fsync(r){r.output&&r.output.length>0&&(out(UTF8ArrayToString(r.output)),r.output=[])},ioctl_tcgets(r){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(r,e,M){return 0},ioctl_tiocgwinsz(r){return[24,80]}},default_tty1_ops:{put_char(r,e){e===null||e===10?(err(UTF8ArrayToString(r.output)),r.output=[]):e!=0&&r.output.push(e)},fsync(r){r.output&&r.output.length>0&&(err(UTF8ArrayToString(r.output)),r.output=[])}}},zeroMemory=(r,e)=>{HEAPU8.fill(0,r,r+e)},mmapAlloc=r=>{r=alignMemory(r,65536);var e=_emscripten_builtin_memalign(65536,r);return e&&zeroMemory(e,r),e},MEMFS={ops_table:null,mount(r){return MEMFS.createNode(null,"/",16895,0)},createNode(r,e,M,tr){if(FS.isBlkdev(M)||FS.isFIFO(M))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var rr=FS.createNode(r,e,M,tr);return FS.isDir(rr.mode)?(rr.node_ops=MEMFS.ops_table.dir.node,rr.stream_ops=MEMFS.ops_table.dir.stream,rr.contents={}):FS.isFile(rr.mode)?(rr.node_ops=MEMFS.ops_table.file.node,rr.stream_ops=MEMFS.ops_table.file.stream,rr.usedBytes=0,rr.contents=null):FS.isLink(rr.mode)?(rr.node_ops=MEMFS.ops_table.link.node,rr.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(rr.mode)&&(rr.node_ops=MEMFS.ops_table.chrdev.node,rr.stream_ops=MEMFS.ops_table.chrdev.stream),rr.atime=rr.mtime=rr.ctime=Date.now(),r&&(r.contents[e]=rr,r.atime=r.mtime=r.ctime=rr.atime),rr},getFileDataAsTypedArray(r){return r.contents?r.contents.subarray?r.contents.subarray(0,r.usedBytes):new Uint8Array(r.contents):new Uint8Array(0)},expandFileStorage(r,e){var M=r.contents?r.contents.length:0;if(!(M>=e)){var tr=1048576;e=Math.max(e,M*(M<tr?2:1.125)>>>0),M!=0&&(e=Math.max(e,256));var rr=r.contents;r.contents=new Uint8Array(e),r.usedBytes>0&&r.contents.set(rr.subarray(0,r.usedBytes),0)}},resizeFileStorage(r,e){if(r.usedBytes!=e)if(e==0)r.contents=null,r.usedBytes=0;else{var M=r.contents;r.contents=new Uint8Array(e),M&&r.contents.set(M.subarray(0,Math.min(e,r.usedBytes))),r.usedBytes=e}},node_ops:{getattr(r){var e={};return e.dev=FS.isChrdev(r.mode)?r.id:1,e.ino=r.id,e.mode=r.mode,e.nlink=1,e.uid=0,e.gid=0,e.rdev=r.rdev,FS.isDir(r.mode)?e.size=4096:FS.isFile(r.mode)?e.size=r.usedBytes:FS.isLink(r.mode)?e.size=r.link.length:e.size=0,e.atime=new Date(r.atime),e.mtime=new Date(r.mtime),e.ctime=new Date(r.ctime),e.blksize=4096,e.blocks=Math.ceil(e.size/e.blksize),e},setattr(r,e){for(let M of["mode","atime","mtime","ctime"])e[M]&&(r[M]=e[M]);e.size!==void 0&&MEMFS.resizeFileStorage(r,e.size)},lookup(r,e){throw MEMFS.doesNotExistError},mknod(r,e,M,tr){return MEMFS.createNode(r,e,M,tr)},rename(r,e,M){var tr;try{tr=FS.lookupNode(e,M)}catch{}if(tr){if(FS.isDir(r.mode))for(var rr in tr.contents)throw new FS.ErrnoError(55);FS.hashRemoveNode(tr)}delete r.parent.contents[r.name],e.contents[M]=r,r.name=M,e.ctime=e.mtime=r.parent.ctime=r.parent.mtime=Date.now()},unlink(r,e){delete r.contents[e],r.ctime=r.mtime=Date.now()},rmdir(r,e){var M=FS.lookupNode(r,e);for(var tr in M.contents)throw new FS.ErrnoError(55);delete r.contents[e],r.ctime=r.mtime=Date.now()},readdir(r){return[".","..",...Object.keys(r.contents)]},symlink(r,e,M){var tr=MEMFS.createNode(r,e,41471,0);return tr.link=M,tr},readlink(r){if(!FS.isLink(r.mode))throw new FS.ErrnoError(28);return r.link}},stream_ops:{read(r,e,M,tr,rr){var ir=r.node.contents;if(rr>=r.node.usedBytes)return 0;var lr=Math.min(r.node.usedBytes-rr,tr);if(lr>8&&ir.subarray)e.set(ir.subarray(rr,rr+lr),M);else for(var dr=0;dr<lr;dr++)e[M+dr]=ir[rr+dr];return lr},write(r,e,M,tr,rr,ir){if(e.buffer===HEAP8.buffer&&(ir=!1),!tr)return 0;var lr=r.node;if(lr.mtime=lr.ctime=Date.now(),e.subarray&&(!lr.contents||lr.contents.subarray)){if(ir)return lr.contents=e.subarray(M,M+tr),lr.usedBytes=tr,tr;if(lr.usedBytes===0&&rr===0)return lr.contents=e.slice(M,M+tr),lr.usedBytes=tr,tr;if(rr+tr<=lr.usedBytes)return lr.contents.set(e.subarray(M,M+tr),rr),tr}if(MEMFS.expandFileStorage(lr,rr+tr),lr.contents.subarray&&e.subarray)lr.contents.set(e.subarray(M,M+tr),rr);else for(var dr=0;dr<tr;dr++)lr.contents[rr+dr]=e[M+dr];return lr.usedBytes=Math.max(lr.usedBytes,rr+tr),tr},llseek(r,e,M){var tr=e;if(M===1?tr+=r.position:M===2&&FS.isFile(r.node.mode)&&(tr+=r.node.usedBytes),tr<0)throw new FS.ErrnoError(28);return tr},allocate(r,e,M){MEMFS.expandFileStorage(r.node,e+M),r.node.usedBytes=Math.max(r.node.usedBytes,e+M)},mmap(r,e,M,tr,rr){if(!FS.isFile(r.node.mode))throw new FS.ErrnoError(43);var ir,lr,dr=r.node.contents;if(!(rr&2)&&dr&&dr.buffer===HEAP8.buffer)lr=!1,ir=dr.byteOffset;else{if(lr=!0,ir=mmapAlloc(e),!ir)throw new FS.ErrnoError(48);dr&&((M>0||M+e<dr.length)&&(dr.subarray?dr=dr.subarray(M,M+e):dr=Array.prototype.slice.call(dr,M,M+e)),HEAP8.set(dr,ir))}return{ptr:ir,allocated:lr}},msync(r,e,M,tr,rr){return MEMFS.stream_ops.write(r,e,0,tr,M,!1),0}}},FS_createDataFile=(r,e,M,tr,rr,ir)=>{FS.createDataFile(r,e,M,tr,rr,ir)},FS_handledByPreloadPlugin=(r,e,M,tr)=>{typeof Browser<"u"&&Browser.init();var rr=!1;return preloadPlugins.forEach(ir=>{rr||ir.canHandle(e)&&(ir.handle(r,e,M,tr),rr=!0)}),rr},FS_createPreloadedFile=(r,e,M,tr,rr,ir,lr,dr,hr,fr)=>{var mr=e?PATH_FS.resolve(PATH.join2(r,e)):r;function _r(gr){function wr(yr){fr?.(),dr||FS_createDataFile(r,e,yr,tr,rr,hr),ir?.(),removeRunDependency()}FS_handledByPreloadPlugin(gr,mr,wr,()=>{lr?.(),removeRunDependency()})||wr(gr)}addRunDependency(),typeof M=="string"?asyncLoad(M).then(_r,lr):_r(M)},FS_modeStringToFlags=r=>{var e={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},M=e[r];if(typeof M>"u")throw new Error(`Unknown file open mode: ${r}`);return M},FS_getMode=(r,e)=>{var M=0;return r&&(M|=365),e&&(M|=146),M},IDBFS={dbs:{},indexedDB:()=>{if(typeof indexedDB<"u")return indexedDB;var r=null;return typeof window=="object"&&(r=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB),r},DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",queuePersist:r=>{function e(){r.idbPersistState==="again"?M():r.idbPersistState=0}function M(){r.idbPersistState="idb",IDBFS.syncfs(r,!1,e)}r.idbPersistState?r.idbPersistState==="idb"&&(r.idbPersistState="again"):r.idbPersistState=setTimeout(M,0)},mount:r=>{var e=MEMFS.mount(r);if(r?.opts?.autoPersist){e.idbPersistState=0;var M=e.node_ops;e.node_ops=Object.assign({},e.node_ops),e.node_ops.mknod=(tr,rr,ir,lr)=>{var dr=M.mknod(tr,rr,ir,lr);return dr.node_ops=e.node_ops,dr.idbfs_mount=e.mount,dr.memfs_stream_ops=dr.stream_ops,dr.stream_ops=Object.assign({},dr.stream_ops),dr.stream_ops.write=(hr,fr,mr,_r,gr,wr)=>(hr.node.isModified=!0,dr.memfs_stream_ops.write(hr,fr,mr,_r,gr,wr)),dr.stream_ops.close=hr=>{var fr=hr.node;if(fr.isModified&&(IDBFS.queuePersist(fr.idbfs_mount),fr.isModified=!1),fr.memfs_stream_ops.close)return fr.memfs_stream_ops.close(hr)},dr},e.node_ops.mkdir=(...tr)=>(IDBFS.queuePersist(e.mount),M.mkdir(...tr)),e.node_ops.rmdir=(...tr)=>(IDBFS.queuePersist(e.mount),M.rmdir(...tr)),e.node_ops.symlink=(...tr)=>(IDBFS.queuePersist(e.mount),M.symlink(...tr)),e.node_ops.unlink=(...tr)=>(IDBFS.queuePersist(e.mount),M.unlink(...tr)),e.node_ops.rename=(...tr)=>(IDBFS.queuePersist(e.mount),M.rename(...tr))}return e},syncfs:(r,e,M)=>{IDBFS.getLocalSet(r,(tr,rr)=>{if(tr)return M(tr);IDBFS.getRemoteSet(r,(ir,lr)=>{if(ir)return M(ir);var dr=e?lr:rr,hr=e?rr:lr;IDBFS.reconcile(dr,hr,M)})})},quit:()=>{Object.values(IDBFS.dbs).forEach(r=>r.close()),IDBFS.dbs={}},getDB:(r,e)=>{var M=IDBFS.dbs[r];if(M)return e(null,M);var tr;try{tr=IDBFS.indexedDB().open(r,IDBFS.DB_VERSION)}catch(rr){return e(rr)}if(!tr)return e("Unable to connect to IndexedDB");tr.onupgradeneeded=rr=>{var ir=rr.target.result,lr=rr.target.transaction,dr;ir.objectStoreNames.contains(IDBFS.DB_STORE_NAME)?dr=lr.objectStore(IDBFS.DB_STORE_NAME):dr=ir.createObjectStore(IDBFS.DB_STORE_NAME),dr.indexNames.contains("timestamp")||dr.createIndex("timestamp","timestamp",{unique:!1})},tr.onsuccess=()=>{M=tr.result,IDBFS.dbs[r]=M,e(null,M)},tr.onerror=rr=>{e(rr.target.error),rr.preventDefault()}},getLocalSet:(r,e)=>{var M={};function tr(hr){return hr!=="."&&hr!==".."}function rr(hr){return fr=>PATH.join2(hr,fr)}for(var ir=FS.readdir(r.mountpoint).filter(tr).map(rr(r.mountpoint));ir.length;){var lr=ir.pop(),dr;try{dr=FS.stat(lr)}catch(hr){return e(hr)}FS.isDir(dr.mode)&&ir.push(...FS.readdir(lr).filter(tr).map(rr(lr))),M[lr]={timestamp:dr.mtime}}return e(null,{type:"local",entries:M})},getRemoteSet:(r,e)=>{var M={};IDBFS.getDB(r.mountpoint,(tr,rr)=>{if(tr)return e(tr);try{var ir=rr.transaction([IDBFS.DB_STORE_NAME],"readonly");ir.onerror=hr=>{e(hr.target.error),hr.preventDefault()};var lr=ir.objectStore(IDBFS.DB_STORE_NAME),dr=lr.index("timestamp");dr.openKeyCursor().onsuccess=hr=>{var fr=hr.target.result;if(!fr)return e(null,{type:"remote",db:rr,entries:M});M[fr.primaryKey]={timestamp:fr.key},fr.continue()}}catch(hr){return e(hr)}})},loadLocalEntry:(r,e)=>{var M,tr;try{var rr=FS.lookupPath(r);tr=rr.node,M=FS.stat(r)}catch(ir){return e(ir)}return FS.isDir(M.mode)?e(null,{timestamp:M.mtime,mode:M.mode}):FS.isFile(M.mode)?(tr.contents=MEMFS.getFileDataAsTypedArray(tr),e(null,{timestamp:M.mtime,mode:M.mode,contents:tr.contents})):e(new Error("node type not supported"))},storeLocalEntry:(r,e,M)=>{try{if(FS.isDir(e.mode))FS.mkdirTree(r,e.mode);else if(FS.isFile(e.mode))FS.writeFile(r,e.contents,{canOwn:!0});else return M(new Error("node type not supported"));FS.chmod(r,e.mode),FS.utime(r,e.timestamp,e.timestamp)}catch(tr){return M(tr)}M(null)},removeLocalEntry:(r,e)=>{try{var M=FS.stat(r);FS.isDir(M.mode)?FS.rmdir(r):FS.isFile(M.mode)&&FS.unlink(r)}catch(tr){return e(tr)}e(null)},loadRemoteEntry:(r,e,M)=>{var tr=r.get(e);tr.onsuccess=rr=>M(null,rr.target.result),tr.onerror=rr=>{M(rr.target.error),rr.preventDefault()}},storeRemoteEntry:(r,e,M,tr)=>{try{var rr=r.put(M,e)}catch(ir){tr(ir);return}rr.onsuccess=ir=>tr(),rr.onerror=ir=>{tr(ir.target.error),ir.preventDefault()}},removeRemoteEntry:(r,e,M)=>{var tr=r.delete(e);tr.onsuccess=rr=>M(),tr.onerror=rr=>{M(rr.target.error),rr.preventDefault()}},reconcile:(r,e,M)=>{var tr=0,rr=[];Object.keys(r.entries).forEach(_r=>{var gr=r.entries[_r],wr=e.entries[_r];(!wr||gr.timestamp.getTime()!=wr.timestamp.getTime())&&(rr.push(_r),tr++)});var ir=[];if(Object.keys(e.entries).forEach(_r=>{r.entries[_r]||(ir.push(_r),tr++)}),!tr)return M(null);var lr=!1,dr=r.type==="remote"?r.db:e.db,hr=dr.transaction([IDBFS.DB_STORE_NAME],"readwrite"),fr=hr.objectStore(IDBFS.DB_STORE_NAME);function mr(_r){if(_r&&!lr)return lr=!0,M(_r)}hr.onerror=hr.onabort=_r=>{mr(_r.target.error),_r.preventDefault()},hr.oncomplete=_r=>{lr||M(null)},rr.sort().forEach(_r=>{e.type==="local"?IDBFS.loadRemoteEntry(fr,_r,(gr,wr)=>{if(gr)return mr(gr);IDBFS.storeLocalEntry(_r,wr,mr)}):IDBFS.loadLocalEntry(_r,(gr,wr)=>{if(gr)return mr(gr);IDBFS.storeRemoteEntry(fr,_r,wr,mr)})}),ir.sort().reverse().forEach(_r=>{e.type==="local"?IDBFS.removeLocalEntry(_r,mr):IDBFS.removeRemoteEntry(fr,_r,mr)})}},ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},NODEFS={isWindows:!1,staticInit(){NODEFS.isWindows=!!process$1.platform.match(/^win/);var r=process$1.binding("constants");r.fs&&(r=r.fs),NODEFS.flagsForNodeMap={1024:r.O_APPEND,64:r.O_CREAT,128:r.O_EXCL,256:r.O_NOCTTY,0:r.O_RDONLY,2:r.O_RDWR,4096:r.O_SYNC,512:r.O_TRUNC,1:r.O_WRONLY,131072:r.O_NOFOLLOW}},convertNodeCode(r){var e=r.code;return ERRNO_CODES[e]},tryFSOperation(r){try{return r()}catch(e){throw e.code?e.code==="UNKNOWN"?new FS.ErrnoError(28):new FS.ErrnoError(NODEFS.convertNodeCode(e)):e}},mount(r){return NODEFS.createNode(null,"/",NODEFS.getMode(r.opts.root),0)},createNode(r,e,M,tr){if(!FS.isDir(M)&&!FS.isFile(M)&&!FS.isLink(M))throw new FS.ErrnoError(28);var rr=FS.createNode(r,e,M);return rr.node_ops=NODEFS.node_ops,rr.stream_ops=NODEFS.stream_ops,rr},getMode(r){return NODEFS.tryFSOperation(()=>{var e=fs.lstatSync(r).mode;return NODEFS.isWindows&&(e|=(e&292)>>2),e})},realPath(r){for(var e=[];r.parent!==r;)e.push(r.name),r=r.parent;return e.push(r.mount.opts.root),e.reverse(),PATH.join(...e)},flagsForNode(r){r&=-2097153,r&=-2049,r&=-32769,r&=-524289,r&=-65537;var e=0;for(var M in NODEFS.flagsForNodeMap)r&M&&(e|=NODEFS.flagsForNodeMap[M],r^=M);if(r)throw new FS.ErrnoError(28);return e},node_ops:{getattr(r){var e=NODEFS.realPath(r),M;return NODEFS.tryFSOperation(()=>M=fs.lstatSync(e)),NODEFS.isWindows&&(M.blksize||(M.blksize=4096),M.blocks||(M.blocks=(M.size+M.blksize-1)/M.blksize|0),M.mode|=(M.mode&292)>>2),{dev:M.dev,ino:M.ino,mode:M.mode,nlink:M.nlink,uid:M.uid,gid:M.gid,rdev:M.rdev,size:M.size,atime:M.atime,mtime:M.mtime,ctime:M.ctime,blksize:M.blksize,blocks:M.blocks}},setattr(r,e){var M=NODEFS.realPath(r);NODEFS.tryFSOperation(()=>{if(e.mode!==void 0){var tr=e.mode;NODEFS.isWindows&&(tr&=384),fs.chmodSync(M,tr),r.mode=e.mode}if(e.atime||e.mtime){var rr=e.atime&&new Date(e.atime),ir=e.mtime&&new Date(e.mtime);fs.utimesSync(M,rr,ir)}e.size!==void 0&&fs.truncateSync(M,e.size)})},lookup(r,e){var M=PATH.join2(NODEFS.realPath(r),e),tr=NODEFS.getMode(M);return NODEFS.createNode(r,e,tr)},mknod(r,e,M,tr){var rr=NODEFS.createNode(r,e,M,tr),ir=NODEFS.realPath(rr);return NODEFS.tryFSOperation(()=>{FS.isDir(rr.mode)?fs.mkdirSync(ir,rr.mode):fs.writeFileSync(ir,"",{mode:rr.mode})}),rr},rename(r,e,M){var tr=NODEFS.realPath(r),rr=PATH.join2(NODEFS.realPath(e),M);try{FS.unlink(rr)}catch{}NODEFS.tryFSOperation(()=>fs.renameSync(tr,rr)),r.name=M},unlink(r,e){var M=PATH.join2(NODEFS.realPath(r),e);NODEFS.tryFSOperation(()=>fs.unlinkSync(M))},rmdir(r,e){var M=PATH.join2(NODEFS.realPath(r),e);NODEFS.tryFSOperation(()=>fs.rmdirSync(M))},readdir(r){var e=NODEFS.realPath(r);return NODEFS.tryFSOperation(()=>fs.readdirSync(e))},symlink(r,e,M){var tr=PATH.join2(NODEFS.realPath(r),e);NODEFS.tryFSOperation(()=>fs.symlinkSync(M,tr))},readlink(r){var e=NODEFS.realPath(r);return NODEFS.tryFSOperation(()=>fs.readlinkSync(e))},statfs(r){var e=NODEFS.tryFSOperation(()=>fs.statfsSync(r));return e.frsize=e.bsize,e}},stream_ops:{open(r){var e=NODEFS.realPath(r.node);NODEFS.tryFSOperation(()=>{FS.isFile(r.node.mode)&&(r.shared.refcount=1,r.nfd=fs.openSync(e,NODEFS.flagsForNode(r.flags)))})},close(r){NODEFS.tryFSOperation(()=>{FS.isFile(r.node.mode)&&r.nfd&&--r.shared.refcount===0&&fs.closeSync(r.nfd)})},dup(r){r.shared.refcount++},read(r,e,M,tr,rr){return tr===0?0:NODEFS.tryFSOperation(()=>fs.readSync(r.nfd,new Int8Array(e.buffer,M,tr),0,tr,rr))},write(r,e,M,tr,rr){return NODEFS.tryFSOperation(()=>fs.writeSync(r.nfd,new Int8Array(e.buffer,M,tr),0,tr,rr))},llseek(r,e,M){var tr=e;if(M===1?tr+=r.position:M===2&&FS.isFile(r.node.mode)&&NODEFS.tryFSOperation(()=>{var rr=fs.fstatSync(r.nfd);tr+=rr.size}),tr<0)throw new FS.ErrnoError(28);return tr},mmap(r,e,M,tr,rr){if(!FS.isFile(r.node.mode))throw new FS.ErrnoError(43);var ir=mmapAlloc(e);return NODEFS.stream_ops.read(r,HEAP8,ir,e,M),{ptr:ir,allocated:!0}},msync(r,e,M,tr,rr){return NODEFS.stream_ops.write(r,e,0,tr,M,!1),0}}},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:class{constructor(r){P$1(this,"name","ErrnoError"),this.errno=r}},filesystems:null,syncFSRequests:0,readFiles:{},FSStream:class{constructor(){P$1(this,"shared",{})}get object(){return this.node}set object(r){this.node=r}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(r){this.shared.flags=r}get position(){return this.shared.position}set position(r){this.shared.position=r}},FSNode:class{constructor(r,e,M,tr){P$1(this,"node_ops",{}),P$1(this,"stream_ops",{}),P$1(this,"readMode",365),P$1(this,"writeMode",146),P$1(this,"mounted",null),r||(r=this),this.parent=r,this.mount=r.mount,this.id=FS.nextInode++,this.name=e,this.mode=M,this.rdev=tr,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(r){r?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(r){r?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(r,e={}){if(!r)return{path:"",node:null};e.follow_mount??(e.follow_mount=!0),PATH.isAbs(r)||(r=FS.cwd()+"/"+r);e:for(var M=0;M<40;M++){for(var tr=r.split("/").filter(fr=>!!fr&&fr!=="."),rr=FS.root,ir="/",lr=0;lr<tr.length;lr++){var dr=lr===tr.length-1;if(dr&&e.parent)break;if(tr[lr]===".."){ir=PATH.dirname(ir),rr=rr.parent;continue}ir=PATH.join2(ir,tr[lr]);try{rr=FS.lookupNode(rr,tr[lr])}catch(fr){if(fr?.errno===44&&dr&&e.noent_okay)return{path:ir};throw fr}if(FS.isMountpoint(rr)&&(!dr||e.follow_mount)&&(rr=rr.mounted.root),FS.isLink(rr.mode)&&(!dr||e.follow)){if(!rr.node_ops.readlink)throw new FS.ErrnoError(52);var hr=rr.node_ops.readlink(rr);PATH.isAbs(hr)||(hr=PATH.dirname(ir)+"/"+hr),r=hr+"/"+tr.slice(lr+1).join("/");continue e}}return{path:ir,node:rr}}throw new FS.ErrnoError(32)},getPath(r){for(var e;;){if(FS.isRoot(r)){var M=r.mount.mountpoint;return e?M[M.length-1]!=="/"?`${M}/${e}`:M+e:M}e=e?`${r.name}/${e}`:r.name,r=r.parent}},hashName(r,e){for(var M=0,tr=0;tr<e.length;tr++)M=(M<<5)-M+e.charCodeAt(tr)|0;return(r+M>>>0)%FS.nameTable.length},hashAddNode(r){var e=FS.hashName(r.parent.id,r.name);r.name_next=FS.nameTable[e],FS.nameTable[e]=r},hashRemoveNode(r){var e=FS.hashName(r.parent.id,r.name);if(FS.nameTable[e]===r)FS.nameTable[e]=r.name_next;else for(var M=FS.nameTable[e];M;){if(M.name_next===r){M.name_next=r.name_next;break}M=M.name_next}},lookupNode(r,e){var M=FS.mayLookup(r);if(M)throw new FS.ErrnoError(M);for(var tr=FS.hashName(r.id,e),rr=FS.nameTable[tr];rr;rr=rr.name_next){var ir=rr.name;if(rr.parent.id===r.id&&ir===e)return rr}return FS.lookup(r,e)},createNode(r,e,M,tr){var rr=new FS.FSNode(r,e,M,tr);return FS.hashAddNode(rr),rr},destroyNode(r){FS.hashRemoveNode(r)},isRoot(r){return r===r.parent},isMountpoint(r){return!!r.mounted},isFile(r){return(r&61440)===32768},isDir(r){return(r&61440)===16384},isLink(r){return(r&61440)===40960},isChrdev(r){return(r&61440)===8192},isBlkdev(r){return(r&61440)===24576},isFIFO(r){return(r&61440)===4096},isSocket(r){return(r&49152)===49152},flagsToPermissionString(r){var e=["r","w","rw"][r&3];return r&512&&(e+="w"),e},nodePermissions(r,e){return FS.ignorePermissions?0:e.includes("r")&&!(r.mode&292)||e.includes("w")&&!(r.mode&146)||e.includes("x")&&!(r.mode&73)?2:0},mayLookup(r){if(!FS.isDir(r.mode))return 54;var e=FS.nodePermissions(r,"x");return e||(r.node_ops.lookup?0:2)},mayCreate(r,e){if(!FS.isDir(r.mode))return 54;try{var M=FS.lookupNode(r,e);return 20}catch{}return FS.nodePermissions(r,"wx")},mayDelete(r,e,M){var tr;try{tr=FS.lookupNode(r,e)}catch(ir){return ir.errno}var rr=FS.nodePermissions(r,"wx");if(rr)return rr;if(M){if(!FS.isDir(tr.mode))return 54;if(FS.isRoot(tr)||FS.getPath(tr)===FS.cwd())return 10}else if(FS.isDir(tr.mode))return 31;return 0},mayOpen(r,e){return r?FS.isLink(r.mode)?32:FS.isDir(r.mode)&&(FS.flagsToPermissionString(e)!=="r"||e&512)?31:FS.nodePermissions(r,FS.flagsToPermissionString(e)):44},MAX_OPEN_FDS:4096,nextfd(){for(var r=0;r<=FS.MAX_OPEN_FDS;r++)if(!FS.streams[r])return r;throw new FS.ErrnoError(33)},getStreamChecked(r){var e=FS.getStream(r);if(!e)throw new FS.ErrnoError(8);return e},getStream:r=>FS.streams[r],createStream(r,e=-1){return r=Object.assign(new FS.FSStream,r),e==-1&&(e=FS.nextfd()),r.fd=e,FS.streams[e]=r,r},closeStream(r){FS.streams[r]=null},dupStream(r,e=-1){var M=FS.createStream(r,e);return M.stream_ops?.dup?.(M),M},chrdev_stream_ops:{open(r){var e=FS.getDevice(r.node.rdev);r.stream_ops=e.stream_ops,r.stream_ops.open?.(r)},llseek(){throw new FS.ErrnoError(70)}},major:r=>r>>8,minor:r=>r&255,makedev:(r,e)=>r<<8|e,registerDevice(r,e){FS.devices[r]={stream_ops:e}},getDevice:r=>FS.devices[r],getMounts(r){for(var e=[],M=[r];M.length;){var tr=M.pop();e.push(tr),M.push(...tr.mounts)}return e},syncfs(r,e){typeof r=="function"&&(e=r,r=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var M=FS.getMounts(FS.root.mount),tr=0;function rr(lr){return FS.syncFSRequests--,e(lr)}function ir(lr){if(lr)return ir.errored?void 0:(ir.errored=!0,rr(lr));++tr>=M.length&&rr(null)}M.forEach(lr=>{if(!lr.type.syncfs)return ir(null);lr.type.syncfs(lr,r,ir)})},mount(r,e,M){var tr=M==="/",rr=!M,ir;if(tr&&FS.root)throw new FS.ErrnoError(10);if(!tr&&!rr){var lr=FS.lookupPath(M,{follow_mount:!1});if(M=lr.path,ir=lr.node,FS.isMountpoint(ir))throw new FS.ErrnoError(10);if(!FS.isDir(ir.mode))throw new FS.ErrnoError(54)}var dr={type:r,opts:e,mountpoint:M,mounts:[]},hr=r.mount(dr);return hr.mount=dr,dr.root=hr,tr?FS.root=hr:ir&&(ir.mounted=dr,ir.mount&&ir.mount.mounts.push(dr)),hr},unmount(r){var e=FS.lookupPath(r,{follow_mount:!1});if(!FS.isMountpoint(e.node))throw new FS.ErrnoError(28);var M=e.node,tr=M.mounted,rr=FS.getMounts(tr);Object.keys(FS.nameTable).forEach(lr=>{for(var dr=FS.nameTable[lr];dr;){var hr=dr.name_next;rr.includes(dr.mount)&&FS.destroyNode(dr),dr=hr}}),M.mounted=null;var ir=M.mount.mounts.indexOf(tr);M.mount.mounts.splice(ir,1)},lookup(r,e){return r.node_ops.lookup(r,e)},mknod(r,e,M){var tr=FS.lookupPath(r,{parent:!0}),rr=tr.node,ir=PATH.basename(r);if(!ir||ir==="."||ir==="..")throw new FS.ErrnoError(28);var lr=FS.mayCreate(rr,ir);if(lr)throw new FS.ErrnoError(lr);if(!rr.node_ops.mknod)throw new FS.ErrnoError(63);return rr.node_ops.mknod(rr,ir,e,M)},statfs(r){var e={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255},M=FS.lookupPath(r,{follow:!0}).node;return M?.node_ops.statfs&&Object.assign(e,M.node_ops.statfs(M.mount.opts.root)),e},create(r,e=438){return e&=4095,e|=32768,FS.mknod(r,e,0)},mkdir(r,e=511){return e&=1023,e|=16384,FS.mknod(r,e,0)},mkdirTree(r,e){for(var M=r.split("/"),tr="",rr=0;rr<M.length;++rr)if(M[rr]){tr+="/"+M[rr];try{FS.mkdir(tr,e)}catch(ir){if(ir.errno!=20)throw ir}}},mkdev(r,e,M){return typeof M>"u"&&(M=e,e=438),e|=8192,FS.mknod(r,e,M)},symlink(r,e){if(!PATH_FS.resolve(r))throw new FS.ErrnoError(44);var M=FS.lookupPath(e,{parent:!0}),tr=M.node;if(!tr)throw new FS.ErrnoError(44);var rr=PATH.basename(e),ir=FS.mayCreate(tr,rr);if(ir)throw new FS.ErrnoError(ir);if(!tr.node_ops.symlink)throw new FS.ErrnoError(63);return tr.node_ops.symlink(tr,rr,r)},rename(r,e){var M=PATH.dirname(r),tr=PATH.dirname(e),rr=PATH.basename(r),ir=PATH.basename(e),lr,dr,hr;if(lr=FS.lookupPath(r,{parent:!0}),dr=lr.node,lr=FS.lookupPath(e,{parent:!0}),hr=lr.node,!dr||!hr)throw new FS.ErrnoError(44);if(dr.mount!==hr.mount)throw new FS.ErrnoError(75);var fr=FS.lookupNode(dr,rr),mr=PATH_FS.relative(r,tr);if(mr.charAt(0)!==".")throw new FS.ErrnoError(28);if(mr=PATH_FS.relative(e,M),mr.charAt(0)!==".")throw new FS.ErrnoError(55);var _r;try{_r=FS.lookupNode(hr,ir)}catch{}if(fr!==_r){var gr=FS.isDir(fr.mode),wr=FS.mayDelete(dr,rr,gr);if(wr)throw new FS.ErrnoError(wr);if(wr=_r?FS.mayDelete(hr,ir,gr):FS.mayCreate(hr,ir),wr)throw new FS.ErrnoError(wr);if(!dr.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(fr)||_r&&FS.isMountpoint(_r))throw new FS.ErrnoError(10);if(hr!==dr&&(wr=FS.nodePermissions(dr,"w"),wr))throw new FS.ErrnoError(wr);FS.hashRemoveNode(fr);try{dr.node_ops.rename(fr,hr,ir),fr.parent=hr}catch(yr){throw yr}finally{FS.hashAddNode(fr)}}},rmdir(r){var e=FS.lookupPath(r,{parent:!0}),M=e.node,tr=PATH.basename(r),rr=FS.lookupNode(M,tr),ir=FS.mayDelete(M,tr,!0);if(ir)throw new FS.ErrnoError(ir);if(!M.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(rr))throw new FS.ErrnoError(10);M.node_ops.rmdir(M,tr),FS.destroyNode(rr)},readdir(r){var e=FS.lookupPath(r,{follow:!0}),M=e.node;if(!M.node_ops.readdir)throw new FS.ErrnoError(54);return M.node_ops.readdir(M)},unlink(r){var e=FS.lookupPath(r,{parent:!0}),M=e.node;if(!M)throw new FS.ErrnoError(44);var tr=PATH.basename(r),rr=FS.lookupNode(M,tr),ir=FS.mayDelete(M,tr,!1);if(ir)throw new FS.ErrnoError(ir);if(!M.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(rr))throw new FS.ErrnoError(10);M.node_ops.unlink(M,tr),FS.destroyNode(rr)},readlink(r){var e=FS.lookupPath(r),M=e.node;if(!M)throw new FS.ErrnoError(44);if(!M.node_ops.readlink)throw new FS.ErrnoError(28);return M.node_ops.readlink(M)},stat(r,e){var M=FS.lookupPath(r,{follow:!e}),tr=M.node;if(!tr)throw new FS.ErrnoError(44);if(!tr.node_ops.getattr)throw new FS.ErrnoError(63);return tr.node_ops.getattr(tr)},lstat(r){return FS.stat(r,!0)},chmod(r,e,M){var tr;if(typeof r=="string"){var rr=FS.lookupPath(r,{follow:!M});tr=rr.node}else tr=r;if(!tr.node_ops.setattr)throw new FS.ErrnoError(63);tr.node_ops.setattr(tr,{mode:e&4095|tr.mode&-4096,ctime:Date.now()})},lchmod(r,e){FS.chmod(r,e,!0)},fchmod(r,e){var M=FS.getStreamChecked(r);FS.chmod(M.node,e)},chown(r,e,M,tr){var rr;if(typeof r=="string"){var ir=FS.lookupPath(r,{follow:!tr});rr=ir.node}else rr=r;if(!rr.node_ops.setattr)throw new FS.ErrnoError(63);rr.node_ops.setattr(rr,{timestamp:Date.now()})},lchown(r,e,M){FS.chown(r,e,M,!0)},fchown(r,e,M){var tr=FS.getStreamChecked(r);FS.chown(tr.node,e,M)},truncate(r,e){if(e<0)throw new FS.ErrnoError(28);var M;if(typeof r=="string"){var tr=FS.lookupPath(r,{follow:!0});M=tr.node}else M=r;if(!M.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(M.mode))throw new FS.ErrnoError(31);if(!FS.isFile(M.mode))throw new FS.ErrnoError(28);var rr=FS.nodePermissions(M,"w");if(rr)throw new FS.ErrnoError(rr);M.node_ops.setattr(M,{size:e,timestamp:Date.now()})},ftruncate(r,e){var M=FS.getStreamChecked(r);if(!(M.flags&2097155))throw new FS.ErrnoError(28);FS.truncate(M.node,e)},utime(r,e,M){var tr=FS.lookupPath(r,{follow:!0}),rr=tr.node;rr.node_ops.setattr(rr,{atime:e,mtime:M})},open(r,e,M=438){if(r==="")throw new FS.ErrnoError(44);e=typeof e=="string"?FS_modeStringToFlags(e):e,e&64?M=M&4095|32768:M=0;var tr;if(typeof r=="object")tr=r;else{var rr=FS.lookupPath(r,{follow:!(e&131072),noent_okay:!0});tr=rr.node,r=rr.path}var ir=!1;if(e&64)if(tr){if(e&128)throw new FS.ErrnoError(20)}else tr=FS.mknod(r,M,0),ir=!0;if(!tr)throw new FS.ErrnoError(44);if(FS.isChrdev(tr.mode)&&(e&=-513),e&65536&&!FS.isDir(tr.mode))throw new FS.ErrnoError(54);if(!ir){var lr=FS.mayOpen(tr,e);if(lr)throw new FS.ErrnoError(lr)}e&512&&!ir&&FS.truncate(tr,0),e&=-131713;var dr=FS.createStream({node:tr,path:FS.getPath(tr),flags:e,seekable:!0,position:0,stream_ops:tr.stream_ops,ungotten:[],error:!1});return dr.stream_ops.open&&dr.stream_ops.open(dr),Module.logReadFiles&&!(e&1)&&(r in FS.readFiles||(FS.readFiles[r]=1)),dr},close(r){if(FS.isClosed(r))throw new FS.ErrnoError(8);r.getdents&&(r.getdents=null);try{r.stream_ops.close&&r.stream_ops.close(r)}catch(e){throw e}finally{FS.closeStream(r.fd)}r.fd=null},isClosed(r){return r.fd===null},llseek(r,e,M){if(FS.isClosed(r))throw new FS.ErrnoError(8);if(!r.seekable||!r.stream_ops.llseek)throw new FS.ErrnoError(70);if(M!=0&&M!=1&&M!=2)throw new FS.ErrnoError(28);return r.position=r.stream_ops.llseek(r,e,M),r.ungotten=[],r.position},read(r,e,M,tr,rr){if(tr<0||rr<0)throw new FS.ErrnoError(28);if(FS.isClosed(r))throw new FS.ErrnoError(8);if((r.flags&2097155)===1)throw new FS.ErrnoError(8);if(FS.isDir(r.node.mode))throw new FS.ErrnoError(31);if(!r.stream_ops.read)throw new FS.ErrnoError(28);var ir=typeof rr<"u";if(!ir)rr=r.position;else if(!r.seekable)throw new FS.ErrnoError(70);var lr=r.stream_ops.read(r,e,M,tr,rr);return ir||(r.position+=lr),lr},write(r,e,M,tr,rr,ir){if(tr<0||rr<0)throw new FS.ErrnoError(28);if(FS.isClosed(r))throw new FS.ErrnoError(8);if(!(r.flags&2097155))throw new FS.ErrnoError(8);if(FS.isDir(r.node.mode))throw new FS.ErrnoError(31);if(!r.stream_ops.write)throw new FS.ErrnoError(28);r.seekable&&r.flags&1024&&FS.llseek(r,0,2);var lr=typeof rr<"u";if(!lr)rr=r.position;else if(!r.seekable)throw new FS.ErrnoError(70);var dr=r.stream_ops.write(r,e,M,tr,rr,ir);return lr||(r.position+=dr),dr},allocate(r,e,M){if(FS.isClosed(r))throw new FS.ErrnoError(8);if(e<0||M<=0)throw new FS.ErrnoError(28);if(!(r.flags&2097155))throw new FS.ErrnoError(8);if(!FS.isFile(r.node.mode)&&!FS.isDir(r.node.mode))throw new FS.ErrnoError(43);if(!r.stream_ops.allocate)throw new FS.ErrnoError(138);r.stream_ops.allocate(r,e,M)},mmap(r,e,M,tr,rr){if(tr&2&&!(rr&2)&&(r.flags&2097155)!==2)throw new FS.ErrnoError(2);if((r.flags&2097155)===1)throw new FS.ErrnoError(2);if(!r.stream_ops.mmap)throw new FS.ErrnoError(43);if(!e)throw new FS.ErrnoError(28);return r.stream_ops.mmap(r,e,M,tr,rr)},msync(r,e,M,tr,rr){return r.stream_ops.msync?r.stream_ops.msync(r,e,M,tr,rr):0},ioctl(r,e,M){if(!r.stream_ops.ioctl)throw new FS.ErrnoError(59);return r.stream_ops.ioctl(r,e,M)},readFile(r,e={}){if(e.flags=e.flags||0,e.encoding=e.encoding||"binary",e.encoding!=="utf8"&&e.encoding!=="binary")throw new Error(`Invalid encoding type "${e.encoding}"`);var M,tr=FS.open(r,e.flags),rr=FS.stat(r),ir=rr.size,lr=new Uint8Array(ir);return FS.read(tr,lr,0,ir,0),e.encoding==="utf8"?M=UTF8ArrayToString(lr):e.encoding==="binary"&&(M=lr),FS.close(tr),M},writeFile(r,e,M={}){M.flags=M.flags||577;var tr=FS.open(r,M.flags,M.mode);if(typeof e=="string"){var rr=new Uint8Array(lengthBytesUTF8(e)+1),ir=stringToUTF8Array(e,rr,0,rr.length);FS.write(tr,rr,0,ir,void 0,M.canOwn)}else if(ArrayBuffer.isView(e))FS.write(tr,e,0,e.byteLength,void 0,M.canOwn);else throw new Error("Unsupported data type");FS.close(tr)},cwd:()=>FS.currentPath,chdir(r){var e=FS.lookupPath(r,{follow:!0});if(e.node===null)throw new FS.ErrnoError(44);if(!FS.isDir(e.node.mode))throw new FS.ErrnoError(54);var M=FS.nodePermissions(e.node,"x");if(M)throw new FS.ErrnoError(M);FS.currentPath=e.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(tr,rr,ir,lr,dr)=>lr,llseek:()=>0}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var r=new Uint8Array(1024),e=0,M=()=>(e===0&&(e=randomFill(r).byteLength),r[--e]);FS.createDevice("/dev","random",M),FS.createDevice("/dev","urandom",M),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var r=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var e=FS.createNode(r,"fd",16895,73);return e.stream_ops={llseek:MEMFS.stream_ops.llseek},e.node_ops={lookup(M,tr){var rr=+tr,ir=FS.getStreamChecked(rr),lr={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>ir.path},id:rr+1};return lr.parent=lr,lr},readdir(){return Array.from(FS.streams.entries()).filter(([M,tr])=>tr).map(([M,tr])=>M.toString())}},e}},{},"/proc/self/fd")},createStandardStreams(r,e,M){r?FS.createDevice("/dev","stdin",r):FS.symlink("/dev/tty","/dev/stdin"),e?FS.createDevice("/dev","stdout",null,e):FS.symlink("/dev/tty","/dev/stdout"),M?FS.createDevice("/dev","stderr",null,M):FS.symlink("/dev/tty1","/dev/stderr"),FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS,IDBFS,NODEFS}},init(r,e,M){FS.initialized=!0,r??(r=Module.stdin),e??(e=Module.stdout),M??(M=Module.stderr),FS.createStandardStreams(r,e,M)},quit(){FS.initialized=!1,_fflush(0);for(var r=0;r<FS.streams.length;r++){var e=FS.streams[r];e&&FS.close(e)}},findObject(r,e){var M=FS.analyzePath(r,e);return M.exists?M.object:null},analyzePath(r,e){try{var M=FS.lookupPath(r,{follow:!e});r=M.path}catch{}var tr={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var M=FS.lookupPath(r,{parent:!0});tr.parentExists=!0,tr.parentPath=M.path,tr.parentObject=M.node,tr.name=PATH.basename(r),M=FS.lookupPath(r,{follow:!e}),tr.exists=!0,tr.path=M.path,tr.object=M.node,tr.name=M.node.name,tr.isRoot=M.path==="/"}catch(rr){tr.error=rr.errno}return tr},createPath(r,e,M,tr){r=typeof r=="string"?r:FS.getPath(r);for(var rr=e.split("/").reverse();rr.length;){var ir=rr.pop();if(ir){var lr=PATH.join2(r,ir);try{FS.mkdir(lr)}catch{}r=lr}}return lr},createFile(r,e,M,tr,rr){var ir=PATH.join2(typeof r=="string"?r:FS.getPath(r),e),lr=FS_getMode(tr,rr);return FS.create(ir,lr)},createDataFile(r,e,M,tr,rr,ir){var lr=e;r&&(r=typeof r=="string"?r:FS.getPath(r),lr=e?PATH.join2(r,e):r);var dr=FS_getMode(tr,rr),hr=FS.create(lr,dr);if(M){if(typeof M=="string"){for(var fr=new Array(M.length),mr=0,_r=M.length;mr<_r;++mr)fr[mr]=M.charCodeAt(mr);M=fr}FS.chmod(hr,dr|146);var gr=FS.open(hr,577);FS.write(gr,M,0,M.length,0,ir),FS.close(gr),FS.chmod(hr,dr)}},createDevice(r,e,M,tr){var rr,ir=PATH.join2(typeof r=="string"?r:FS.getPath(r),e),lr=FS_getMode(!!M,!!tr);(rr=FS.createDevice).major??(rr.major=64);var dr=FS.makedev(FS.createDevice.major++,0);return FS.registerDevice(dr,{open(hr){hr.seekable=!1},close(hr){tr?.buffer?.length&&tr(10)},read(hr,fr,mr,_r,gr){for(var wr=0,yr=0;yr<_r;yr++){var br;try{br=M()}catch{throw new FS.ErrnoError(29)}if(br===void 0&&wr===0)throw new FS.ErrnoError(6);if(br==null)break;wr++,fr[mr+yr]=br}return wr&&(hr.node.atime=Date.now()),wr},write(hr,fr,mr,_r,gr){for(var wr=0;wr<_r;wr++)try{tr(fr[mr+wr])}catch{throw new FS.ErrnoError(29)}return _r&&(hr.node.mtime=hr.node.ctime=Date.now()),wr}}),FS.mkdev(ir,lr,dr)},forceLoadFile(r){if(r.isDevice||r.isFolder||r.link||r.contents)return!0;if(typeof XMLHttpRequest<"u")throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");try{r.contents=readBinary(r.url),r.usedBytes=r.contents.length}catch{throw new FS.ErrnoError(29)}},createLazyFile(r,e,M,tr,rr){class ir{constructor(){P$1(this,"lengthKnown",!1),P$1(this,"chunks",[])}get(wr){if(!(wr>this.length-1||wr<0)){var yr=wr%this.chunkSize,br=wr/this.chunkSize|0;return this.getter(br)[yr]}}setDataGetter(wr){this.getter=wr}cacheLength(){var wr=new XMLHttpRequest;if(wr.open("HEAD",M,!1),wr.send(null),!(wr.status>=200&&wr.status<300||wr.status===304))throw new Error("Couldn't load "+M+". Status: "+wr.status);var yr=Number(wr.getResponseHeader("Content-length")),br,Mr=(br=wr.getResponseHeader("Accept-Ranges"))&&br==="bytes",vr=(br=wr.getResponseHeader("Content-Encoding"))&&br==="gzip",Sr=1024*1024;Mr||(Sr=yr);var xr=(Dr,Ir)=>{if(Dr>Ir)throw new Error("invalid range ("+Dr+", "+Ir+") or no bytes requested!");if(Ir>yr-1)throw new Error("only "+yr+" bytes available! programmer error!");var kr=new XMLHttpRequest;if(kr.open("GET",M,!1),yr!==Sr&&kr.setRequestHeader("Range","bytes="+Dr+"-"+Ir),kr.responseType="arraybuffer",kr.overrideMimeType&&kr.overrideMimeType("text/plain; charset=x-user-defined"),kr.send(null),!(kr.status>=200&&kr.status<300||kr.status===304))throw new Error("Couldn't load "+M+". Status: "+kr.status);return kr.response!==void 0?new Uint8Array(kr.response||[]):intArrayFromString(kr.responseText||"")},Ar=this;Ar.setDataGetter(Dr=>{var Ir=Dr*Sr,kr=(Dr+1)*Sr-1;if(kr=Math.min(kr,yr-1),typeof Ar.chunks[Dr]>"u"&&(Ar.chunks[Dr]=xr(Ir,kr)),typeof Ar.chunks[Dr]>"u")throw new Error("doXHR failed!");return Ar.chunks[Dr]}),(vr||!yr)&&(Sr=yr=1,yr=this.getter(0).length,Sr=yr,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=yr,this._chunkSize=Sr,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(typeof XMLHttpRequest<"u"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lr=new ir,dr={isDevice:!1,contents:lr}}else var dr={isDevice:!1,url:M};var hr=FS.createFile(r,e,dr,tr,rr);dr.contents?hr.contents=dr.contents:dr.url&&(hr.contents=null,hr.url=dr.url),Object.defineProperties(hr,{usedBytes:{get:function(){return this.contents.length}}});var fr={},mr=Object.keys(hr.stream_ops);mr.forEach(gr=>{var wr=hr.stream_ops[gr];fr[gr]=(...yr)=>(FS.forceLoadFile(hr),wr(...yr))});function _r(gr,wr,yr,br,Mr){var vr=gr.node.contents;if(Mr>=vr.length)return 0;var Sr=Math.min(vr.length-Mr,br);if(vr.slice)for(var xr=0;xr<Sr;xr++)wr[yr+xr]=vr[Mr+xr];else for(var xr=0;xr<Sr;xr++)wr[yr+xr]=vr.get(Mr+xr);return Sr}return fr.read=(gr,wr,yr,br,Mr)=>(FS.forceLoadFile(hr),_r(gr,wr,yr,br,Mr)),fr.mmap=(gr,wr,yr,br,Mr)=>{FS.forceLoadFile(hr);var vr=mmapAlloc(wr);if(!vr)throw new FS.ErrnoError(48);return _r(gr,HEAP8,vr,wr,yr),{ptr:vr,allocated:!0}},hr.stream_ops=fr,hr}},SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(r,e,M){if(PATH.isAbs(e))return e;var tr;if(r===-100)tr=FS.cwd();else{var rr=SYSCALLS.getStreamFromFD(r);tr=rr.path}if(e.length==0){if(!M)throw new FS.ErrnoError(44);return tr}return tr+"/"+e},doStat(r,e,M){var tr=r(e);HEAP32[M>>2]=tr.dev,HEAP32[M+4>>2]=tr.mode,HEAPU32[M+8>>2]=tr.nlink,HEAP32[M+12>>2]=tr.uid,HEAP32[M+16>>2]=tr.gid,HEAP32[M+20>>2]=tr.rdev,HEAP64[M+24>>3]=BigInt(tr.size),HEAP32[M+32>>2]=4096,HEAP32[M+36>>2]=tr.blocks;var rr=tr.atime.getTime(),ir=tr.mtime.getTime(),lr=tr.ctime.getTime();return HEAP64[M+40>>3]=BigInt(Math.floor(rr/1e3)),HEAPU32[M+48>>2]=rr%1e3*1e3*1e3,HEAP64[M+56>>3]=BigInt(Math.floor(ir/1e3)),HEAPU32[M+64>>2]=ir%1e3*1e3*1e3,HEAP64[M+72>>3]=BigInt(Math.floor(lr/1e3)),HEAPU32[M+80>>2]=lr%1e3*1e3*1e3,HEAP64[M+88>>3]=BigInt(tr.ino),0},doMsync(r,e,M,tr,rr){if(!FS.isFile(e.node.mode))throw new FS.ErrnoError(43);if(tr&2)return 0;var ir=HEAPU8.slice(r,r+M);FS.msync(e,ir,rr,M,tr)},getStreamFromFD(r){var e=FS.getStreamChecked(r);return e},varargs:void 0,getStr(r){var e=UTF8ToString(r);return e}},___syscall__newselect=function(r,e,M,tr,rr){try{for(var ir=0,lr=e?HEAP32[e>>2]:0,dr=e?HEAP32[e+4>>2]:0,hr=M?HEAP32[M>>2]:0,fr=M?HEAP32[M+4>>2]:0,mr=tr?HEAP32[tr>>2]:0,_r=tr?HEAP32[tr+4>>2]:0,gr=0,wr=0,yr=0,br=0,Mr=0,vr=0,Sr=(e?HEAP32[e>>2]:0)|(M?HEAP32[M>>2]:0)|(tr?HEAP32[tr>>2]:0),xr=(e?HEAP32[e+4>>2]:0)|(M?HEAP32[M+4>>2]:0)|(tr?HEAP32[tr+4>>2]:0),Ar=(Gr,Lr,$r,zr)=>Gr<32?Lr&zr:$r&zr,Dr=0;Dr<r;Dr++){var Ir=1<<Dr%32;if(Ar(Dr,Sr,xr,Ir)){var kr=SYSCALLS.getStreamFromFD(Dr),Or=SYSCALLS.DEFAULT_POLLMASK;if(kr.stream_ops.poll){var Fr=-1;if(rr){var Jr=e?HEAP32[rr>>2]:0,$n=e?HEAP32[rr+4>>2]:0;Fr=(Jr+$n/1e6)*1e3}Or=kr.stream_ops.poll(kr,Fr)}Or&1&&Ar(Dr,lr,dr,Ir)&&(Dr<32?gr=gr|Ir:wr=wr|Ir,ir++),Or&4&&Ar(Dr,hr,fr,Ir)&&(Dr<32?yr=yr|Ir:br=br|Ir,ir++),Or&2&&Ar(Dr,mr,_r,Ir)&&(Dr<32?Mr=Mr|Ir:vr=vr|Ir,ir++)}}return e&&(HEAP32[e>>2]=gr,HEAP32[e+4>>2]=wr),M&&(HEAP32[M>>2]=yr,HEAP32[M+4>>2]=br),tr&&(HEAP32[tr>>2]=Mr,HEAP32[tr+4>>2]=vr),ir}catch(Gr){if(typeof FS>"u"||Gr.name!=="ErrnoError")throw Gr;return-Gr.errno}};___syscall__newselect.sig="iipppp";var SOCKFS={websocketArgs:{},callbacks:{},on(r,e){SOCKFS.callbacks[r]=e},emit(r,e){SOCKFS.callbacks[r]?.(e)},mount(r){return SOCKFS.websocketArgs=Module.websocket||{},(Module.websocket??(Module.websocket={})).on=SOCKFS.on,FS.createNode(null,"/",16895,0)},createSocket(r,e,M){e&=-526337;var tr=e==1;if(tr&&M&&M!=6)throw new FS.ErrnoError(66);var rr={family:r,type:e,protocol:M,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},ir=SOCKFS.nextname(),lr=FS.createNode(SOCKFS.root,ir,49152,0);lr.sock=rr;var dr=FS.createStream({path:ir,node:lr,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return rr.stream=dr,rr},getSocket(r){var e=FS.getStream(r);return!e||!FS.isSocket(e.node.mode)?null:e.node.sock},stream_ops:{poll(r){var e=r.node.sock;return e.sock_ops.poll(e)},ioctl(r,e,M){var tr=r.node.sock;return tr.sock_ops.ioctl(tr,e,M)},read(r,e,M,tr,rr){var ir=r.node.sock,lr=ir.sock_ops.recvmsg(ir,tr);return lr?(e.set(lr.buffer,M),lr.buffer.length):0},write(r,e,M,tr,rr){var ir=r.node.sock;return ir.sock_ops.sendmsg(ir,e,M,tr)},close(r){var e=r.node.sock;e.sock_ops.close(e)}},nextname(){return SOCKFS.nextname.current||(SOCKFS.nextname.current=0),`socket[${SOCKFS.nextname.current++}]`},websocket_sock_ops:{createPeer(r,e,M){var tr;if(typeof e=="object"&&(tr=e,e=null,M=null),tr)if(tr._socket)e=tr._socket.remoteAddress,M=tr._socket.remotePort;else{var rr=/ws[s]?:\/\/([^:]+):(\d+)/.exec(tr.url);if(!rr)throw new Error("WebSocket URL must be in the format ws(s)://address:port");e=rr[1],M=parseInt(rr[2],10)}else try{var ir="ws:#".replace("#","//"),lr="binary",dr=void 0;if(SOCKFS.websocketArgs.url&&(ir=SOCKFS.websocketArgs.url),SOCKFS.websocketArgs.subprotocol?lr=SOCKFS.websocketArgs.subprotocol:SOCKFS.websocketArgs.subprotocol===null&&(lr="null"),ir==="ws://"||ir==="wss://"){var hr=e.split("/");ir=ir+hr[0]+":"+M+"/"+hr.slice(1).join("/")}lr!=="null"&&(lr=lr.replace(/^ +| +$/g,"").split(/ *, */),dr=lr);var fr;ENVIRONMENT_IS_NODE?fr=require("ws"):fr=WebSocket,tr=new fr(ir,dr),tr.binaryType="arraybuffer"}catch{throw new FS.ErrnoError(23)}var mr={addr:e,port:M,socket:tr,msg_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(r,mr),SOCKFS.websocket_sock_ops.handlePeerEvents(r,mr),r.type===2&&typeof r.sport<"u"&&mr.msg_send_queue.push(new Uint8Array([255,255,255,255,112,111,114,116,(r.sport&65280)>>8,r.sport&255])),mr},getPeer(r,e,M){return r.peers[e+":"+M]},addPeer(r,e){r.peers[e.addr+":"+e.port]=e},removePeer(r,e){delete r.peers[e.addr+":"+e.port]},handlePeerEvents(r,e){var M=!0,tr=function(){r.connecting=!1,SOCKFS.emit("open",r.stream.fd);try{for(var ir=e.msg_send_queue.shift();ir;)e.socket.send(ir),ir=e.msg_send_queue.shift()}catch{e.socket.close()}};function rr(ir){if(typeof ir=="string"){var lr=new TextEncoder;ir=lr.encode(ir)}else{if(assert(ir.byteLength!==void 0),ir.byteLength==0)return;ir=new Uint8Array(ir)}var dr=M;if(M=!1,dr&&ir.length===10&&ir[0]===255&&ir[1]===255&&ir[2]===255&&ir[3]===255&&ir[4]===112&&ir[5]===111&&ir[6]===114&&ir[7]===116){var hr=ir[8]<<8|ir[9];SOCKFS.websocket_sock_ops.removePeer(r,e),e.port=hr,SOCKFS.websocket_sock_ops.addPeer(r,e);return}r.recv_queue.push({addr:e.addr,port:e.port,data:ir}),SOCKFS.emit("message",r.stream.fd)}ENVIRONMENT_IS_NODE?(e.socket.on("open",tr),e.socket.on("message",function(ir,lr){lr&&rr(new Uint8Array(ir).buffer)}),e.socket.on("close",function(){SOCKFS.emit("close",r.stream.fd)}),e.socket.on("error",function(ir){r.error=14,SOCKFS.emit("error",[r.stream.fd,r.error,"ECONNREFUSED: Connection refused"])})):(e.socket.onopen=tr,e.socket.onclose=function(){SOCKFS.emit("close",r.stream.fd)},e.socket.onmessage=function(ir){rr(ir.data)},e.socket.onerror=function(ir){r.error=14,SOCKFS.emit("error",[r.stream.fd,r.error,"ECONNREFUSED: Connection refused"])})},poll(r){if(r.type===1&&r.server)return r.pending.length?65:0;var e=0,M=r.type===1?SOCKFS.websocket_sock_ops.getPeer(r,r.daddr,r.dport):null;return(r.recv_queue.length||!M||M&&M.socket.readyState===M.socket.CLOSING||M&&M.socket.readyState===M.socket.CLOSED)&&(e|=65),(!M||M&&M.socket.readyState===M.socket.OPEN)&&(e|=4),(M&&M.socket.readyState===M.socket.CLOSING||M&&M.socket.readyState===M.socket.CLOSED)&&(r.connecting?e|=4:e|=16),e},ioctl(r,e,M){if(e===21531){var tr=0;return r.recv_queue.length&&(tr=r.recv_queue[0].data.length),HEAP32[M>>2]=tr,0}else return 28},close(r){if(r.server){try{r.server.close()}catch{}r.server=null}for(var e=Object.keys(r.peers),M=0;M<e.length;M++){var tr=r.peers[e[M]];try{tr.socket.close()}catch{}SOCKFS.websocket_sock_ops.removePeer(r,tr)}return 0},bind(r,e,M){if(typeof r.saddr<"u"||typeof r.sport<"u")throw new FS.ErrnoError(28);if(r.saddr=e,r.sport=M,r.type===2){r.server&&(r.server.close(),r.server=null);try{r.sock_ops.listen(r,0)}catch(tr){if(tr.name!=="ErrnoError"||tr.errno!==138)throw tr}}},connect(r,e,M){if(r.server)throw new FS.ErrnoError(138);if(typeof r.daddr<"u"&&typeof r.dport<"u"){var tr=SOCKFS.websocket_sock_ops.getPeer(r,r.daddr,r.dport);if(tr)throw tr.socket.readyState===tr.socket.CONNECTING?new FS.ErrnoError(7):new FS.ErrnoError(30)}var rr=SOCKFS.websocket_sock_ops.createPeer(r,e,M);r.daddr=rr.addr,r.dport=rr.port,r.connecting=!0},listen(r,e){if(!ENVIRONMENT_IS_NODE)throw new FS.ErrnoError(138);if(r.server)throw new FS.ErrnoError(28);var M=require("ws").Server,tr=r.saddr;r.server=new M({host:tr,port:r.sport}),SOCKFS.emit("listen",r.stream.fd),r.server.on("connection",function(rr){if(r.type===1){var ir=SOCKFS.createSocket(r.family,r.type,r.protocol),lr=SOCKFS.websocket_sock_ops.createPeer(ir,rr);ir.daddr=lr.addr,ir.dport=lr.port,r.pending.push(ir),SOCKFS.emit("connection",ir.stream.fd)}else SOCKFS.websocket_sock_ops.createPeer(r,rr),SOCKFS.emit("connection",r.stream.fd)}),r.server.on("close",function(){SOCKFS.emit("close",r.stream.fd),r.server=null}),r.server.on("error",function(rr){r.error=23,SOCKFS.emit("error",[r.stream.fd,r.error,"EHOSTUNREACH: Host is unreachable"])})},accept(r){if(!r.server||!r.pending.length)throw new FS.ErrnoError(28);var e=r.pending.shift();return e.stream.flags=r.stream.flags,e},getname(r,e){var M,tr;if(e){if(r.daddr===void 0||r.dport===void 0)throw new FS.ErrnoError(53);M=r.daddr,tr=r.dport}else M=r.saddr||0,tr=r.sport||0;return{addr:M,port:tr}},sendmsg(r,e,M,tr,rr,ir){if(r.type===2){if((rr===void 0||ir===void 0)&&(rr=r.daddr,ir=r.dport),rr===void 0||ir===void 0)throw new FS.ErrnoError(17)}else rr=r.daddr,ir=r.dport;var lr=SOCKFS.websocket_sock_ops.getPeer(r,rr,ir);if(r.type===1&&(!lr||lr.socket.readyState===lr.socket.CLOSING||lr.socket.readyState===lr.socket.CLOSED))throw new FS.ErrnoError(53);ArrayBuffer.isView(e)&&(M+=e.byteOffset,e=e.buffer);var dr=e.slice(M,M+tr);if(!lr||lr.socket.readyState!==lr.socket.OPEN)return r.type===2&&(!lr||lr.socket.readyState===lr.socket.CLOSING||lr.socket.readyState===lr.socket.CLOSED)&&(lr=SOCKFS.websocket_sock_ops.createPeer(r,rr,ir)),lr.msg_send_queue.push(dr),tr;try{return lr.socket.send(dr),tr}catch{throw new FS.ErrnoError(28)}},recvmsg(r,e){if(r.type===1&&r.server)throw new FS.ErrnoError(53);var M=r.recv_queue.shift();if(!M){if(r.type===1){var tr=SOCKFS.websocket_sock_ops.getPeer(r,r.daddr,r.dport);if(!tr)throw new FS.ErrnoError(53);if(tr.socket.readyState===tr.socket.CLOSING||tr.socket.readyState===tr.socket.CLOSED)return null;throw new FS.ErrnoError(6)}throw new FS.ErrnoError(6)}var rr=M.data.byteLength||M.data.length,ir=M.data.byteOffset||0,lr=M.data.buffer||M.data,dr=Math.min(e,rr),hr={buffer:new Uint8Array(lr,ir,dr),addr:M.addr,port:M.port};if(r.type===1&&dr<rr){var fr=rr-dr;M.data=new Uint8Array(lr,ir+dr,fr),r.recv_queue.unshift(M)}return hr}}},getSocketFromFD=r=>{var e=SOCKFS.getSocket(r);if(!e)throw new FS.ErrnoError(8);return e},inetNtop4=r=>(r&255)+"."+(r>>8&255)+"."+(r>>16&255)+"."+(r>>24&255),inetNtop6=r=>{var e="",M=0,tr=0,rr=0,ir=0,lr=0,dr=0,hr=[r[0]&65535,r[0]>>16,r[1]&65535,r[1]>>16,r[2]&65535,r[2]>>16,r[3]&65535,r[3]>>16],fr=!0,mr="";for(dr=0;dr<5;dr++)if(hr[dr]!==0){fr=!1;break}if(fr){if(mr=inetNtop4(hr[6]|hr[7]<<16),hr[5]===-1)return e="::ffff:",e+=mr,e;if(hr[5]===0)return e="::",mr==="0.0.0.0"&&(mr=""),mr==="0.0.0.1"&&(mr="1"),e+=mr,e}for(M=0;M<8;M++)hr[M]===0&&(M-rr>1&&(lr=0),rr=M,lr++),lr>tr&&(tr=lr,ir=M-tr+1);for(M=0;M<8;M++){if(tr>1&&hr[M]===0&&M>=ir&&M<ir+tr){M===ir&&(e+=":",ir===0&&(e+=":"));continue}e+=Number(_ntohs(hr[M]&65535)).toString(16),e+=M<7?":":""}return e},readSockaddr=(r,e)=>{var M=HEAP16[r>>1],tr=_ntohs(HEAPU16[r+2>>1]),rr;switch(M){case 2:if(e!==16)return{errno:28};rr=HEAP32[r+4>>2],rr=inetNtop4(rr);break;case 10:if(e!==28)return{errno:28};rr=[HEAP32[r+8>>2],HEAP32[r+12>>2],HEAP32[r+16>>2],HEAP32[r+20>>2]],rr=inetNtop6(rr);break;default:return{errno:5}}return{family:M,addr:rr,port:tr}},inetPton4=r=>{for(var e=r.split("."),M=0;M<4;M++){var tr=Number(e[M]);if(isNaN(tr))return null;e[M]=tr}return(e[0]|e[1]<<8|e[2]<<16|e[3]<<24)>>>0},jstoi_q=r=>parseInt(r),inetPton6=r=>{var e,M,tr,rr,ir=/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i,lr=[];if(!ir.test(r))return null;if(r==="::")return[0,0,0,0,0,0,0,0];for(r.startsWith("::")?r=r.replace("::","Z:"):r=r.replace("::",":Z:"),r.indexOf(".")>0?(r=r.replace(new RegExp("[.]","g"),":"),e=r.split(":"),e[e.length-4]=jstoi_q(e[e.length-4])+jstoi_q(e[e.length-3])*256,e[e.length-3]=jstoi_q(e[e.length-2])+jstoi_q(e[e.length-1])*256,e=e.slice(0,e.length-2)):e=r.split(":"),tr=0,rr=0,M=0;M<e.length;M++)if(typeof e[M]=="string")if(e[M]==="Z"){for(rr=0;rr<8-e.length+1;rr++)lr[M+rr]=0;tr=rr-1}else lr[M+tr]=_htons(parseInt(e[M],16));else lr[M+tr]=e[M];return[lr[1]<<16|lr[0],lr[3]<<16|lr[2],lr[5]<<16|lr[4],lr[7]<<16|lr[6]]},DNS={address_map:{id:1,addrs:{},names:{}},lookup_name(r){var e=inetPton4(r);if(e!==null||(e=inetPton6(r),e!==null))return r;var M;if(DNS.address_map.addrs[r])M=DNS.address_map.addrs[r];else{var tr=DNS.address_map.id++;assert(tr<65535,"exceeded max address mappings of 65535"),M="172.29."+(tr&255)+"."+(tr&65280),DNS.address_map.names[M]=r,DNS.address_map.addrs[r]=M}return M},lookup_addr(r){return DNS.address_map.names[r]?DNS.address_map.names[r]:null}},getSocketAddress=(r,e)=>{var M=readSockaddr(r,e);if(M.errno)throw new FS.ErrnoError(M.errno);return M.addr=DNS.lookup_addr(M.addr)||M.addr,M};function ___syscall_bind(r,e,M,tr,rr,ir){try{var lr=getSocketFromFD(r),dr=getSocketAddress(e,M);return lr.sock_ops.bind(lr,dr.addr,dr.port),0}catch(hr){if(typeof FS>"u"||hr.name!=="ErrnoError")throw hr;return-hr.errno}}___syscall_bind.sig="iippiii";function ___syscall_chdir(r){try{return r=SYSCALLS.getStr(r),FS.chdir(r),0}catch(e){if(typeof FS>"u"||e.name!=="ErrnoError")throw e;return-e.errno}}___syscall_chdir.sig="ip";function ___syscall_chmod(r,e){try{return r=SYSCALLS.getStr(r),FS.chmod(r,e),0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_chmod.sig="ipi";function ___syscall_dup(r){try{var e=SYSCALLS.getStreamFromFD(r);return FS.dupStream(e).fd}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_dup.sig="ii";function ___syscall_dup3(r,e,M){try{var tr=SYSCALLS.getStreamFromFD(r);if(tr.fd===e)return-28;if(e<0||e>=FS.MAX_OPEN_FDS)return-8;var rr=FS.getStream(e);return rr&&FS.close(rr),FS.dupStream(tr,e).fd}catch(ir){if(typeof FS>"u"||ir.name!=="ErrnoError")throw ir;return-ir.errno}}___syscall_dup3.sig="iiii";function ___syscall_faccessat(r,e,M,tr){try{if(e=SYSCALLS.getStr(e),e=SYSCALLS.calculateAt(r,e),M&-8)return-28;var rr=FS.lookupPath(e,{follow:!0}),ir=rr.node;if(!ir)return-44;var lr="";return M&4&&(lr+="r"),M&2&&(lr+="w"),M&1&&(lr+="x"),lr&&FS.nodePermissions(ir,lr)?-2:0}catch(dr){if(typeof FS>"u"||dr.name!=="ErrnoError")throw dr;return-dr.errno}}___syscall_faccessat.sig="iipii";var ___syscall_fadvise64=(r,e,M,tr)=>0;___syscall_fadvise64.sig="iijji";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=r=>r<INT53_MIN||r>INT53_MAX?NaN:Number(r);function ___syscall_fallocate(r,e,M,tr){M=bigintToI53Checked(M),tr=bigintToI53Checked(tr);try{if(isNaN(M))return 61;var rr=SYSCALLS.getStreamFromFD(r);return FS.allocate(rr,M,tr),0}catch(ir){if(typeof FS>"u"||ir.name!=="ErrnoError")throw ir;return-ir.errno}}___syscall_fallocate.sig="iiijj";var syscallGetVarargI=()=>{var r=HEAP32[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,r},syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(r,e,M){SYSCALLS.varargs=M;try{var tr=SYSCALLS.getStreamFromFD(r);switch(e){case 0:{var rr=syscallGetVarargI();if(rr<0)return-28;for(;FS.streams[rr];)rr++;var ir;return ir=FS.dupStream(tr,rr),ir.fd}case 1:case 2:return 0;case 3:return tr.flags;case 4:{var rr=syscallGetVarargI();return tr.flags|=rr,0}case 12:{var rr=syscallGetVarargP(),lr=0;return HEAP16[rr+lr>>1]=2,0}case 13:case 14:return 0}return-28}catch(dr){if(typeof FS>"u"||dr.name!=="ErrnoError")throw dr;return-dr.errno}}___syscall_fcntl64.sig="iiip";function ___syscall_fdatasync(r){try{var e=SYSCALLS.getStreamFromFD(r);return 0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_fdatasync.sig="ii";function ___syscall_fstat64(r,e){try{var M=SYSCALLS.getStreamFromFD(r);return SYSCALLS.doStat(FS.stat,M.path,e)}catch(tr){if(typeof FS>"u"||tr.name!=="ErrnoError")throw tr;return-tr.errno}}___syscall_fstat64.sig="iip";function ___syscall_ftruncate64(r,e){e=bigintToI53Checked(e);try{return isNaN(e)?61:(FS.ftruncate(r,e),0)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_ftruncate64.sig="iij";var stringToUTF8=(r,e,M)=>stringToUTF8Array(r,HEAPU8,e,M);function ___syscall_getcwd(r,e){try{if(e===0)return-28;var M=FS.cwd(),tr=lengthBytesUTF8(M)+1;return e<tr?-68:(stringToUTF8(M,r,e),tr)}catch(rr){if(typeof FS>"u"||rr.name!=="ErrnoError")throw rr;return-rr.errno}}___syscall_getcwd.sig="ipp";function ___syscall_getdents64(r,e,M){try{var tr=SYSCALLS.getStreamFromFD(r);tr.getdents||(tr.getdents=FS.readdir(tr.path));for(var rr=280,ir=0,lr=FS.llseek(tr,0,1),dr=Math.floor(lr/rr),hr=Math.min(tr.getdents.length,dr+Math.floor(M/rr)),fr=dr;fr<hr;fr++){var mr,_r,gr=tr.getdents[fr];if(gr===".")mr=tr.node.id,_r=4;else if(gr===".."){var wr=FS.lookupPath(tr.path,{parent:!0});mr=wr.node.id,_r=4}else{var yr;try{yr=FS.lookupNode(tr.node,gr)}catch(br){if(br?.errno===28)continue;throw br}mr=yr.id,_r=FS.isChrdev(yr.mode)?2:FS.isDir(yr.mode)?4:FS.isLink(yr.mode)?10:8}HEAP64[e+ir>>3]=BigInt(mr),HEAP64[e+ir+8>>3]=BigInt((fr+1)*rr),HEAP16[e+ir+16>>1]=280,HEAP8[e+ir+18]=_r,stringToUTF8(gr,e+ir+19,256),ir+=rr}return FS.llseek(tr,fr*rr,0),ir}catch(br){if(typeof FS>"u"||br.name!=="ErrnoError")throw br;return-br.errno}}___syscall_getdents64.sig="iipp";function ___syscall_ioctl(r,e,M){SYSCALLS.varargs=M;try{var tr=SYSCALLS.getStreamFromFD(r);switch(e){case 21509:return tr.tty?0:-59;case 21505:{if(!tr.tty)return-59;if(tr.tty.ops.ioctl_tcgets){var rr=tr.tty.ops.ioctl_tcgets(tr),ir=syscallGetVarargP();HEAP32[ir>>2]=rr.c_iflag||0,HEAP32[ir+4>>2]=rr.c_oflag||0,HEAP32[ir+8>>2]=rr.c_cflag||0,HEAP32[ir+12>>2]=rr.c_lflag||0;for(var lr=0;lr<32;lr++)HEAP8[ir+lr+17]=rr.c_cc[lr]||0;return 0}return 0}case 21510:case 21511:case 21512:return tr.tty?0:-59;case 21506:case 21507:case 21508:{if(!tr.tty)return-59;if(tr.tty.ops.ioctl_tcsets){for(var ir=syscallGetVarargP(),dr=HEAP32[ir>>2],hr=HEAP32[ir+4>>2],fr=HEAP32[ir+8>>2],mr=HEAP32[ir+12>>2],_r=[],lr=0;lr<32;lr++)_r.push(HEAP8[ir+lr+17]);return tr.tty.ops.ioctl_tcsets(tr.tty,e,{c_iflag:dr,c_oflag:hr,c_cflag:fr,c_lflag:mr,c_cc:_r})}return 0}case 21519:{if(!tr.tty)return-59;var ir=syscallGetVarargP();return HEAP32[ir>>2]=0,0}case 21520:return tr.tty?-28:-59;case 21531:{var ir=syscallGetVarargP();return FS.ioctl(tr,e,ir)}case 21523:{if(!tr.tty)return-59;if(tr.tty.ops.ioctl_tiocgwinsz){var gr=tr.tty.ops.ioctl_tiocgwinsz(tr.tty),ir=syscallGetVarargP();HEAP16[ir>>1]=gr[0],HEAP16[ir+2>>1]=gr[1]}return 0}case 21524:return tr.tty?0:-59;case 21515:return tr.tty?0:-59;default:return-28}}catch(wr){if(typeof FS>"u"||wr.name!=="ErrnoError")throw wr;return-wr.errno}}___syscall_ioctl.sig="iiip";function ___syscall_lstat64(r,e){try{return r=SYSCALLS.getStr(r),SYSCALLS.doStat(FS.lstat,r,e)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_lstat64.sig="ipp";function ___syscall_mkdirat(r,e,M){try{return e=SYSCALLS.getStr(e),e=SYSCALLS.calculateAt(r,e),FS.mkdir(e,M,0),0}catch(tr){if(typeof FS>"u"||tr.name!=="ErrnoError")throw tr;return-tr.errno}}___syscall_mkdirat.sig="iipi";function ___syscall_newfstatat(r,e,M,tr){try{e=SYSCALLS.getStr(e);var rr=tr&256,ir=tr&4096;return tr=tr&-6401,e=SYSCALLS.calculateAt(r,e,ir),SYSCALLS.doStat(rr?FS.lstat:FS.stat,e,M)}catch(lr){if(typeof FS>"u"||lr.name!=="ErrnoError")throw lr;return-lr.errno}}___syscall_newfstatat.sig="iippi";function ___syscall_openat(r,e,M,tr){SYSCALLS.varargs=tr;try{e=SYSCALLS.getStr(e),e=SYSCALLS.calculateAt(r,e);var rr=tr?syscallGetVarargI():0;return FS.open(e,M,rr).fd}catch(ir){if(typeof FS>"u"||ir.name!=="ErrnoError")throw ir;return-ir.errno}}___syscall_openat.sig="iipip";var PIPEFS={BUCKET_BUFFER_SIZE:8192,mount(r){return FS.createNode(null,"/",16895,0)},createPipe(){var r={buckets:[],refcnt:2};r.buckets.push({buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:0,roffset:0});var e=PIPEFS.nextname(),M=PIPEFS.nextname(),tr=FS.createNode(PIPEFS.root,e,4096,0),rr=FS.createNode(PIPEFS.root,M,4096,0);tr.pipe=r,rr.pipe=r;var ir=FS.createStream({path:e,node:tr,flags:0,seekable:!1,stream_ops:PIPEFS.stream_ops});tr.stream=ir;var lr=FS.createStream({path:M,node:rr,flags:1,seekable:!1,stream_ops:PIPEFS.stream_ops});return rr.stream=lr,{readable_fd:ir.fd,writable_fd:lr.fd}},stream_ops:{poll(r){var e=r.node.pipe;if((r.flags&2097155)===1)return 260;if(e.buckets.length>0)for(var M=0;M<e.buckets.length;M++){var tr=e.buckets[M];if(tr.offset-tr.roffset>0)return 65}return 0},ioctl(r,e,M){return 28},fsync(r){return 28},read(r,e,M,tr,rr){for(var ir=r.node.pipe,lr=0,dr=0;dr<ir.buckets.length;dr++){var hr=ir.buckets[dr];lr+=hr.offset-hr.roffset}var fr=e.subarray(M,M+tr);if(tr<=0)return 0;if(lr==0)throw new FS.ErrnoError(6);for(var mr=Math.min(lr,tr),_r=mr,gr=0,dr=0;dr<ir.buckets.length;dr++){var wr=ir.buckets[dr],yr=wr.offset-wr.roffset;if(mr<=yr){var br=wr.buffer.subarray(wr.roffset,wr.offset);mr<yr?(br=br.subarray(0,mr),wr.roffset+=mr):gr++,fr.set(br);break}else{var br=wr.buffer.subarray(wr.roffset,wr.offset);fr.set(br),fr=fr.subarray(br.byteLength),mr-=br.byteLength,gr++}}return gr&&gr==ir.buckets.length&&(gr--,ir.buckets[gr].offset=0,ir.buckets[gr].roffset=0),ir.buckets.splice(0,gr),_r},write(r,e,M,tr,rr){var ir=r.node.pipe,lr=e.subarray(M,M+tr),dr=lr.byteLength;if(dr<=0)return 0;var hr=null;ir.buckets.length==0?(hr={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:0,roffset:0},ir.buckets.push(hr)):hr=ir.buckets[ir.buckets.length-1],assert(hr.offset<=PIPEFS.BUCKET_BUFFER_SIZE);var fr=PIPEFS.BUCKET_BUFFER_SIZE-hr.offset;if(fr>=dr)return hr.buffer.set(lr,hr.offset),hr.offset+=dr,dr;fr>0&&(hr.buffer.set(lr.subarray(0,fr),hr.offset),hr.offset+=fr,lr=lr.subarray(fr,lr.byteLength));for(var mr=lr.byteLength/PIPEFS.BUCKET_BUFFER_SIZE|0,_r=lr.byteLength%PIPEFS.BUCKET_BUFFER_SIZE,gr=0;gr<mr;gr++){var wr={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:PIPEFS.BUCKET_BUFFER_SIZE,roffset:0};ir.buckets.push(wr),wr.buffer.set(lr.subarray(0,PIPEFS.BUCKET_BUFFER_SIZE)),lr=lr.subarray(PIPEFS.BUCKET_BUFFER_SIZE,lr.byteLength)}if(_r>0){var wr={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:lr.byteLength,roffset:0};ir.buckets.push(wr),wr.buffer.set(lr)}return dr},close(r){var e=r.node.pipe;e.refcnt--,e.refcnt===0&&(e.buckets=null)}},nextname(){return PIPEFS.nextname.current||(PIPEFS.nextname.current=0),"pipe["+PIPEFS.nextname.current+++"]"}};function ___syscall_pipe(r){try{if(r==0)throw new FS.ErrnoError(21);var e=PIPEFS.createPipe();return HEAP32[r>>2]=e.readable_fd,HEAP32[r+4>>2]=e.writable_fd,0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_pipe.sig="ip";function ___syscall_readlinkat(r,e,M,tr){try{if(e=SYSCALLS.getStr(e),e=SYSCALLS.calculateAt(r,e),tr<=0)return-28;var rr=FS.readlink(e),ir=Math.min(tr,lengthBytesUTF8(rr)),lr=HEAP8[M+ir];return stringToUTF8(rr,M,tr+1),HEAP8[M+ir]=lr,ir}catch(dr){if(typeof FS>"u"||dr.name!=="ErrnoError")throw dr;return-dr.errno}}___syscall_readlinkat.sig="iippp";var writeSockaddr=(r,e,M,tr,rr)=>{switch(e){case 2:M=inetPton4(M),zeroMemory(r,16),rr&&(HEAP32[rr>>2]=16),HEAP16[r>>1]=e,HEAP32[r+4>>2]=M,HEAP16[r+2>>1]=_htons(tr);break;case 10:M=inetPton6(M),zeroMemory(r,28),rr&&(HEAP32[rr>>2]=28),HEAP32[r>>2]=e,HEAP32[r+8>>2]=M[0],HEAP32[r+12>>2]=M[1],HEAP32[r+16>>2]=M[2],HEAP32[r+20>>2]=M[3],HEAP16[r+2>>1]=_htons(tr);break;default:return 5}return 0};function ___syscall_recvfrom(r,e,M,tr,rr,ir){try{var lr=getSocketFromFD(r),dr=lr.sock_ops.recvmsg(lr,M);if(!dr)return 0;if(rr)var hr=writeSockaddr(rr,lr.family,DNS.lookup_name(dr.addr),dr.port,ir);return HEAPU8.set(dr.buffer,e),dr.buffer.byteLength}catch(fr){if(typeof FS>"u"||fr.name!=="ErrnoError")throw fr;return-fr.errno}}___syscall_recvfrom.sig="iippipp";function ___syscall_renameat(r,e,M,tr){try{return e=SYSCALLS.getStr(e),tr=SYSCALLS.getStr(tr),e=SYSCALLS.calculateAt(r,e),tr=SYSCALLS.calculateAt(M,tr),FS.rename(e,tr),0}catch(rr){if(typeof FS>"u"||rr.name!=="ErrnoError")throw rr;return-rr.errno}}___syscall_renameat.sig="iipip";function ___syscall_rmdir(r){try{return r=SYSCALLS.getStr(r),FS.rmdir(r),0}catch(e){if(typeof FS>"u"||e.name!=="ErrnoError")throw e;return-e.errno}}___syscall_rmdir.sig="ip";function ___syscall_sendto(r,e,M,tr,rr,ir){try{var lr=getSocketFromFD(r);if(!rr)return FS.write(lr.stream,HEAP8,e,M);var dr=getSocketAddress(rr,ir);return lr.sock_ops.sendmsg(lr,HEAP8,e,M,dr.addr,dr.port)}catch(hr){if(typeof FS>"u"||hr.name!=="ErrnoError")throw hr;return-hr.errno}}___syscall_sendto.sig="iippipp";function ___syscall_socket(r,e,M){try{var tr=SOCKFS.createSocket(r,e,M);return tr.stream.fd}catch(rr){if(typeof FS>"u"||rr.name!=="ErrnoError")throw rr;return-rr.errno}}___syscall_socket.sig="iiiiiii";function ___syscall_stat64(r,e){try{return r=SYSCALLS.getStr(r),SYSCALLS.doStat(FS.stat,r,e)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_stat64.sig="ipp";function ___syscall_symlinkat(r,e,M){try{return r=SYSCALLS.getStr(r),M=SYSCALLS.getStr(M),M=SYSCALLS.calculateAt(e,M),FS.symlink(r,M),0}catch(tr){if(typeof FS>"u"||tr.name!=="ErrnoError")throw tr;return-tr.errno}}___syscall_symlinkat.sig="ipip";function ___syscall_truncate64(r,e){e=bigintToI53Checked(e);try{return isNaN(e)?61:(r=SYSCALLS.getStr(r),FS.truncate(r,e),0)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_truncate64.sig="ipj";function ___syscall_unlinkat(r,e,M){try{return e=SYSCALLS.getStr(e),e=SYSCALLS.calculateAt(r,e),M===0?FS.unlink(e):M===512?FS.rmdir(e):abort("Invalid flags passed to unlinkat"),0}catch(tr){if(typeof FS>"u"||tr.name!=="ErrnoError")throw tr;return-tr.errno}}___syscall_unlinkat.sig="iipi";var ___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1);Module.___table_base=___table_base;var __abort_js=()=>abort("");__abort_js.sig="v";var ENV={},stackAlloc=r=>__emscripten_stack_alloc(r),stringToUTF8OnStack=r=>{var e=lengthBytesUTF8(r)+1,M=stackAlloc(e);return stringToUTF8(r,M,e),M},dlSetError=r=>{var e=stackSave(),M=stringToUTF8OnStack(r);___dl_seterr(M,0),stackRestore(e)},dlopenInternal=(r,e)=>{var M=UTF8ToString(r+36),tr=HEAP32[r+4>>2];M=PATH.normalize(M);var rr=!!(tr&256),ir=rr?null:{},lr={global:rr,nodelete:!!(tr&4096),loadAsync:e.loadAsync};try{return loadDynamicLibrary(M,lr,ir,r)}catch(dr){return dlSetError(`Could not load dynamic lib: ${M}
11
+ ${dr}`),0}},__dlopen_js=r=>dlopenInternal(r,{loadAsync:!1});__dlopen_js.sig="pp";var __dlsym_js=(r,e,M)=>{e=UTF8ToString(e);var tr,rr,ir=LDSO.loadedLibsByHandle[r];if(!ir.exports.hasOwnProperty(e)||ir.exports[e].stub)return dlSetError(`Tried to lookup unknown symbol "${e}" in dynamic lib: ${ir.name}`),0;if(rr=Object.keys(ir.exports).indexOf(e),tr=ir.exports[e],typeof tr=="function"){var lr=getFunctionAddress(tr);lr?tr=lr:(tr=addFunction(tr,tr.sig),HEAPU32[M>>2]=rr)}return tr};__dlsym_js.sig="pppp";var __emscripten_memcpy_js=(r,e,M)=>HEAPU8.copyWithin(r,e,e+M);__emscripten_memcpy_js.sig="vppp";var runtimeKeepaliveCounter=0,__emscripten_runtime_keepalive_clear=()=>{noExitRuntime=!1,runtimeKeepaliveCounter=0};__emscripten_runtime_keepalive_clear.sig="v";var __emscripten_system=r=>{if(ENVIRONMENT_IS_NODE){if(!r)return 1;var e=UTF8ToString(r);if(!e.length)return 0;var M=require("child_process"),tr=M.spawnSync(e,[],{shell:!0,stdio:"inherit"}),rr=(lr,dr)=>lr<<8|dr;if(tr.status===null){var ir=lr=>{switch(lr){case"SIGHUP":return 1;case"SIGQUIT":return 3;case"SIGFPE":return 8;case"SIGKILL":return 9;case"SIGALRM":return 14;case"SIGTERM":return 15;default:return 2}};return rr(0,ir(tr.signal))}return rr(tr.status,0)}return r?-52:0};__emscripten_system.sig="ip";var __emscripten_throw_longjmp=()=>{throw 1/0};__emscripten_throw_longjmp.sig="v";function __gmtime_js(r,e){r=bigintToI53Checked(r);var M=new Date(r*1e3);HEAP32[e>>2]=M.getUTCSeconds(),HEAP32[e+4>>2]=M.getUTCMinutes(),HEAP32[e+8>>2]=M.getUTCHours(),HEAP32[e+12>>2]=M.getUTCDate(),HEAP32[e+16>>2]=M.getUTCMonth(),HEAP32[e+20>>2]=M.getUTCFullYear()-1900,HEAP32[e+24>>2]=M.getUTCDay();var tr=Date.UTC(M.getUTCFullYear(),0,1,0,0,0,0),rr=(M.getTime()-tr)/(1e3*60*60*24)|0;HEAP32[e+28>>2]=rr}__gmtime_js.sig="vjp";var isLeapYear=r=>r%4===0&&(r%100!==0||r%400===0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=r=>{var e=isLeapYear(r.getFullYear()),M=e?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE,tr=M[r.getMonth()]+r.getDate()-1;return tr};function __localtime_js(r,e){r=bigintToI53Checked(r);var M=new Date(r*1e3);HEAP32[e>>2]=M.getSeconds(),HEAP32[e+4>>2]=M.getMinutes(),HEAP32[e+8>>2]=M.getHours(),HEAP32[e+12>>2]=M.getDate(),HEAP32[e+16>>2]=M.getMonth(),HEAP32[e+20>>2]=M.getFullYear()-1900,HEAP32[e+24>>2]=M.getDay();var tr=ydayFromDate(M)|0;HEAP32[e+28>>2]=tr,HEAP32[e+36>>2]=-(M.getTimezoneOffset()*60);var rr=new Date(M.getFullYear(),0,1),ir=new Date(M.getFullYear(),6,1).getTimezoneOffset(),lr=rr.getTimezoneOffset(),dr=(ir!=lr&&M.getTimezoneOffset()==Math.min(lr,ir))|0;HEAP32[e+32>>2]=dr}__localtime_js.sig="vjp";function __mmap_js(r,e,M,tr,rr,ir,lr){rr=bigintToI53Checked(rr);try{if(isNaN(rr))return 61;var dr=SYSCALLS.getStreamFromFD(tr),hr=FS.mmap(dr,r,rr,e,M),fr=hr.ptr;return HEAP32[ir>>2]=hr.allocated,HEAPU32[lr>>2]=fr,0}catch(mr){if(typeof FS>"u"||mr.name!=="ErrnoError")throw mr;return-mr.errno}}__mmap_js.sig="ipiiijpp";function __munmap_js(r,e,M,tr,rr,ir){ir=bigintToI53Checked(ir);try{var lr=SYSCALLS.getStreamFromFD(rr);M&2&&SYSCALLS.doMsync(r,lr,e,tr,ir)}catch(dr){if(typeof FS>"u"||dr.name!=="ErrnoError")throw dr;return-dr.errno}}__munmap_js.sig="ippiiij";var timers={},handleException=r=>{if(r instanceof ExitStatus||r=="unwind")return EXITSTATUS;quit_(1,r)},keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0,_proc_exit=r=>{EXITSTATUS=r,keepRuntimeAlive()||(Module.onExit?.(r),ABORT=!0),quit_(r,new ExitStatus(r))};_proc_exit.sig="vi";var exitJS=(r,e)=>{EXITSTATUS=r,_proc_exit(r)},_exit=exitJS;_exit.sig="vi";var maybeExit=()=>{if(!keepRuntimeAlive())try{_exit(EXITSTATUS)}catch(r){handleException(r)}},callUserCallback=r=>{if(!ABORT)try{r(),maybeExit()}catch(e){handleException(e)}},_emscripten_get_now=()=>performance.now();_emscripten_get_now.sig="d";var __setitimer_js=(r,e)=>{if(timers[r]&&(clearTimeout(timers[r].id),delete timers[r]),!e)return 0;var M=setTimeout(()=>{delete timers[r],callUserCallback(()=>__emscripten_timeout(r,_emscripten_get_now()))},e);return timers[r]={id:M,timeout_ms:e},0};__setitimer_js.sig="iid";var __tzset_js=(r,e,M,tr)=>{var rr=new Date().getFullYear(),ir=new Date(rr,0,1),lr=new Date(rr,6,1),dr=ir.getTimezoneOffset(),hr=lr.getTimezoneOffset(),fr=Math.max(dr,hr);HEAPU32[r>>2]=fr*60,HEAP32[e>>2]=+(dr!=hr);var mr=wr=>{var yr=wr>=0?"-":"+",br=Math.abs(wr),Mr=String(Math.floor(br/60)).padStart(2,"0"),vr=String(br%60).padStart(2,"0");return`UTC${yr}${Mr}${vr}`},_r=mr(dr),gr=mr(hr);hr<dr?(stringToUTF8(_r,M,17),stringToUTF8(gr,tr,17)):(stringToUTF8(_r,tr,17),stringToUTF8(gr,M,17))};__tzset_js.sig="vpppp";var _emscripten_date_now=()=>Date.now();_emscripten_date_now.sig="d";var checkWasiClock=r=>r>=0&&r<=3;function _clock_time_get(r,e,M){if(!checkWasiClock(r))return 28;var tr;r===0?tr=_emscripten_date_now():tr=_emscripten_get_now();var rr=Math.round(tr*1e3*1e3);return HEAP64[M>>3]=BigInt(rr),0}_clock_time_get.sig="iijp";var readEmAsmArgsArray=[],readEmAsmArgs=(r,e)=>{readEmAsmArgsArray.length=0;for(var M;M=HEAPU8[r++];){var tr=M!=105;tr&=M!=112,e+=tr&&e%8?4:0,readEmAsmArgsArray.push(M==112?HEAPU32[e>>2]:M==106?HEAP64[e>>3]:M==105?HEAP32[e>>2]:HEAPF64[e>>3]),e+=tr?8:4}return readEmAsmArgsArray},runEmAsmFunction=(r,e,M)=>{var tr=readEmAsmArgs(e,M);return ASM_CONSTS[r](...tr)},_emscripten_asm_const_int=(r,e,M)=>runEmAsmFunction(r,e,M);_emscripten_asm_const_int.sig="ippp";var _emscripten_force_exit=r=>{__emscripten_runtime_keepalive_clear(),_exit(r)};_emscripten_force_exit.sig="vi";var getHeapMax=()=>2147483648,growMemory=r=>{var e=wasmMemory.buffer,M=(r-e.byteLength+65535)/65536|0;try{return wasmMemory.grow(M),updateMemoryViews(),1}catch{}},_emscripten_resize_heap=r=>{var e=HEAPU8.length;r>>>=0;var M=getHeapMax();if(r>M)return!1;for(var tr=1;tr<=4;tr*=2){var rr=e*(1+.2/tr);rr=Math.min(rr,r+100663296);var ir=Math.min(M,alignMemory(Math.max(r,rr),65536)),lr=growMemory(ir);if(lr)return!0}return!1};_emscripten_resize_heap.sig="ip";var getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var r=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:r,_:getExecutableName()};for(var M in ENV)ENV[M]===void 0?delete e[M]:e[M]=ENV[M];var tr=[];for(var M in e)tr.push(`${M}=${e[M]}`);getEnvStrings.strings=tr}return getEnvStrings.strings},stringToAscii=(r,e)=>{for(var M=0;M<r.length;++M)HEAP8[e++]=r.charCodeAt(M);HEAP8[e]=0},_environ_get=(r,e)=>{var M=0;return getEnvStrings().forEach((tr,rr)=>{var ir=e+M;HEAPU32[r+rr*4>>2]=ir,stringToAscii(tr,ir),M+=tr.length+1}),0};_environ_get.sig="ipp";var _environ_sizes_get=(r,e)=>{var M=getEnvStrings();HEAPU32[r>>2]=M.length;var tr=0;return M.forEach(rr=>tr+=rr.length+1),HEAPU32[e>>2]=tr,0};_environ_sizes_get.sig="ipp";function _fd_close(r){try{var e=SYSCALLS.getStreamFromFD(r);return FS.close(e),0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return M.errno}}_fd_close.sig="ii";function _fd_fdstat_get(r,e){try{var M=0,tr=0,rr=0,ir=SYSCALLS.getStreamFromFD(r),lr=ir.tty?2:FS.isDir(ir.mode)?3:FS.isLink(ir.mode)?7:4;return HEAP8[e]=lr,HEAP16[e+2>>1]=rr,HEAP64[e+8>>3]=BigInt(M),HEAP64[e+16>>3]=BigInt(tr),0}catch(dr){if(typeof FS>"u"||dr.name!=="ErrnoError")throw dr;return dr.errno}}_fd_fdstat_get.sig="iip";var doReadv=(r,e,M,tr)=>{for(var rr=0,ir=0;ir<M;ir++){var lr=HEAPU32[e>>2],dr=HEAPU32[e+4>>2];e+=8;var hr=FS.read(r,HEAP8,lr,dr,tr);if(hr<0)return-1;if(rr+=hr,hr<dr)break;typeof tr<"u"&&(tr+=hr)}return rr};function _fd_pread(r,e,M,tr,rr){tr=bigintToI53Checked(tr);try{if(isNaN(tr))return 61;var ir=SYSCALLS.getStreamFromFD(r),lr=doReadv(ir,e,M,tr);return HEAPU32[rr>>2]=lr,0}catch(dr){if(typeof FS>"u"||dr.name!=="ErrnoError")throw dr;return dr.errno}}_fd_pread.sig="iippjp";var doWritev=(r,e,M,tr)=>{for(var rr=0,ir=0;ir<M;ir++){var lr=HEAPU32[e>>2],dr=HEAPU32[e+4>>2];e+=8;var hr=FS.write(r,HEAP8,lr,dr,tr);if(hr<0)return-1;if(rr+=hr,hr<dr)break;typeof tr<"u"&&(tr+=hr)}return rr};function _fd_pwrite(r,e,M,tr,rr){tr=bigintToI53Checked(tr);try{if(isNaN(tr))return 61;var ir=SYSCALLS.getStreamFromFD(r),lr=doWritev(ir,e,M,tr);return HEAPU32[rr>>2]=lr,0}catch(dr){if(typeof FS>"u"||dr.name!=="ErrnoError")throw dr;return dr.errno}}_fd_pwrite.sig="iippjp";function _fd_read(r,e,M,tr){try{var rr=SYSCALLS.getStreamFromFD(r),ir=doReadv(rr,e,M);return HEAPU32[tr>>2]=ir,0}catch(lr){if(typeof FS>"u"||lr.name!=="ErrnoError")throw lr;return lr.errno}}_fd_read.sig="iippp";function _fd_seek(r,e,M,tr){e=bigintToI53Checked(e);try{if(isNaN(e))return 61;var rr=SYSCALLS.getStreamFromFD(r);return FS.llseek(rr,e,M),HEAP64[tr>>3]=BigInt(rr.position),rr.getdents&&e===0&&M===0&&(rr.getdents=null),0}catch(ir){if(typeof FS>"u"||ir.name!=="ErrnoError")throw ir;return ir.errno}}_fd_seek.sig="iijip";function _fd_sync(r){try{var e=SYSCALLS.getStreamFromFD(r);return e.stream_ops?.fsync?e.stream_ops.fsync(e):0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return M.errno}}_fd_sync.sig="ii";function _fd_write(r,e,M,tr){try{var rr=SYSCALLS.getStreamFromFD(r),ir=doWritev(rr,e,M);return HEAPU32[tr>>2]=ir,0}catch(lr){if(typeof FS>"u"||lr.name!=="ErrnoError")throw lr;return lr.errno}}_fd_write.sig="iippp";var _getaddrinfo=(r,e,M,tr)=>{var rr=0,ir=0,lr=0,dr=0,hr=0,fr=0,mr;function _r(gr,wr,yr,br,Mr,vr){var Sr,xr,Ar,Dr;return xr=gr===10?28:16,Mr=gr===10?inetNtop6(Mr):inetNtop4(Mr),Sr=_malloc(xr),Dr=writeSockaddr(Sr,gr,Mr,vr),assert(!Dr),Ar=_malloc(32),HEAP32[Ar+4>>2]=gr,HEAP32[Ar+8>>2]=wr,HEAP32[Ar+12>>2]=yr,HEAPU32[Ar+24>>2]=br,HEAPU32[Ar+20>>2]=Sr,gr===10?HEAP32[Ar+16>>2]=28:HEAP32[Ar+16>>2]=16,HEAP32[Ar+28>>2]=0,Ar}if(M&&(lr=HEAP32[M>>2],dr=HEAP32[M+4>>2],hr=HEAP32[M+8>>2],fr=HEAP32[M+12>>2]),hr&&!fr&&(fr=hr===2?17:6),!hr&&fr&&(hr=fr===17?2:1),fr===0&&(fr=6),hr===0&&(hr=1),!r&&!e)return-2;if(lr&-1088||M!==0&&HEAP32[M>>2]&2&&!r)return-1;if(lr&32)return-2;if(hr!==0&&hr!==1&&hr!==2)return-7;if(dr!==0&&dr!==2&&dr!==10)return-6;if(e&&(e=UTF8ToString(e),ir=parseInt(e,10),isNaN(ir)))return lr&1024?-2:-8;if(!r)return dr===0&&(dr=2),lr&1||(dr===2?rr=_htonl(2130706433):rr=[0,0,0,_htonl(1)]),mr=_r(dr,hr,fr,null,rr,ir),HEAPU32[tr>>2]=mr,0;if(r=UTF8ToString(r),rr=inetPton4(r),rr!==null)if(dr===0||dr===2)dr=2;else if(dr===10&&lr&8)rr=[0,0,_htonl(65535),rr],dr=10;else return-2;else if(rr=inetPton6(r),rr!==null)if(dr===0||dr===10)dr=10;else return-2;return rr!=null?(mr=_r(dr,hr,fr,r,rr,ir),HEAPU32[tr>>2]=mr,0):lr&4?-2:(r=DNS.lookup_name(r),rr=inetPton4(r),dr===0?dr=2:dr===10&&(rr=[0,0,_htonl(65535),rr]),mr=_r(dr,hr,fr,null,rr,ir),HEAPU32[tr>>2]=mr,0)};_getaddrinfo.sig="ipppp";var _getnameinfo=(r,e,M,tr,rr,ir,lr)=>{var dr=readSockaddr(r,e);if(dr.errno)return-6;var hr=dr.port,fr=dr.addr,mr=!1;if(M&&tr){var _r;if(lr&1||!(_r=DNS.lookup_addr(fr))){if(lr&8)return-2}else fr=_r;var gr=stringToUTF8(fr,M,tr);gr+1>=tr&&(mr=!0)}if(rr&&ir){hr=""+hr;var gr=stringToUTF8(hr,rr,ir);gr+1>=ir&&(mr=!0)}return mr?-12:0};_getnameinfo.sig="ipipipii";var stringToNewUTF8=r=>{var e=lengthBytesUTF8(r)+1,M=_malloc(e);return M&&stringToUTF8(r,M,e),M},removeFunction=r=>{functionsInTableMap.delete(getWasmTableEntry(r)),setWasmTableEntry(r,null),freeTableIndexes.push(r)},FS_createPath=FS.createPath,FS_unlink=r=>FS.unlink(r),FS_createLazyFile=FS.createLazyFile,FS_createDevice=FS.createDevice,setTempRet0=r=>__emscripten_tempret_set(r),_setTempRet0=setTempRet0;Module._setTempRet0=_setTempRet0;var getTempRet0=r=>__emscripten_tempret_get(),_getTempRet0=getTempRet0;Module._getTempRet0=_getTempRet0,registerWasmPlugin(),FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit(),Module.FS_createPath=FS.createPath,Module.FS_createDataFile=FS.createDataFile,Module.FS_createPreloadedFile=FS.createPreloadedFile,Module.FS_unlink=FS.unlink,Module.FS_createLazyFile=FS.createLazyFile,Module.FS_createDevice=FS.createDevice,MEMFS.doesNotExistError=new FS.ErrnoError(44),MEMFS.doesNotExistError.stack="<generic error, no stack>",ENVIRONMENT_IS_NODE&&NODEFS.staticInit();var wasmImports={__assert_fail:___assert_fail,__call_sighandler:___call_sighandler,__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_pointer:___stack_pointer,__syscall__newselect:___syscall__newselect,__syscall_bind:___syscall_bind,__syscall_chdir:___syscall_chdir,__syscall_chmod:___syscall_chmod,__syscall_dup:___syscall_dup,__syscall_dup3:___syscall_dup3,__syscall_faccessat:___syscall_faccessat,__syscall_fadvise64:___syscall_fadvise64,__syscall_fallocate:___syscall_fallocate,__syscall_fcntl64:___syscall_fcntl64,__syscall_fdatasync:___syscall_fdatasync,__syscall_fstat64:___syscall_fstat64,__syscall_ftruncate64:___syscall_ftruncate64,__syscall_getcwd:___syscall_getcwd,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_pipe:___syscall_pipe,__syscall_readlinkat:___syscall_readlinkat,__syscall_recvfrom:___syscall_recvfrom,__syscall_renameat:___syscall_renameat,__syscall_rmdir:___syscall_rmdir,__syscall_sendto:___syscall_sendto,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_symlinkat:___syscall_symlinkat,__syscall_truncate64:___syscall_truncate64,__syscall_unlinkat:___syscall_unlinkat,__table_base:___table_base,_abort_js:__abort_js,_dlopen_js:__dlopen_js,_dlsym_js:__dlsym_js,_emscripten_memcpy_js:__emscripten_memcpy_js,_emscripten_runtime_keepalive_clear:__emscripten_runtime_keepalive_clear,_emscripten_system:__emscripten_system,_emscripten_throw_longjmp:__emscripten_throw_longjmp,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_mmap_js:__mmap_js,_munmap_js:__munmap_js,_setitimer_js:__setitimer_js,_tzset_js:__tzset_js,clock_time_get:_clock_time_get,emscripten_asm_const_int:_emscripten_asm_const_int,emscripten_date_now:_emscripten_date_now,emscripten_force_exit:_emscripten_force_exit,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,exit:_exit,fd_close:_fd_close,fd_fdstat_get:_fd_fdstat_get,fd_pread:_fd_pread,fd_pwrite:_fd_pwrite,fd_read:_fd_read,fd_seek:_fd_seek,fd_sync:_fd_sync,fd_write:_fd_write,getTempRet0:_getTempRet0,getaddrinfo:_getaddrinfo,getnameinfo:_getnameinfo,invoke_di,invoke_i,invoke_id,invoke_ii,invoke_iii,invoke_iiii,invoke_iiiii,invoke_iiiiii,invoke_iiiiiii,invoke_iiiiiiii,invoke_iiiiiiiii,invoke_iiiiiiiiii,invoke_iiiiiiiiiii,invoke_iiiiiiiiiiiiii,invoke_iiiiiiiiiiiiiiiiii,invoke_iiiiiji,invoke_iiiij,invoke_iiiijii,invoke_iiij,invoke_iiji,invoke_ij,invoke_ijiiiii,invoke_ijiiiiii,invoke_j,invoke_ji,invoke_jii,invoke_jiiii,invoke_jiiiiii,invoke_jiiiiiiiii,invoke_v,invoke_vi,invoke_vid,invoke_vii,invoke_viii,invoke_viiii,invoke_viiiii,invoke_viiiiii,invoke_viiiiiii,invoke_viiiiiiii,invoke_viiiiiiiii,invoke_viiiiiiiiiiii,invoke_viiiji,invoke_viij,invoke_viiji,invoke_viijii,invoke_viijiiii,invoke_vij,invoke_viji,invoke_vijiji,invoke_vj,invoke_vji,memory:wasmMemory,proc_exit:_proc_exit,setTempRet0:_setTempRet0},wasmExports;createWasm(),Module._fopen=(r,e)=>(Module._fopen=wasmExports.fopen)(r,e);var _fflush=Module._fflush=r=>(_fflush=Module._fflush=wasmExports.fflush)(r);Module.___errno_location=()=>(Module.___errno_location=wasmExports.__errno_location)(),Module._ProcessInterrupts=()=>(Module._ProcessInterrupts=wasmExports.ProcessInterrupts)(),Module._errstart_cold=(r,e)=>(Module._errstart_cold=wasmExports.errstart_cold)(r,e),Module._errcode=r=>(Module._errcode=wasmExports.errcode)(r),Module._errmsg=(r,e)=>(Module._errmsg=wasmExports.errmsg)(r,e),Module._errfinish=(r,e,M)=>(Module._errfinish=wasmExports.errfinish)(r,e,M),Module._puts=r=>(Module._puts=wasmExports.puts)(r),Module._errstart=(r,e)=>(Module._errstart=wasmExports.errstart)(r,e),Module._errmsg_internal=(r,e)=>(Module._errmsg_internal=wasmExports.errmsg_internal)(r,e),Module._errdetail=(r,e)=>(Module._errdetail=wasmExports.errdetail)(r,e),Module._errhint=(r,e)=>(Module._errhint=wasmExports.errhint)(r,e),Module._pg_parse_query=r=>(Module._pg_parse_query=wasmExports.pg_parse_query)(r),Module._gettimeofday=(r,e)=>(Module._gettimeofday=wasmExports.gettimeofday)(r,e),Module._raw_parser=(r,e)=>(Module._raw_parser=wasmExports.raw_parser)(r,e),Module._initStringInfo=r=>(Module._initStringInfo=wasmExports.initStringInfo)(r),Module._appendStringInfoString=(r,e)=>(Module._appendStringInfoString=wasmExports.appendStringInfoString)(r,e),Module._appendStringInfo=(r,e,M)=>(Module._appendStringInfo=wasmExports.appendStringInfo)(r,e,M),Module._errdetail_internal=(r,e)=>(Module._errdetail_internal=wasmExports.errdetail_internal)(r,e),Module._pfree=r=>(Module._pfree=wasmExports.pfree)(r),Module._list_make1_impl=(r,e)=>(Module._list_make1_impl=wasmExports.list_make1_impl)(r,e),Module._QueryRewrite=r=>(Module._QueryRewrite=wasmExports.QueryRewrite)(r),Module._pg_plan_query=(r,e,M,tr)=>(Module._pg_plan_query=wasmExports.pg_plan_query)(r,e,M,tr),Module._palloc0=r=>(Module._palloc0=wasmExports.palloc0)(r),Module._lappend=(r,e)=>(Module._lappend=wasmExports.lappend)(r,e),Module._GetCurrentTimestamp=()=>(Module._GetCurrentTimestamp=wasmExports.GetCurrentTimestamp)(),Module._pg_prng_double=r=>(Module._pg_prng_double=wasmExports.pg_prng_double)(r),Module._pg_snprintf=(r,e,M,tr)=>(Module._pg_snprintf=wasmExports.pg_snprintf)(r,e,M,tr),Module._die=r=>(Module._die=wasmExports.die)(r),Module._check_stack_depth=()=>(Module._check_stack_depth=wasmExports.check_stack_depth)(),Module._pre_format_elog_string=(r,e)=>(Module._pre_format_elog_string=wasmExports.pre_format_elog_string)(r,e),Module._format_elog_string=(r,e)=>(Module._format_elog_string=wasmExports.format_elog_string)(r,e),Module._pstrdup=r=>(Module._pstrdup=wasmExports.pstrdup)(r),Module._SplitIdentifierString=(r,e,M)=>(Module._SplitIdentifierString=wasmExports.SplitIdentifierString)(r,e,M),Module._list_free=r=>(Module._list_free=wasmExports.list_free)(r),Module._pg_strcasecmp=(r,e)=>(Module._pg_strcasecmp=wasmExports.pg_strcasecmp)(r,e),Module._guc_malloc=(r,e)=>(Module._guc_malloc=wasmExports.guc_malloc)(r,e),Module._SetConfigOption=(r,e,M,tr)=>(Module._SetConfigOption=wasmExports.SetConfigOption)(r,e,M,tr),Module._pg_sprintf=(r,e,M)=>(Module._pg_sprintf=wasmExports.pg_sprintf)(r,e,M),Module._strcmp=(r,e)=>(Module._strcmp=wasmExports.strcmp)(r,e),Module._strdup=r=>(Module._strdup=wasmExports.strdup)(r),Module._atoi=r=>(Module._atoi=wasmExports.atoi)(r),Module._strlcpy=(r,e,M)=>(Module._strlcpy=wasmExports.strlcpy)(r,e,M),Module._pgl_shutdown=()=>(Module._pgl_shutdown=wasmExports.pgl_shutdown)(),Module._pgl_closed=()=>(Module._pgl_closed=wasmExports.pgl_closed)(),Module._MemoryContextReset=r=>(Module._MemoryContextReset=wasmExports.MemoryContextReset)(r),Module._resetStringInfo=r=>(Module._resetStringInfo=wasmExports.resetStringInfo)(r),Module._getc=r=>(Module._getc=wasmExports.getc)(r),Module._appendStringInfoChar=(r,e)=>(Module._appendStringInfoChar=wasmExports.appendStringInfoChar)(r,e),Module._strlen=r=>(Module._strlen=wasmExports.strlen)(r),Module._strncmp=(r,e,M)=>(Module._strncmp=wasmExports.strncmp)(r,e,M),Module._pg_fprintf=(r,e,M)=>(Module._pg_fprintf=wasmExports.pg_fprintf)(r,e,M),Module._pgstat_report_activity=(r,e)=>(Module._pgstat_report_activity=wasmExports.pgstat_report_activity)(r,e),Module._errhidestmt=r=>(Module._errhidestmt=wasmExports.errhidestmt)(r),Module._GetTransactionSnapshot=()=>(Module._GetTransactionSnapshot=wasmExports.GetTransactionSnapshot)(),Module._PushActiveSnapshot=r=>(Module._PushActiveSnapshot=wasmExports.PushActiveSnapshot)(r),Module._AllocSetContextCreateInternal=(r,e,M,tr,rr)=>(Module._AllocSetContextCreateInternal=wasmExports.AllocSetContextCreateInternal)(r,e,M,tr,rr),Module._PopActiveSnapshot=()=>(Module._PopActiveSnapshot=wasmExports.PopActiveSnapshot)(),Module._CreateDestReceiver=r=>(Module._CreateDestReceiver=wasmExports.CreateDestReceiver)(r),Module._CommitTransactionCommand=()=>(Module._CommitTransactionCommand=wasmExports.CommitTransactionCommand)(),Module._CommandCounterIncrement=()=>(Module._CommandCounterIncrement=wasmExports.CommandCounterIncrement)(),Module._MemoryContextDelete=r=>(Module._MemoryContextDelete=wasmExports.MemoryContextDelete)(r),Module._StartTransactionCommand=()=>(Module._StartTransactionCommand=wasmExports.StartTransactionCommand)(),Module.___wasm_setjmp_test=(r,e)=>(Module.___wasm_setjmp_test=wasmExports.__wasm_setjmp_test)(r,e),Module._pg_printf=(r,e)=>(Module._pg_printf=wasmExports.pg_printf)(r,e),Module.___wasm_setjmp=(r,e,M)=>(Module.___wasm_setjmp=wasmExports.__wasm_setjmp)(r,e,M),Module._FlushErrorState=()=>(Module._FlushErrorState=wasmExports.FlushErrorState)(),Module._emscripten_longjmp=(r,e)=>(Module._emscripten_longjmp=wasmExports.emscripten_longjmp)(r,e),Module._enlargeStringInfo=(r,e)=>(Module._enlargeStringInfo=wasmExports.enlargeStringInfo)(r,e);var _malloc=Module._malloc=r=>(_malloc=Module._malloc=wasmExports.malloc)(r);Module._realloc=(r,e)=>(Module._realloc=wasmExports.realloc)(r,e),Module._getenv=r=>(Module._getenv=wasmExports.getenv)(r),Module._strspn=(r,e)=>(Module._strspn=wasmExports.strspn)(r,e),Module._memcpy=(r,e,M)=>(Module._memcpy=wasmExports.memcpy)(r,e,M),Module._fileno=r=>(Module._fileno=wasmExports.fileno)(r),Module._strchr=(r,e)=>(Module._strchr=wasmExports.strchr)(r,e),Module._free=r=>(Module._free=wasmExports.free)(r),Module._pg_vsnprintf=(r,e,M,tr)=>(Module._pg_vsnprintf=wasmExports.pg_vsnprintf)(r,e,M,tr),Module._strcpy=(r,e)=>(Module._strcpy=wasmExports.strcpy)(r,e),Module._psprintf=(r,e)=>(Module._psprintf=wasmExports.psprintf)(r,e),Module._stat=(r,e)=>(Module._stat=wasmExports.stat)(r,e),Module._fwrite=(r,e,M,tr)=>(Module._fwrite=wasmExports.fwrite)(r,e,M,tr),Module._strftime=(r,e,M,tr)=>(Module._strftime=wasmExports.strftime)(r,e,M,tr),Module._strstr=(r,e)=>(Module._strstr=wasmExports.strstr)(r,e),Module._atexit=r=>(Module._atexit=wasmExports.atexit)(r),Module._strtol=(r,e,M)=>(Module._strtol=wasmExports.strtol)(r,e,M),Module._ferror=r=>(Module._ferror=wasmExports.ferror)(r),Module._clear_error=()=>(Module._clear_error=wasmExports.clear_error)(),Module._interactive_one=(r,e)=>(Module._interactive_one=wasmExports.interactive_one)(r,e),Module._pq_getmsgint=(r,e)=>(Module._pq_getmsgint=wasmExports.pq_getmsgint)(r,e),Module._palloc=r=>(Module._palloc=wasmExports.palloc)(r),Module._makeParamList=r=>(Module._makeParamList=wasmExports.makeParamList)(r),Module._getTypeInputInfo=(r,e,M)=>(Module._getTypeInputInfo=wasmExports.getTypeInputInfo)(r,e,M),Module._pnstrdup=(r,e)=>(Module._pnstrdup=wasmExports.pnstrdup)(r,e),Module._MemoryContextSetParent=(r,e)=>(Module._MemoryContextSetParent=wasmExports.MemoryContextSetParent)(r,e),Module._pgl_backend=()=>(Module._pgl_backend=wasmExports.pgl_backend)(),Module._pgl_initdb=()=>(Module._pgl_initdb=wasmExports.pgl_initdb)(),Module._main=(r,e)=>(Module._main=wasmExports.__main_argc_argv)(r,e),Module._appendStringInfoStringQuoted=(r,e,M)=>(Module._appendStringInfoStringQuoted=wasmExports.appendStringInfoStringQuoted)(r,e,M),Module._set_errcontext_domain=r=>(Module._set_errcontext_domain=wasmExports.set_errcontext_domain)(r),Module._errcontext_msg=(r,e)=>(Module._errcontext_msg=wasmExports.errcontext_msg)(r,e),Module._pg_is_ascii=r=>(Module._pg_is_ascii=wasmExports.pg_is_ascii)(r),Module._memchr=(r,e,M)=>(Module._memchr=wasmExports.memchr)(r,e,M),Module._strrchr=(r,e)=>(Module._strrchr=wasmExports.strrchr)(r,e),Module._xsltFreeStylesheet=r=>(Module._xsltFreeStylesheet=wasmExports.xsltFreeStylesheet)(r),Module._xsltParseStylesheetDoc=r=>(Module._xsltParseStylesheetDoc=wasmExports.xsltParseStylesheetDoc)(r),Module._xsltSaveResultToString=(r,e,M,tr)=>(Module._xsltSaveResultToString=wasmExports.xsltSaveResultToString)(r,e,M,tr),Module._xsltCleanupGlobals=()=>(Module._xsltCleanupGlobals=wasmExports.xsltCleanupGlobals)(),Module._xsltNewTransformContext=(r,e)=>(Module._xsltNewTransformContext=wasmExports.xsltNewTransformContext)(r,e),Module._xsltFreeTransformContext=r=>(Module._xsltFreeTransformContext=wasmExports.xsltFreeTransformContext)(r),Module._xsltApplyStylesheetUser=(r,e,M,tr,rr,ir)=>(Module._xsltApplyStylesheetUser=wasmExports.xsltApplyStylesheetUser)(r,e,M,tr,rr,ir),Module._xsltNewSecurityPrefs=()=>(Module._xsltNewSecurityPrefs=wasmExports.xsltNewSecurityPrefs)(),Module._xsltFreeSecurityPrefs=r=>(Module._xsltFreeSecurityPrefs=wasmExports.xsltFreeSecurityPrefs)(r),Module._xsltSetSecurityPrefs=(r,e,M)=>(Module._xsltSetSecurityPrefs=wasmExports.xsltSetSecurityPrefs)(r,e,M),Module._xsltSetCtxtSecurityPrefs=(r,e)=>(Module._xsltSetCtxtSecurityPrefs=wasmExports.xsltSetCtxtSecurityPrefs)(r,e),Module._xsltSecurityForbid=(r,e,M)=>(Module._xsltSecurityForbid=wasmExports.xsltSecurityForbid)(r,e,M),Module._replace_percent_placeholders=(r,e,M,tr)=>(Module._replace_percent_placeholders=wasmExports.replace_percent_placeholders)(r,e,M,tr),Module._memset=(r,e,M)=>(Module._memset=wasmExports.memset)(r,e,M),Module._MemoryContextAllocZero=(r,e)=>(Module._MemoryContextAllocZero=wasmExports.MemoryContextAllocZero)(r,e),Module._MemoryContextAllocExtended=(r,e,M)=>(Module._MemoryContextAllocExtended=wasmExports.MemoryContextAllocExtended)(r,e,M),Module._hash_bytes=(r,e)=>(Module._hash_bytes=wasmExports.hash_bytes)(r,e),Module._memcmp=(r,e,M)=>(Module._memcmp=wasmExports.memcmp)(r,e,M),Module._repalloc=(r,e)=>(Module._repalloc=wasmExports.repalloc)(r,e),Module._pg_qsort=(r,e,M,tr)=>(Module._pg_qsort=wasmExports.pg_qsort)(r,e,M,tr),Module._OpenTransientFile=(r,e)=>(Module._OpenTransientFile=wasmExports.OpenTransientFile)(r,e),Module._errcode_for_file_access=()=>(Module._errcode_for_file_access=wasmExports.errcode_for_file_access)(),Module._read=(r,e,M)=>(Module._read=wasmExports.read)(r,e,M),Module._CloseTransientFile=r=>(Module._CloseTransientFile=wasmExports.CloseTransientFile)(r),Module._time=r=>(Module._time=wasmExports.time)(r),Module._close=r=>(Module._close=wasmExports.close)(r),Module.___multi3=(r,e,M,tr,rr)=>(Module.___multi3=wasmExports.__multi3)(r,e,M,tr,rr),Module._isalnum=r=>(Module._isalnum=wasmExports.isalnum)(r),Module._wait_result_to_str=r=>(Module._wait_result_to_str=wasmExports.wait_result_to_str)(r),Module._float_to_shortest_decimal_bufn=(r,e)=>(Module._float_to_shortest_decimal_bufn=wasmExports.float_to_shortest_decimal_bufn)(r,e),Module._float_to_shortest_decimal_buf=(r,e)=>(Module._float_to_shortest_decimal_buf=wasmExports.float_to_shortest_decimal_buf)(r,e),Module._memmove=(r,e,M)=>(Module._memmove=wasmExports.memmove)(r,e,M),Module._pwrite=(r,e,M,tr)=>(Module._pwrite=wasmExports.pwrite)(r,e,M,tr),Module._hash_bytes_extended=(r,e,M)=>(Module._hash_bytes_extended=wasmExports.hash_bytes_extended)(r,e,M);var _calloc=(r,e)=>(_calloc=wasmExports.calloc)(r,e);Module._IsValidJsonNumber=(r,e)=>(Module._IsValidJsonNumber=wasmExports.IsValidJsonNumber)(r,e),Module._appendBinaryStringInfo=(r,e,M)=>(Module._appendBinaryStringInfo=wasmExports.appendBinaryStringInfo)(r,e,M),Module._makeStringInfo=()=>(Module._makeStringInfo=wasmExports.makeStringInfo)(),Module._GetDatabaseEncodingName=()=>(Module._GetDatabaseEncodingName=wasmExports.GetDatabaseEncodingName)(),Module._ScanKeywordLookup=(r,e)=>(Module._ScanKeywordLookup=wasmExports.ScanKeywordLookup)(r,e),Module._strtoul=(r,e,M)=>(Module._strtoul=wasmExports.strtoul)(r,e,M),Module._sscanf=(r,e,M)=>(Module._sscanf=wasmExports.sscanf)(r,e,M),Module._strtoull=(r,e,M)=>(Module._strtoull=wasmExports.strtoull)(r,e,M),Module._pg_prng_uint64=r=>(Module._pg_prng_uint64=wasmExports.pg_prng_uint64)(r),Module._pg_prng_uint32=r=>(Module._pg_prng_uint32=wasmExports.pg_prng_uint32)(r),Module._log=r=>(Module._log=wasmExports.log)(r),Module._sin=r=>(Module._sin=wasmExports.sin)(r),Module._readdir=r=>(Module._readdir=wasmExports.readdir)(r),Module._forkname_to_number=r=>(Module._forkname_to_number=wasmExports.forkname_to_number)(r),Module._unlink=r=>(Module._unlink=wasmExports.unlink)(r),Module._pg_utf_mblen_private=r=>(Module._pg_utf_mblen_private=wasmExports.pg_utf_mblen_private)(r),Module._bsearch=(r,e,M,tr,rr)=>(Module._bsearch=wasmExports.bsearch)(r,e,M,tr,rr),Module._palloc_extended=(r,e)=>(Module._palloc_extended=wasmExports.palloc_extended)(r,e),Module._appendStringInfoSpaces=(r,e)=>(Module._appendStringInfoSpaces=wasmExports.appendStringInfoSpaces)(r,e),Module._geteuid=()=>(Module._geteuid=wasmExports.geteuid)(),Module._fcntl=(r,e,M)=>(Module._fcntl=wasmExports.fcntl)(r,e,M),Module._pg_popcount_optimized=(r,e)=>(Module._pg_popcount_optimized=wasmExports.pg_popcount_optimized)(r,e),Module._pg_strong_random=(r,e)=>(Module._pg_strong_random=wasmExports.pg_strong_random)(r,e),Module._open=(r,e,M)=>(Module._open=wasmExports.open)(r,e,M),Module._pg_usleep=r=>(Module._pg_usleep=wasmExports.pg_usleep)(r),Module._nanosleep=(r,e)=>(Module._nanosleep=wasmExports.nanosleep)(r,e),Module._getpid=()=>(Module._getpid=wasmExports.getpid)(),Module._qsort_arg=(r,e,M,tr,rr)=>(Module._qsort_arg=wasmExports.qsort_arg)(r,e,M,tr,rr),Module._strerror=r=>(Module._strerror=wasmExports.strerror)(r),Module._RelationGetNumberOfBlocksInFork=(r,e)=>(Module._RelationGetNumberOfBlocksInFork=wasmExports.RelationGetNumberOfBlocksInFork)(r,e),Module._ExtendBufferedRel=(r,e,M,tr)=>(Module._ExtendBufferedRel=wasmExports.ExtendBufferedRel)(r,e,M,tr),Module._MarkBufferDirty=r=>(Module._MarkBufferDirty=wasmExports.MarkBufferDirty)(r),Module._XLogBeginInsert=()=>(Module._XLogBeginInsert=wasmExports.XLogBeginInsert)(),Module._XLogRegisterData=(r,e)=>(Module._XLogRegisterData=wasmExports.XLogRegisterData)(r,e),Module._XLogInsert=(r,e)=>(Module._XLogInsert=wasmExports.XLogInsert)(r,e),Module._UnlockReleaseBuffer=r=>(Module._UnlockReleaseBuffer=wasmExports.UnlockReleaseBuffer)(r),Module._brin_build_desc=r=>(Module._brin_build_desc=wasmExports.brin_build_desc)(r),Module._EnterParallelMode=()=>(Module._EnterParallelMode=wasmExports.EnterParallelMode)(),Module._CreateParallelContext=(r,e,M)=>(Module._CreateParallelContext=wasmExports.CreateParallelContext)(r,e,M),Module._RegisterSnapshot=r=>(Module._RegisterSnapshot=wasmExports.RegisterSnapshot)(r),Module._table_parallelscan_estimate=(r,e)=>(Module._table_parallelscan_estimate=wasmExports.table_parallelscan_estimate)(r,e),Module._add_size=(r,e)=>(Module._add_size=wasmExports.add_size)(r,e),Module._tuplesort_estimate_shared=r=>(Module._tuplesort_estimate_shared=wasmExports.tuplesort_estimate_shared)(r),Module._InitializeParallelDSM=r=>(Module._InitializeParallelDSM=wasmExports.InitializeParallelDSM)(r),Module._UnregisterSnapshot=r=>(Module._UnregisterSnapshot=wasmExports.UnregisterSnapshot)(r),Module._DestroyParallelContext=r=>(Module._DestroyParallelContext=wasmExports.DestroyParallelContext)(r),Module._ExitParallelMode=()=>(Module._ExitParallelMode=wasmExports.ExitParallelMode)(),Module._shm_toc_allocate=(r,e)=>(Module._shm_toc_allocate=wasmExports.shm_toc_allocate)(r,e),Module._ConditionVariableInit=r=>(Module._ConditionVariableInit=wasmExports.ConditionVariableInit)(r),Module._s_init_lock_sema=(r,e)=>(Module._s_init_lock_sema=wasmExports.s_init_lock_sema)(r,e),Module._table_parallelscan_initialize=(r,e,M)=>(Module._table_parallelscan_initialize=wasmExports.table_parallelscan_initialize)(r,e,M),Module._tuplesort_initialize_shared=(r,e,M)=>(Module._tuplesort_initialize_shared=wasmExports.tuplesort_initialize_shared)(r,e,M),Module._shm_toc_insert=(r,e,M)=>(Module._shm_toc_insert=wasmExports.shm_toc_insert)(r,e,M),Module._LaunchParallelWorkers=r=>(Module._LaunchParallelWorkers=wasmExports.LaunchParallelWorkers)(r),Module._WaitForParallelWorkersToAttach=r=>(Module._WaitForParallelWorkersToAttach=wasmExports.WaitForParallelWorkersToAttach)(r),Module._tas_sema=r=>(Module._tas_sema=wasmExports.tas_sema)(r),Module._s_lock=(r,e,M,tr)=>(Module._s_lock=wasmExports.s_lock)(r,e,M,tr),Module._s_unlock_sema=r=>(Module._s_unlock_sema=wasmExports.s_unlock_sema)(r),Module._ConditionVariableSleep=(r,e)=>(Module._ConditionVariableSleep=wasmExports.ConditionVariableSleep)(r,e),Module._ConditionVariableCancelSleep=()=>(Module._ConditionVariableCancelSleep=wasmExports.ConditionVariableCancelSleep)(),Module._tuplesort_performsort=r=>(Module._tuplesort_performsort=wasmExports.tuplesort_performsort)(r),Module._tuplesort_end=r=>(Module._tuplesort_end=wasmExports.tuplesort_end)(r),Module._brin_deform_tuple=(r,e,M)=>(Module._brin_deform_tuple=wasmExports.brin_deform_tuple)(r,e,M),Module._log_newpage_buffer=(r,e)=>(Module._log_newpage_buffer=wasmExports.log_newpage_buffer)(r,e),Module._LockBuffer=(r,e)=>(Module._LockBuffer=wasmExports.LockBuffer)(r,e),Module._ReleaseBuffer=r=>(Module._ReleaseBuffer=wasmExports.ReleaseBuffer)(r),Module._IndexGetRelation=(r,e)=>(Module._IndexGetRelation=wasmExports.IndexGetRelation)(r,e),Module._table_open=(r,e)=>(Module._table_open=wasmExports.table_open)(r,e),Module._ReadBufferExtended=(r,e,M,tr,rr)=>(Module._ReadBufferExtended=wasmExports.ReadBufferExtended)(r,e,M,tr,rr),Module._table_close=(r,e)=>(Module._table_close=wasmExports.table_close)(r,e),Module._build_reloptions=(r,e,M,tr,rr,ir)=>(Module._build_reloptions=wasmExports.build_reloptions)(r,e,M,tr,rr,ir),Module._RelationGetIndexScan=(r,e,M)=>(Module._RelationGetIndexScan=wasmExports.RelationGetIndexScan)(r,e,M),Module._pgstat_assoc_relation=r=>(Module._pgstat_assoc_relation=wasmExports.pgstat_assoc_relation)(r),Module._index_getprocinfo=(r,e,M)=>(Module._index_getprocinfo=wasmExports.index_getprocinfo)(r,e,M),Module._fmgr_info_copy=(r,e,M)=>(Module._fmgr_info_copy=wasmExports.fmgr_info_copy)(r,e,M),Module._FunctionCall4Coll=(r,e,M,tr,rr,ir)=>(Module._FunctionCall4Coll=wasmExports.FunctionCall4Coll)(r,e,M,tr,rr,ir),Module._FunctionCall1Coll=(r,e,M)=>(Module._FunctionCall1Coll=wasmExports.FunctionCall1Coll)(r,e,M),Module._brin_free_desc=r=>(Module._brin_free_desc=wasmExports.brin_free_desc)(r),Module._WaitForParallelWorkersToFinish=r=>(Module._WaitForParallelWorkersToFinish=wasmExports.WaitForParallelWorkersToFinish)(r),Module._PageGetFreeSpace=r=>(Module._PageGetFreeSpace=wasmExports.PageGetFreeSpace)(r),Module._BufferGetBlockNumber=r=>(Module._BufferGetBlockNumber=wasmExports.BufferGetBlockNumber)(r),Module._BuildIndexInfo=r=>(Module._BuildIndexInfo=wasmExports.BuildIndexInfo)(r),Module._Int64GetDatum=r=>(Module._Int64GetDatum=wasmExports.Int64GetDatum)(r),Module._DirectFunctionCall2Coll=(r,e,M,tr)=>(Module._DirectFunctionCall2Coll=wasmExports.DirectFunctionCall2Coll)(r,e,M,tr),Module._RecoveryInProgress=()=>(Module._RecoveryInProgress=wasmExports.RecoveryInProgress)(),Module._GetUserIdAndSecContext=(r,e)=>(Module._GetUserIdAndSecContext=wasmExports.GetUserIdAndSecContext)(r,e),Module._SetUserIdAndSecContext=(r,e)=>(Module._SetUserIdAndSecContext=wasmExports.SetUserIdAndSecContext)(r,e),Module._NewGUCNestLevel=()=>(Module._NewGUCNestLevel=wasmExports.NewGUCNestLevel)(),Module._RestrictSearchPath=()=>(Module._RestrictSearchPath=wasmExports.RestrictSearchPath)(),Module._index_open=(r,e)=>(Module._index_open=wasmExports.index_open)(r,e),Module._object_ownercheck=(r,e,M)=>(Module._object_ownercheck=wasmExports.object_ownercheck)(r,e,M),Module._aclcheck_error=(r,e,M)=>(Module._aclcheck_error=wasmExports.aclcheck_error)(r,e,M),Module._AtEOXact_GUC=(r,e)=>(Module._AtEOXact_GUC=wasmExports.AtEOXact_GUC)(r,e),Module._relation_close=(r,e)=>(Module._relation_close=wasmExports.relation_close)(r,e),Module._GetUserId=()=>(Module._GetUserId=wasmExports.GetUserId)(),Module._ReadBuffer=(r,e)=>(Module._ReadBuffer=wasmExports.ReadBuffer)(r,e),Module._shm_toc_lookup=(r,e,M)=>(Module._shm_toc_lookup=wasmExports.shm_toc_lookup)(r,e,M),Module._tuplesort_attach_shared=(r,e)=>(Module._tuplesort_attach_shared=wasmExports.tuplesort_attach_shared)(r,e),Module._index_close=(r,e)=>(Module._index_close=wasmExports.index_close)(r,e),Module._table_beginscan_parallel=(r,e)=>(Module._table_beginscan_parallel=wasmExports.table_beginscan_parallel)(r,e),Module._ConditionVariableSignal=r=>(Module._ConditionVariableSignal=wasmExports.ConditionVariableSignal)(r),Module._datumCopy=(r,e,M)=>(Module._datumCopy=wasmExports.datumCopy)(r,e,M),Module._lookup_type_cache=(r,e)=>(Module._lookup_type_cache=wasmExports.lookup_type_cache)(r,e),Module._get_fn_opclass_options=r=>(Module._get_fn_opclass_options=wasmExports.get_fn_opclass_options)(r),Module._pg_detoast_datum=r=>(Module._pg_detoast_datum=wasmExports.pg_detoast_datum)(r),Module._index_getprocid=(r,e,M)=>(Module._index_getprocid=wasmExports.index_getprocid)(r,e,M),Module._init_local_reloptions=(r,e)=>(Module._init_local_reloptions=wasmExports.init_local_reloptions)(r,e),Module._FunctionCall2Coll=(r,e,M,tr)=>(Module._FunctionCall2Coll=wasmExports.FunctionCall2Coll)(r,e,M,tr),Module._SysCacheGetAttrNotNull=(r,e,M)=>(Module._SysCacheGetAttrNotNull=wasmExports.SysCacheGetAttrNotNull)(r,e,M),Module._ReleaseSysCache=r=>(Module._ReleaseSysCache=wasmExports.ReleaseSysCache)(r),Module._fmgr_info_cxt=(r,e,M)=>(Module._fmgr_info_cxt=wasmExports.fmgr_info_cxt)(r,e,M),Module._Float8GetDatum=r=>(Module._Float8GetDatum=wasmExports.Float8GetDatum)(r),Module._numeric_sub=r=>(Module._numeric_sub=wasmExports.numeric_sub)(r),Module._DirectFunctionCall1Coll=(r,e,M)=>(Module._DirectFunctionCall1Coll=wasmExports.DirectFunctionCall1Coll)(r,e,M),Module._pg_detoast_datum_packed=r=>(Module._pg_detoast_datum_packed=wasmExports.pg_detoast_datum_packed)(r),Module._add_local_int_reloption=(r,e,M,tr,rr,ir,lr)=>(Module._add_local_int_reloption=wasmExports.add_local_int_reloption)(r,e,M,tr,rr,ir,lr),Module._getTypeOutputInfo=(r,e,M)=>(Module._getTypeOutputInfo=wasmExports.getTypeOutputInfo)(r,e,M),Module._fmgr_info=(r,e)=>(Module._fmgr_info=wasmExports.fmgr_info)(r,e),Module._OutputFunctionCall=(r,e)=>(Module._OutputFunctionCall=wasmExports.OutputFunctionCall)(r,e),Module._cstring_to_text_with_len=(r,e)=>(Module._cstring_to_text_with_len=wasmExports.cstring_to_text_with_len)(r,e),Module._accumArrayResult=(r,e,M,tr,rr)=>(Module._accumArrayResult=wasmExports.accumArrayResult)(r,e,M,tr,rr),Module._makeArrayResult=(r,e)=>(Module._makeArrayResult=wasmExports.makeArrayResult)(r,e),Module._OidOutputFunctionCall=(r,e)=>(Module._OidOutputFunctionCall=wasmExports.OidOutputFunctionCall)(r,e),Module._cstring_to_text=r=>(Module._cstring_to_text=wasmExports.cstring_to_text)(r),Module._PageGetExactFreeSpace=r=>(Module._PageGetExactFreeSpace=wasmExports.PageGetExactFreeSpace)(r),Module._PageIndexTupleOverwrite=(r,e,M,tr)=>(Module._PageIndexTupleOverwrite=wasmExports.PageIndexTupleOverwrite)(r,e,M,tr),Module._PageInit=(r,e,M)=>(Module._PageInit=wasmExports.PageInit)(r,e,M),Module._PageAddItemExtended=(r,e,M,tr,rr)=>(Module._PageAddItemExtended=wasmExports.PageAddItemExtended)(r,e,M,tr,rr),Module._LockRelationForExtension=(r,e)=>(Module._LockRelationForExtension=wasmExports.LockRelationForExtension)(r,e),Module._UnlockRelationForExtension=(r,e)=>(Module._UnlockRelationForExtension=wasmExports.UnlockRelationForExtension)(r,e),Module._smgropen=(r,e)=>(Module._smgropen=wasmExports.smgropen)(r,e),Module._smgrpin=r=>(Module._smgrpin=wasmExports.smgrpin)(r),Module._ItemPointerEquals=(r,e)=>(Module._ItemPointerEquals=wasmExports.ItemPointerEquals)(r,e),Module._detoast_external_attr=r=>(Module._detoast_external_attr=wasmExports.detoast_external_attr)(r),Module._CreateTemplateTupleDesc=r=>(Module._CreateTemplateTupleDesc=wasmExports.CreateTemplateTupleDesc)(r),Module._TupleDescInitEntry=(r,e,M,tr,rr,ir)=>(Module._TupleDescInitEntry=wasmExports.TupleDescInitEntry)(r,e,M,tr,rr,ir),Module._SearchSysCache1=(r,e)=>(Module._SearchSysCache1=wasmExports.SearchSysCache1)(r,e),Module._SearchSysCacheList=(r,e,M,tr,rr)=>(Module._SearchSysCacheList=wasmExports.SearchSysCacheList)(r,e,M,tr,rr),Module._check_amproc_signature=(r,e,M,tr,rr,ir)=>(Module._check_amproc_signature=wasmExports.check_amproc_signature)(r,e,M,tr,rr,ir),Module._check_amoptsproc_signature=r=>(Module._check_amoptsproc_signature=wasmExports.check_amoptsproc_signature)(r),Module._format_procedure=r=>(Module._format_procedure=wasmExports.format_procedure)(r),Module._format_operator=r=>(Module._format_operator=wasmExports.format_operator)(r),Module._check_amop_signature=(r,e,M,tr)=>(Module._check_amop_signature=wasmExports.check_amop_signature)(r,e,M,tr),Module._identify_opfamily_groups=(r,e)=>(Module._identify_opfamily_groups=wasmExports.identify_opfamily_groups)(r,e),Module._format_type_be=r=>(Module._format_type_be=wasmExports.format_type_be)(r),Module._ReleaseCatCacheList=r=>(Module._ReleaseCatCacheList=wasmExports.ReleaseCatCacheList)(r),Module._format_type_with_typemod=(r,e)=>(Module._format_type_with_typemod=wasmExports.format_type_with_typemod)(r,e),Module._DatumGetEOHP=r=>(Module._DatumGetEOHP=wasmExports.DatumGetEOHP)(r),Module._EOH_get_flat_size=r=>(Module._EOH_get_flat_size=wasmExports.EOH_get_flat_size)(r),Module._EOH_flatten_into=(r,e,M)=>(Module._EOH_flatten_into=wasmExports.EOH_flatten_into)(r,e,M),Module._getmissingattr=(r,e,M)=>(Module._getmissingattr=wasmExports.getmissingattr)(r,e,M),Module._hash_create=(r,e,M,tr)=>(Module._hash_create=wasmExports.hash_create)(r,e,M,tr),Module._hash_search=(r,e,M,tr)=>(Module._hash_search=wasmExports.hash_search)(r,e,M,tr),Module._nocachegetattr=(r,e,M)=>(Module._nocachegetattr=wasmExports.nocachegetattr)(r,e,M),Module._heap_form_tuple=(r,e,M)=>(Module._heap_form_tuple=wasmExports.heap_form_tuple)(r,e,M),Module._heap_modify_tuple=(r,e,M,tr,rr)=>(Module._heap_modify_tuple=wasmExports.heap_modify_tuple)(r,e,M,tr,rr),Module._heap_deform_tuple=(r,e,M,tr)=>(Module._heap_deform_tuple=wasmExports.heap_deform_tuple)(r,e,M,tr),Module._heap_modify_tuple_by_cols=(r,e,M,tr,rr,ir)=>(Module._heap_modify_tuple_by_cols=wasmExports.heap_modify_tuple_by_cols)(r,e,M,tr,rr,ir),Module._heap_freetuple=r=>(Module._heap_freetuple=wasmExports.heap_freetuple)(r),Module._index_form_tuple=(r,e,M)=>(Module._index_form_tuple=wasmExports.index_form_tuple)(r,e,M),Module._nocache_index_getattr=(r,e,M)=>(Module._nocache_index_getattr=wasmExports.nocache_index_getattr)(r,e,M),Module._index_deform_tuple=(r,e,M,tr)=>(Module._index_deform_tuple=wasmExports.index_deform_tuple)(r,e,M,tr),Module._slot_getsomeattrs_int=(r,e)=>(Module._slot_getsomeattrs_int=wasmExports.slot_getsomeattrs_int)(r,e),Module._pg_ltoa=(r,e)=>(Module._pg_ltoa=wasmExports.pg_ltoa)(r,e),Module._relation_open=(r,e)=>(Module._relation_open=wasmExports.relation_open)(r,e),Module._LockRelationOid=(r,e)=>(Module._LockRelationOid=wasmExports.LockRelationOid)(r,e),Module._try_relation_open=(r,e)=>(Module._try_relation_open=wasmExports.try_relation_open)(r,e),Module._relation_openrv=(r,e)=>(Module._relation_openrv=wasmExports.relation_openrv)(r,e),Module._RangeVarGetRelidExtended=(r,e,M,tr,rr)=>(Module._RangeVarGetRelidExtended=wasmExports.RangeVarGetRelidExtended)(r,e,M,tr,rr),Module._add_reloption_kind=()=>(Module._add_reloption_kind=wasmExports.add_reloption_kind)(),Module._register_reloptions_validator=(r,e)=>(Module._register_reloptions_validator=wasmExports.register_reloptions_validator)(r,e),Module._add_int_reloption=(r,e,M,tr,rr,ir,lr)=>(Module._add_int_reloption=wasmExports.add_int_reloption)(r,e,M,tr,rr,ir,lr),Module._MemoryContextStrdup=(r,e)=>(Module._MemoryContextStrdup=wasmExports.MemoryContextStrdup)(r,e),Module._transformRelOptions=(r,e,M,tr,rr,ir)=>(Module._transformRelOptions=wasmExports.transformRelOptions)(r,e,M,tr,rr,ir),Module._deconstruct_array_builtin=(r,e,M,tr,rr)=>(Module._deconstruct_array_builtin=wasmExports.deconstruct_array_builtin)(r,e,M,tr,rr),Module._defGetString=r=>(Module._defGetString=wasmExports.defGetString)(r),Module._defGetBoolean=r=>(Module._defGetBoolean=wasmExports.defGetBoolean)(r),Module._untransformRelOptions=r=>(Module._untransformRelOptions=wasmExports.untransformRelOptions)(r),Module._text_to_cstring=r=>(Module._text_to_cstring=wasmExports.text_to_cstring)(r),Module._makeString=r=>(Module._makeString=wasmExports.makeString)(r),Module._makeDefElem=(r,e,M)=>(Module._makeDefElem=wasmExports.makeDefElem)(r,e,M),Module._heap_reloptions=(r,e,M)=>(Module._heap_reloptions=wasmExports.heap_reloptions)(r,e,M),Module._MemoryContextAlloc=(r,e)=>(Module._MemoryContextAlloc=wasmExports.MemoryContextAlloc)(r,e),Module._parse_bool=(r,e)=>(Module._parse_bool=wasmExports.parse_bool)(r,e),Module._parse_int=(r,e,M,tr)=>(Module._parse_int=wasmExports.parse_int)(r,e,M,tr),Module._parse_real=(r,e,M,tr)=>(Module._parse_real=wasmExports.parse_real)(r,e,M,tr),Module._ScanKeyInit=(r,e,M,tr,rr)=>(Module._ScanKeyInit=wasmExports.ScanKeyInit)(r,e,M,tr,rr),Module._dsm_segment_handle=r=>(Module._dsm_segment_handle=wasmExports.dsm_segment_handle)(r),Module._dsm_create=(r,e)=>(Module._dsm_create=wasmExports.dsm_create)(r,e),Module._dsm_segment_address=r=>(Module._dsm_segment_address=wasmExports.dsm_segment_address)(r),Module._dsm_attach=r=>(Module._dsm_attach=wasmExports.dsm_attach)(r),Module._dsm_detach=r=>(Module._dsm_detach=wasmExports.dsm_detach)(r),Module._ShmemInitStruct=(r,e,M)=>(Module._ShmemInitStruct=wasmExports.ShmemInitStruct)(r,e,M),Module._LWLockAcquire=(r,e)=>(Module._LWLockAcquire=wasmExports.LWLockAcquire)(r,e),Module._LWLockRelease=r=>(Module._LWLockRelease=wasmExports.LWLockRelease)(r),Module._LWLockInitialize=(r,e)=>(Module._LWLockInitialize=wasmExports.LWLockInitialize)(r,e),Module._MemoryContextMemAllocated=(r,e)=>(Module._MemoryContextMemAllocated=wasmExports.MemoryContextMemAllocated)(r,e),Module._GetCurrentCommandId=r=>(Module._GetCurrentCommandId=wasmExports.GetCurrentCommandId)(r),Module._toast_open_indexes=(r,e,M,tr)=>(Module._toast_open_indexes=wasmExports.toast_open_indexes)(r,e,M,tr),Module._RelationGetIndexList=r=>(Module._RelationGetIndexList=wasmExports.RelationGetIndexList)(r),Module._systable_beginscan=(r,e,M,tr,rr,ir)=>(Module._systable_beginscan=wasmExports.systable_beginscan)(r,e,M,tr,rr,ir),Module._systable_getnext=r=>(Module._systable_getnext=wasmExports.systable_getnext)(r),Module._systable_endscan=r=>(Module._systable_endscan=wasmExports.systable_endscan)(r),Module._toast_close_indexes=(r,e,M)=>(Module._toast_close_indexes=wasmExports.toast_close_indexes)(r,e,M),Module._systable_beginscan_ordered=(r,e,M,tr,rr)=>(Module._systable_beginscan_ordered=wasmExports.systable_beginscan_ordered)(r,e,M,tr,rr),Module._systable_getnext_ordered=(r,e)=>(Module._systable_getnext_ordered=wasmExports.systable_getnext_ordered)(r,e),Module._systable_endscan_ordered=r=>(Module._systable_endscan_ordered=wasmExports.systable_endscan_ordered)(r),Module._init_toast_snapshot=r=>(Module._init_toast_snapshot=wasmExports.init_toast_snapshot)(r),Module._convert_tuples_by_position=(r,e,M)=>(Module._convert_tuples_by_position=wasmExports.convert_tuples_by_position)(r,e,M),Module._execute_attr_map_tuple=(r,e)=>(Module._execute_attr_map_tuple=wasmExports.execute_attr_map_tuple)(r,e),Module._ExecStoreVirtualTuple=r=>(Module._ExecStoreVirtualTuple=wasmExports.ExecStoreVirtualTuple)(r),Module._bms_is_member=(r,e)=>(Module._bms_is_member=wasmExports.bms_is_member)(r,e),Module._bms_add_member=(r,e)=>(Module._bms_add_member=wasmExports.bms_add_member)(r,e),Module._CreateTupleDescCopy=r=>(Module._CreateTupleDescCopy=wasmExports.CreateTupleDescCopy)(r),Module._ResourceOwnerEnlarge=r=>(Module._ResourceOwnerEnlarge=wasmExports.ResourceOwnerEnlarge)(r),Module._ResourceOwnerRemember=(r,e,M)=>(Module._ResourceOwnerRemember=wasmExports.ResourceOwnerRemember)(r,e,M),Module._DecrTupleDescRefCount=r=>(Module._DecrTupleDescRefCount=wasmExports.DecrTupleDescRefCount)(r),Module._ResourceOwnerForget=(r,e,M)=>(Module._ResourceOwnerForget=wasmExports.ResourceOwnerForget)(r,e,M),Module._datumIsEqual=(r,e,M,tr)=>(Module._datumIsEqual=wasmExports.datumIsEqual)(r,e,M,tr),Module._TupleDescInitEntryCollation=(r,e,M)=>(Module._TupleDescInitEntryCollation=wasmExports.TupleDescInitEntryCollation)(r,e,M),Module._stringToNode=r=>(Module._stringToNode=wasmExports.stringToNode)(r),Module._pg_detoast_datum_copy=r=>(Module._pg_detoast_datum_copy=wasmExports.pg_detoast_datum_copy)(r),Module._get_typlenbyvalalign=(r,e,M,tr)=>(Module._get_typlenbyvalalign=wasmExports.get_typlenbyvalalign)(r,e,M,tr),Module._deconstruct_array=(r,e,M,tr,rr,ir,lr,dr)=>(Module._deconstruct_array=wasmExports.deconstruct_array)(r,e,M,tr,rr,ir,lr,dr),Module._tbm_add_tuples=(r,e,M,tr)=>(Module._tbm_add_tuples=wasmExports.tbm_add_tuples)(r,e,M,tr),Module._ginPostingListDecode=(r,e)=>(Module._ginPostingListDecode=wasmExports.ginPostingListDecode)(r,e),Module._ItemPointerCompare=(r,e)=>(Module._ItemPointerCompare=wasmExports.ItemPointerCompare)(r,e),Module._LockPage=(r,e,M)=>(Module._LockPage=wasmExports.LockPage)(r,e,M),Module._UnlockPage=(r,e,M)=>(Module._UnlockPage=wasmExports.UnlockPage)(r,e,M),Module._vacuum_delay_point=()=>(Module._vacuum_delay_point=wasmExports.vacuum_delay_point)(),Module._RecordFreeIndexPage=(r,e)=>(Module._RecordFreeIndexPage=wasmExports.RecordFreeIndexPage)(r,e),Module._IndexFreeSpaceMapVacuum=r=>(Module._IndexFreeSpaceMapVacuum=wasmExports.IndexFreeSpaceMapVacuum)(r),Module._log_newpage_range=(r,e,M,tr,rr)=>(Module._log_newpage_range=wasmExports.log_newpage_range)(r,e,M,tr,rr),Module._GetFreeIndexPage=r=>(Module._GetFreeIndexPage=wasmExports.GetFreeIndexPage)(r),Module._ConditionalLockBuffer=r=>(Module._ConditionalLockBuffer=wasmExports.ConditionalLockBuffer)(r),Module._LockBufferForCleanup=r=>(Module._LockBufferForCleanup=wasmExports.LockBufferForCleanup)(r),Module._gistcheckpage=(r,e)=>(Module._gistcheckpage=wasmExports.gistcheckpage)(r,e),Module._PageIndexMultiDelete=(r,e,M)=>(Module._PageIndexMultiDelete=wasmExports.PageIndexMultiDelete)(r,e,M),Module._smgrnblocks=(r,e)=>(Module._smgrnblocks=wasmExports.smgrnblocks)(r,e),Module._list_free_deep=r=>(Module._list_free_deep=wasmExports.list_free_deep)(r),Module._pairingheap_remove_first=r=>(Module._pairingheap_remove_first=wasmExports.pairingheap_remove_first)(r),Module._pairingheap_add=(r,e)=>(Module._pairingheap_add=wasmExports.pairingheap_add)(r,e),Module._float_overflow_error=()=>(Module._float_overflow_error=wasmExports.float_overflow_error)(),Module._float_underflow_error=()=>(Module._float_underflow_error=wasmExports.float_underflow_error)(),Module._DirectFunctionCall5Coll=(r,e,M,tr,rr,ir,lr)=>(Module._DirectFunctionCall5Coll=wasmExports.DirectFunctionCall5Coll)(r,e,M,tr,rr,ir,lr),Module._pairingheap_allocate=(r,e)=>(Module._pairingheap_allocate=wasmExports.pairingheap_allocate)(r,e),Module._GenerationContextCreate=(r,e,M,tr,rr)=>(Module._GenerationContextCreate=wasmExports.GenerationContextCreate)(r,e,M,tr,rr),Module._pgstat_progress_update_param=(r,e)=>(Module._pgstat_progress_update_param=wasmExports.pgstat_progress_update_param)(r,e),Module.__hash_getbuf=(r,e,M,tr)=>(Module.__hash_getbuf=wasmExports._hash_getbuf)(r,e,M,tr),Module.__hash_relbuf=(r,e)=>(Module.__hash_relbuf=wasmExports._hash_relbuf)(r,e),Module.__hash_get_indextuple_hashkey=r=>(Module.__hash_get_indextuple_hashkey=wasmExports._hash_get_indextuple_hashkey)(r),Module.__hash_getbuf_with_strategy=(r,e,M,tr,rr)=>(Module.__hash_getbuf_with_strategy=wasmExports._hash_getbuf_with_strategy)(r,e,M,tr,rr),Module.__hash_ovflblkno_to_bitno=(r,e)=>(Module.__hash_ovflblkno_to_bitno=wasmExports._hash_ovflblkno_to_bitno)(r,e),Module._list_member_oid=(r,e)=>(Module._list_member_oid=wasmExports.list_member_oid)(r,e),Module._HeapTupleSatisfiesVisibility=(r,e,M)=>(Module._HeapTupleSatisfiesVisibility=wasmExports.HeapTupleSatisfiesVisibility)(r,e,M),Module._read_stream_begin_relation=(r,e,M,tr,rr,ir,lr)=>(Module._read_stream_begin_relation=wasmExports.read_stream_begin_relation)(r,e,M,tr,rr,ir,lr),Module._GetAccessStrategy=r=>(Module._GetAccessStrategy=wasmExports.GetAccessStrategy)(r),Module._FreeAccessStrategy=r=>(Module._FreeAccessStrategy=wasmExports.FreeAccessStrategy)(r),Module._read_stream_end=r=>(Module._read_stream_end=wasmExports.read_stream_end)(r),Module._heap_getnext=(r,e)=>(Module._heap_getnext=wasmExports.heap_getnext)(r,e),Module._HeapTupleSatisfiesVacuum=(r,e,M)=>(Module._HeapTupleSatisfiesVacuum=wasmExports.HeapTupleSatisfiesVacuum)(r,e,M),Module._GetMultiXactIdMembers=(r,e,M,tr)=>(Module._GetMultiXactIdMembers=wasmExports.GetMultiXactIdMembers)(r,e,M,tr),Module._TransactionIdPrecedes=(r,e)=>(Module._TransactionIdPrecedes=wasmExports.TransactionIdPrecedes)(r,e),Module._HeapTupleGetUpdateXid=r=>(Module._HeapTupleGetUpdateXid=wasmExports.HeapTupleGetUpdateXid)(r),Module._visibilitymap_clear=(r,e,M,tr)=>(Module._visibilitymap_clear=wasmExports.visibilitymap_clear)(r,e,M,tr),Module._pgstat_count_heap_insert=(r,e)=>(Module._pgstat_count_heap_insert=wasmExports.pgstat_count_heap_insert)(r,e),Module._ExecFetchSlotHeapTuple=(r,e,M)=>(Module._ExecFetchSlotHeapTuple=wasmExports.ExecFetchSlotHeapTuple)(r,e,M),Module._PageGetHeapFreeSpace=r=>(Module._PageGetHeapFreeSpace=wasmExports.PageGetHeapFreeSpace)(r),Module._visibilitymap_pin=(r,e,M)=>(Module._visibilitymap_pin=wasmExports.visibilitymap_pin)(r,e,M),Module._HeapTupleSatisfiesUpdate=(r,e,M)=>(Module._HeapTupleSatisfiesUpdate=wasmExports.HeapTupleSatisfiesUpdate)(r,e,M),Module._TransactionIdIsCurrentTransactionId=r=>(Module._TransactionIdIsCurrentTransactionId=wasmExports.TransactionIdIsCurrentTransactionId)(r),Module._TransactionIdDidCommit=r=>(Module._TransactionIdDidCommit=wasmExports.TransactionIdDidCommit)(r),Module._TransactionIdIsInProgress=r=>(Module._TransactionIdIsInProgress=wasmExports.TransactionIdIsInProgress)(r),Module._bms_free=r=>(Module._bms_free=wasmExports.bms_free)(r),Module._bms_add_members=(r,e)=>(Module._bms_add_members=wasmExports.bms_add_members)(r,e),Module._bms_next_member=(r,e)=>(Module._bms_next_member=wasmExports.bms_next_member)(r,e),Module._bms_overlap=(r,e)=>(Module._bms_overlap=wasmExports.bms_overlap)(r,e),Module._MultiXactIdPrecedes=(r,e)=>(Module._MultiXactIdPrecedes=wasmExports.MultiXactIdPrecedes)(r,e),Module._heap_tuple_needs_eventual_freeze=r=>(Module._heap_tuple_needs_eventual_freeze=wasmExports.heap_tuple_needs_eventual_freeze)(r),Module._PrefetchBuffer=(r,e,M,tr)=>(Module._PrefetchBuffer=wasmExports.PrefetchBuffer)(r,e,M,tr),Module._XLogRecGetBlockTagExtended=(r,e,M,tr,rr,ir)=>(Module._XLogRecGetBlockTagExtended=wasmExports.XLogRecGetBlockTagExtended)(r,e,M,tr,rr,ir),Module._read_stream_next_buffer=(r,e)=>(Module._read_stream_next_buffer=wasmExports.read_stream_next_buffer)(r,e),Module._smgrexists=(r,e)=>(Module._smgrexists=wasmExports.smgrexists)(r,e),Module._table_slot_create=(r,e)=>(Module._table_slot_create=wasmExports.table_slot_create)(r,e),Module._ExecDropSingleTupleTableSlot=r=>(Module._ExecDropSingleTupleTableSlot=wasmExports.ExecDropSingleTupleTableSlot)(r),Module._CreateExecutorState=()=>(Module._CreateExecutorState=wasmExports.CreateExecutorState)(),Module._MakePerTupleExprContext=r=>(Module._MakePerTupleExprContext=wasmExports.MakePerTupleExprContext)(r),Module._GetOldestNonRemovableTransactionId=r=>(Module._GetOldestNonRemovableTransactionId=wasmExports.GetOldestNonRemovableTransactionId)(r),Module._FreeExecutorState=r=>(Module._FreeExecutorState=wasmExports.FreeExecutorState)(r),Module._MakeSingleTupleTableSlot=(r,e)=>(Module._MakeSingleTupleTableSlot=wasmExports.MakeSingleTupleTableSlot)(r,e),Module._ExecStoreHeapTuple=(r,e,M)=>(Module._ExecStoreHeapTuple=wasmExports.ExecStoreHeapTuple)(r,e,M),Module._visibilitymap_get_status=(r,e,M)=>(Module._visibilitymap_get_status=wasmExports.visibilitymap_get_status)(r,e,M),Module._ExecStoreAllNullTuple=r=>(Module._ExecStoreAllNullTuple=wasmExports.ExecStoreAllNullTuple)(r),Module._XidInMVCCSnapshot=(r,e)=>(Module._XidInMVCCSnapshot=wasmExports.XidInMVCCSnapshot)(r,e),Module._hash_seq_init=(r,e)=>(Module._hash_seq_init=wasmExports.hash_seq_init)(r,e),Module._hash_seq_search=r=>(Module._hash_seq_search=wasmExports.hash_seq_search)(r),Module._ftruncate=(r,e)=>(Module._ftruncate=wasmExports.ftruncate)(r,e),Module._fd_fsync_fname=(r,e)=>(Module._fd_fsync_fname=wasmExports.fd_fsync_fname)(r,e),Module._get_namespace_name=r=>(Module._get_namespace_name=wasmExports.get_namespace_name)(r),Module._GetRecordedFreeSpace=(r,e)=>(Module._GetRecordedFreeSpace=wasmExports.GetRecordedFreeSpace)(r,e),Module._vac_estimate_reltuples=(r,e,M,tr)=>(Module._vac_estimate_reltuples=wasmExports.vac_estimate_reltuples)(r,e,M,tr),Module._WaitLatch=(r,e,M,tr)=>(Module._WaitLatch=wasmExports.WaitLatch)(r,e,M,tr),Module._ResetLatch=r=>(Module._ResetLatch=wasmExports.ResetLatch)(r),Module._clock_gettime=(r,e)=>(Module._clock_gettime=wasmExports.clock_gettime)(r,e),Module._WalUsageAccumDiff=(r,e,M)=>(Module._WalUsageAccumDiff=wasmExports.WalUsageAccumDiff)(r,e,M),Module._BufferUsageAccumDiff=(r,e,M)=>(Module._BufferUsageAccumDiff=wasmExports.BufferUsageAccumDiff)(r,e,M),Module._visibilitymap_prepare_truncate=(r,e)=>(Module._visibilitymap_prepare_truncate=wasmExports.visibilitymap_prepare_truncate)(r,e),Module._pg_class_aclcheck=(r,e,M)=>(Module._pg_class_aclcheck=wasmExports.pg_class_aclcheck)(r,e,M),Module._btboolcmp=r=>(Module._btboolcmp=wasmExports.btboolcmp)(r),Module._btint2cmp=r=>(Module._btint2cmp=wasmExports.btint2cmp)(r),Module._btint4cmp=r=>(Module._btint4cmp=wasmExports.btint4cmp)(r),Module._btint8cmp=r=>(Module._btint8cmp=wasmExports.btint8cmp)(r),Module._btoidcmp=r=>(Module._btoidcmp=wasmExports.btoidcmp)(r),Module._btcharcmp=r=>(Module._btcharcmp=wasmExports.btcharcmp)(r),Module.__bt_form_posting=(r,e,M)=>(Module.__bt_form_posting=wasmExports._bt_form_posting)(r,e,M),Module.__bt_mkscankey=(r,e)=>(Module.__bt_mkscankey=wasmExports._bt_mkscankey)(r,e),Module.__bt_checkpage=(r,e)=>(Module.__bt_checkpage=wasmExports._bt_checkpage)(r,e),Module.__bt_compare=(r,e,M,tr)=>(Module.__bt_compare=wasmExports._bt_compare)(r,e,M,tr),Module.__bt_relbuf=(r,e)=>(Module.__bt_relbuf=wasmExports._bt_relbuf)(r,e),Module.__bt_search=(r,e,M,tr,rr)=>(Module.__bt_search=wasmExports._bt_search)(r,e,M,tr,rr),Module.__bt_binsrch_insert=(r,e)=>(Module.__bt_binsrch_insert=wasmExports._bt_binsrch_insert)(r,e),Module.__bt_freestack=r=>(Module.__bt_freestack=wasmExports._bt_freestack)(r),Module.__bt_metaversion=(r,e,M)=>(Module.__bt_metaversion=wasmExports._bt_metaversion)(r,e,M),Module.__bt_allequalimage=(r,e)=>(Module.__bt_allequalimage=wasmExports._bt_allequalimage)(r,e),Module._before_shmem_exit=(r,e)=>(Module._before_shmem_exit=wasmExports.before_shmem_exit)(r,e),Module._cancel_before_shmem_exit=(r,e)=>(Module._cancel_before_shmem_exit=wasmExports.cancel_before_shmem_exit)(r,e),Module._pg_re_throw=()=>(Module._pg_re_throw=wasmExports.pg_re_throw)(),Module._get_opfamily_member=(r,e,M,tr)=>(Module._get_opfamily_member=wasmExports.get_opfamily_member)(r,e,M,tr),Module.__bt_check_natts=(r,e,M,tr)=>(Module.__bt_check_natts=wasmExports._bt_check_natts)(r,e,M,tr),Module._strncpy=(r,e,M)=>(Module._strncpy=wasmExports.strncpy)(r,e,M),Module._timestamptz_to_str=r=>(Module._timestamptz_to_str=wasmExports.timestamptz_to_str)(r),Module._XLogRecGetBlockRefInfo=(r,e,M,tr,rr)=>(Module._XLogRecGetBlockRefInfo=wasmExports.XLogRecGetBlockRefInfo)(r,e,M,tr,rr),Module._varstr_cmp=(r,e,M,tr,rr)=>(Module._varstr_cmp=wasmExports.varstr_cmp)(r,e,M,tr,rr),Module._exprType=r=>(Module._exprType=wasmExports.exprType)(r),Module._GetActiveSnapshot=()=>(Module._GetActiveSnapshot=wasmExports.GetActiveSnapshot)(),Module._errdetail_relkind_not_supported=r=>(Module._errdetail_relkind_not_supported=wasmExports.errdetail_relkind_not_supported)(r),Module._table_openrv=(r,e)=>(Module._table_openrv=wasmExports.table_openrv)(r,e),Module._table_slot_callbacks=r=>(Module._table_slot_callbacks=wasmExports.table_slot_callbacks)(r),Module._clamp_row_est=r=>(Module._clamp_row_est=wasmExports.clamp_row_est)(r),Module._estimate_expression_value=(r,e)=>(Module._estimate_expression_value=wasmExports.estimate_expression_value)(r,e),Module._XLogFlush=r=>(Module._XLogFlush=wasmExports.XLogFlush)(r),Module._get_call_result_type=(r,e,M)=>(Module._get_call_result_type=wasmExports.get_call_result_type)(r,e,M),Module._HeapTupleHeaderGetDatum=r=>(Module._HeapTupleHeaderGetDatum=wasmExports.HeapTupleHeaderGetDatum)(r),Module._GenericXLogStart=r=>(Module._GenericXLogStart=wasmExports.GenericXLogStart)(r),Module._GenericXLogRegisterBuffer=(r,e,M)=>(Module._GenericXLogRegisterBuffer=wasmExports.GenericXLogRegisterBuffer)(r,e,M),Module._GenericXLogFinish=r=>(Module._GenericXLogFinish=wasmExports.GenericXLogFinish)(r),Module._GenericXLogAbort=r=>(Module._GenericXLogAbort=wasmExports.GenericXLogAbort)(r),Module._errmsg_plural=(r,e,M,tr)=>(Module._errmsg_plural=wasmExports.errmsg_plural)(r,e,M,tr),Module._ReadNextMultiXactId=()=>(Module._ReadNextMultiXactId=wasmExports.ReadNextMultiXactId)(),Module._ReadMultiXactIdRange=(r,e)=>(Module._ReadMultiXactIdRange=wasmExports.ReadMultiXactIdRange)(r,e),Module._MultiXactIdPrecedesOrEquals=(r,e)=>(Module._MultiXactIdPrecedesOrEquals=wasmExports.MultiXactIdPrecedesOrEquals)(r,e),Module._init_MultiFuncCall=r=>(Module._init_MultiFuncCall=wasmExports.init_MultiFuncCall)(r),Module._TupleDescGetAttInMetadata=r=>(Module._TupleDescGetAttInMetadata=wasmExports.TupleDescGetAttInMetadata)(r),Module._per_MultiFuncCall=r=>(Module._per_MultiFuncCall=wasmExports.per_MultiFuncCall)(r),Module._BuildTupleFromCStrings=(r,e)=>(Module._BuildTupleFromCStrings=wasmExports.BuildTupleFromCStrings)(r,e),Module._end_MultiFuncCall=(r,e)=>(Module._end_MultiFuncCall=wasmExports.end_MultiFuncCall)(r,e),Module._GetCurrentSubTransactionId=()=>(Module._GetCurrentSubTransactionId=wasmExports.GetCurrentSubTransactionId)(),Module._WaitForBackgroundWorkerShutdown=r=>(Module._WaitForBackgroundWorkerShutdown=wasmExports.WaitForBackgroundWorkerShutdown)(r),Module._RegisterDynamicBackgroundWorker=(r,e)=>(Module._RegisterDynamicBackgroundWorker=wasmExports.RegisterDynamicBackgroundWorker)(r,e),Module._BackgroundWorkerUnblockSignals=()=>(Module._BackgroundWorkerUnblockSignals=wasmExports.BackgroundWorkerUnblockSignals)(),Module._BackgroundWorkerInitializeConnectionByOid=(r,e,M)=>(Module._BackgroundWorkerInitializeConnectionByOid=wasmExports.BackgroundWorkerInitializeConnectionByOid)(r,e,M),Module._GetDatabaseEncoding=()=>(Module._GetDatabaseEncoding=wasmExports.GetDatabaseEncoding)(),Module._RmgrNotFound=r=>(Module._RmgrNotFound=wasmExports.RmgrNotFound)(r),Module._InitMaterializedSRF=(r,e)=>(Module._InitMaterializedSRF=wasmExports.InitMaterializedSRF)(r,e),Module._tuplestore_putvalues=(r,e,M,tr)=>(Module._tuplestore_putvalues=wasmExports.tuplestore_putvalues)(r,e,M,tr),Module._AllocateFile=(r,e)=>(Module._AllocateFile=wasmExports.AllocateFile)(r,e),Module._FreeFile=r=>(Module._FreeFile=wasmExports.FreeFile)(r),Module._fd_durable_rename=(r,e,M)=>(Module._fd_durable_rename=wasmExports.fd_durable_rename)(r,e,M),Module._BlessTupleDesc=r=>(Module._BlessTupleDesc=wasmExports.BlessTupleDesc)(r),Module._fstat=(r,e)=>(Module._fstat=wasmExports.fstat)(r,e),Module._superuser_arg=r=>(Module._superuser_arg=wasmExports.superuser_arg)(r),Module._wal_segment_close=r=>(Module._wal_segment_close=wasmExports.wal_segment_close)(r),Module._wal_segment_open=(r,e,M)=>(Module._wal_segment_open=wasmExports.wal_segment_open)(r,e,M),Module._XLogReaderAllocate=(r,e,M,tr)=>(Module._XLogReaderAllocate=wasmExports.XLogReaderAllocate)(r,e,M,tr),Module._XLogReadRecord=(r,e)=>(Module._XLogReadRecord=wasmExports.XLogReadRecord)(r,e),Module._XLogReaderFree=r=>(Module._XLogReaderFree=wasmExports.XLogReaderFree)(r),Module._GetTopFullTransactionId=()=>(Module._GetTopFullTransactionId=wasmExports.GetTopFullTransactionId)(),Module._GetCurrentTransactionNestLevel=()=>(Module._GetCurrentTransactionNestLevel=wasmExports.GetCurrentTransactionNestLevel)(),Module._ResourceOwnerCreate=(r,e)=>(Module._ResourceOwnerCreate=wasmExports.ResourceOwnerCreate)(r,e),Module._RegisterXactCallback=(r,e)=>(Module._RegisterXactCallback=wasmExports.RegisterXactCallback)(r,e),Module._RegisterSubXactCallback=(r,e)=>(Module._RegisterSubXactCallback=wasmExports.RegisterSubXactCallback)(r,e),Module._BeginInternalSubTransaction=r=>(Module._BeginInternalSubTransaction=wasmExports.BeginInternalSubTransaction)(r),Module._ReleaseCurrentSubTransaction=()=>(Module._ReleaseCurrentSubTransaction=wasmExports.ReleaseCurrentSubTransaction)(),Module._ResourceOwnerDelete=r=>(Module._ResourceOwnerDelete=wasmExports.ResourceOwnerDelete)(r),Module._RollbackAndReleaseCurrentSubTransaction=()=>(Module._RollbackAndReleaseCurrentSubTransaction=wasmExports.RollbackAndReleaseCurrentSubTransaction)(),Module._ReleaseExternalFD=()=>(Module._ReleaseExternalFD=wasmExports.ReleaseExternalFD)(),Module._GetFlushRecPtr=r=>(Module._GetFlushRecPtr=wasmExports.GetFlushRecPtr)(r),Module._GetXLogReplayRecPtr=r=>(Module._GetXLogReplayRecPtr=wasmExports.GetXLogReplayRecPtr)(r),Module._TimestampDifferenceMilliseconds=(r,e)=>(Module._TimestampDifferenceMilliseconds=wasmExports.TimestampDifferenceMilliseconds)(r,e),Module._numeric_in=r=>(Module._numeric_in=wasmExports.numeric_in)(r),Module._DirectFunctionCall3Coll=(r,e,M,tr,rr)=>(Module._DirectFunctionCall3Coll=wasmExports.DirectFunctionCall3Coll)(r,e,M,tr,rr),Module._XLogFindNextRecord=(r,e)=>(Module._XLogFindNextRecord=wasmExports.XLogFindNextRecord)(r,e),Module._RestoreBlockImage=(r,e,M)=>(Module._RestoreBlockImage=wasmExports.RestoreBlockImage)(r,e,M),Module._timestamptz_in=r=>(Module._timestamptz_in=wasmExports.timestamptz_in)(r),Module._fscanf=(r,e,M)=>(Module._fscanf=wasmExports.fscanf)(r,e,M),Module._XLogRecStoreStats=(r,e)=>(Module._XLogRecStoreStats=wasmExports.XLogRecStoreStats)(r,e),Module._hash_get_num_entries=r=>(Module._hash_get_num_entries=wasmExports.hash_get_num_entries)(r),Module._read_local_xlog_page_no_wait=(r,e,M,tr,rr)=>(Module._read_local_xlog_page_no_wait=wasmExports.read_local_xlog_page_no_wait)(r,e,M,tr,rr),Module._escape_json=(r,e)=>(Module._escape_json=wasmExports.escape_json)(r,e),Module._list_sort=(r,e)=>(Module._list_sort=wasmExports.list_sort)(r,e),Module._getegid=()=>(Module._getegid=wasmExports.getegid)(),Module._pg_checksum_page=(r,e)=>(Module._pg_checksum_page=wasmExports.pg_checksum_page)(r,e),Module._bbsink_forward_end_archive=r=>(Module._bbsink_forward_end_archive=wasmExports.bbsink_forward_end_archive)(r),Module._bbsink_forward_begin_manifest=r=>(Module._bbsink_forward_begin_manifest=wasmExports.bbsink_forward_begin_manifest)(r),Module._bbsink_forward_end_manifest=r=>(Module._bbsink_forward_end_manifest=wasmExports.bbsink_forward_end_manifest)(r),Module._bbsink_forward_end_backup=(r,e,M)=>(Module._bbsink_forward_end_backup=wasmExports.bbsink_forward_end_backup)(r,e,M),Module._bbsink_forward_cleanup=r=>(Module._bbsink_forward_cleanup=wasmExports.bbsink_forward_cleanup)(r),Module._list_concat=(r,e)=>(Module._list_concat=wasmExports.list_concat)(r,e),Module._bbsink_forward_begin_backup=r=>(Module._bbsink_forward_begin_backup=wasmExports.bbsink_forward_begin_backup)(r),Module._bbsink_forward_archive_contents=(r,e)=>(Module._bbsink_forward_archive_contents=wasmExports.bbsink_forward_archive_contents)(r,e),Module._bbsink_forward_begin_archive=(r,e)=>(Module._bbsink_forward_begin_archive=wasmExports.bbsink_forward_begin_archive)(r,e),Module._bbsink_forward_manifest_contents=(r,e)=>(Module._bbsink_forward_manifest_contents=wasmExports.bbsink_forward_manifest_contents)(r,e),Module._has_privs_of_role=(r,e)=>(Module._has_privs_of_role=wasmExports.has_privs_of_role)(r,e),Module._BaseBackupAddTarget=(r,e,M)=>(Module._BaseBackupAddTarget=wasmExports.BaseBackupAddTarget)(r,e,M),Module._list_copy=r=>(Module._list_copy=wasmExports.list_copy)(r),Module._tuplestore_puttuple=(r,e)=>(Module._tuplestore_puttuple=wasmExports.tuplestore_puttuple)(r,e),Module._makeRangeVar=(r,e,M)=>(Module._makeRangeVar=wasmExports.makeRangeVar)(r,e,M),Module._DefineIndex=(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r)=>(Module._DefineIndex=wasmExports.DefineIndex)(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r),Module._fread=(r,e,M,tr)=>(Module._fread=wasmExports.fread)(r,e,M,tr),Module._clearerr=r=>(Module._clearerr=wasmExports.clearerr)(r),Module._copyObjectImpl=r=>(Module._copyObjectImpl=wasmExports.copyObjectImpl)(r),Module._lappend_oid=(r,e)=>(Module._lappend_oid=wasmExports.lappend_oid)(r,e),Module._makeTypeNameFromNameList=r=>(Module._makeTypeNameFromNameList=wasmExports.makeTypeNameFromNameList)(r),Module._CatalogTupleUpdate=(r,e,M)=>(Module._CatalogTupleUpdate=wasmExports.CatalogTupleUpdate)(r,e,M),Module._get_rel_name=r=>(Module._get_rel_name=wasmExports.get_rel_name)(r),Module._CatalogTupleDelete=(r,e)=>(Module._CatalogTupleDelete=wasmExports.CatalogTupleDelete)(r,e),Module._CatalogTupleInsert=(r,e)=>(Module._CatalogTupleInsert=wasmExports.CatalogTupleInsert)(r,e),Module._recordDependencyOn=(r,e,M)=>(Module._recordDependencyOn=wasmExports.recordDependencyOn)(r,e,M),Module._get_element_type=r=>(Module._get_element_type=wasmExports.get_element_type)(r),Module._object_aclcheck=(r,e,M,tr)=>(Module._object_aclcheck=wasmExports.object_aclcheck)(r,e,M,tr),Module._superuser=()=>(Module._superuser=wasmExports.superuser)(),Module._SearchSysCacheAttName=(r,e)=>(Module._SearchSysCacheAttName=wasmExports.SearchSysCacheAttName)(r,e),Module._new_object_addresses=()=>(Module._new_object_addresses=wasmExports.new_object_addresses)(),Module._free_object_addresses=r=>(Module._free_object_addresses=wasmExports.free_object_addresses)(r),Module._performMultipleDeletions=(r,e,M)=>(Module._performMultipleDeletions=wasmExports.performMultipleDeletions)(r,e,M),Module._recordDependencyOnExpr=(r,e,M,tr)=>(Module._recordDependencyOnExpr=wasmExports.recordDependencyOnExpr)(r,e,M,tr),Module._query_tree_walker_impl=(r,e,M,tr)=>(Module._query_tree_walker_impl=wasmExports.query_tree_walker_impl)(r,e,M,tr),Module._expression_tree_walker_impl=(r,e,M)=>(Module._expression_tree_walker_impl=wasmExports.expression_tree_walker_impl)(r,e,M),Module._add_exact_object_address=(r,e)=>(Module._add_exact_object_address=wasmExports.add_exact_object_address)(r,e),Module._get_rel_relkind=r=>(Module._get_rel_relkind=wasmExports.get_rel_relkind)(r),Module._get_typtype=r=>(Module._get_typtype=wasmExports.get_typtype)(r),Module._list_delete_last=r=>(Module._list_delete_last=wasmExports.list_delete_last)(r),Module._type_is_collatable=r=>(Module._type_is_collatable=wasmExports.type_is_collatable)(r),Module._GetSysCacheOid=(r,e,M,tr,rr,ir)=>(Module._GetSysCacheOid=wasmExports.GetSysCacheOid)(r,e,M,tr,rr,ir),Module._CheckTableNotInUse=(r,e)=>(Module._CheckTableNotInUse=wasmExports.CheckTableNotInUse)(r,e),Module._construct_array=(r,e,M,tr,rr,ir)=>(Module._construct_array=wasmExports.construct_array)(r,e,M,tr,rr,ir),Module._make_parsestate=r=>(Module._make_parsestate=wasmExports.make_parsestate)(r),Module._transformExpr=(r,e,M)=>(Module._transformExpr=wasmExports.transformExpr)(r,e,M),Module._equal=(r,e)=>(Module._equal=wasmExports.equal)(r,e),Module._pull_var_clause=(r,e)=>(Module._pull_var_clause=wasmExports.pull_var_clause)(r,e),Module._get_attname=(r,e,M)=>(Module._get_attname=wasmExports.get_attname)(r,e,M),Module._coerce_to_target_type=(r,e,M,tr,rr,ir,lr,dr)=>(Module._coerce_to_target_type=wasmExports.coerce_to_target_type)(r,e,M,tr,rr,ir,lr,dr),Module._nodeToString=r=>(Module._nodeToString=wasmExports.nodeToString)(r),Module._parser_errposition=(r,e)=>(Module._parser_errposition=wasmExports.parser_errposition)(r,e),Module._exprTypmod=r=>(Module._exprTypmod=wasmExports.exprTypmod)(r),Module._get_base_element_type=r=>(Module._get_base_element_type=wasmExports.get_base_element_type)(r),Module._SystemFuncName=r=>(Module._SystemFuncName=wasmExports.SystemFuncName)(r),Module._CreateTrigger=(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r)=>(Module._CreateTrigger=wasmExports.CreateTrigger)(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r),Module._plan_create_index_workers=(r,e)=>(Module._plan_create_index_workers=wasmExports.plan_create_index_workers)(r,e),Module._get_rel_namespace=r=>(Module._get_rel_namespace=wasmExports.get_rel_namespace)(r),Module._ConditionalLockRelationOid=(r,e)=>(Module._ConditionalLockRelationOid=wasmExports.ConditionalLockRelationOid)(r,e),Module._RelnameGetRelid=r=>(Module._RelnameGetRelid=wasmExports.RelnameGetRelid)(r),Module._get_relkind_objtype=r=>(Module._get_relkind_objtype=wasmExports.get_relkind_objtype)(r),Module._RelationIsVisible=r=>(Module._RelationIsVisible=wasmExports.RelationIsVisible)(r),Module._get_func_arg_info=(r,e,M,tr)=>(Module._get_func_arg_info=wasmExports.get_func_arg_info)(r,e,M,tr),Module._NameListToString=r=>(Module._NameListToString=wasmExports.NameListToString)(r),Module._OpernameGetOprid=(r,e,M)=>(Module._OpernameGetOprid=wasmExports.OpernameGetOprid)(r,e,M),Module._makeRangeVarFromNameList=r=>(Module._makeRangeVarFromNameList=wasmExports.makeRangeVarFromNameList)(r),Module._quote_identifier=r=>(Module._quote_identifier=wasmExports.quote_identifier)(r),Module._GetSearchPathMatcher=r=>(Module._GetSearchPathMatcher=wasmExports.GetSearchPathMatcher)(r),Module._SearchPathMatchesCurrentEnvironment=r=>(Module._SearchPathMatchesCurrentEnvironment=wasmExports.SearchPathMatchesCurrentEnvironment)(r),Module._get_collation_oid=(r,e)=>(Module._get_collation_oid=wasmExports.get_collation_oid)(r,e),Module._CacheRegisterSyscacheCallback=(r,e,M)=>(Module._CacheRegisterSyscacheCallback=wasmExports.CacheRegisterSyscacheCallback)(r,e,M),Module._get_extension_oid=(r,e)=>(Module._get_extension_oid=wasmExports.get_extension_oid)(r,e),Module._get_role_oid=(r,e)=>(Module._get_role_oid=wasmExports.get_role_oid)(r,e),Module._GetForeignServerByName=(r,e)=>(Module._GetForeignServerByName=wasmExports.GetForeignServerByName)(r,e),Module._typeStringToTypeName=(r,e)=>(Module._typeStringToTypeName=wasmExports.typeStringToTypeName)(r,e),Module._list_make2_impl=(r,e,M)=>(Module._list_make2_impl=wasmExports.list_make2_impl)(r,e,M),Module._GetUserNameFromId=(r,e)=>(Module._GetUserNameFromId=wasmExports.GetUserNameFromId)(r,e),Module._format_type_extended=(r,e,M)=>(Module._format_type_extended=wasmExports.format_type_extended)(r,e,M),Module._quote_qualified_identifier=(r,e)=>(Module._quote_qualified_identifier=wasmExports.quote_qualified_identifier)(r,e),Module._get_tablespace_name=r=>(Module._get_tablespace_name=wasmExports.get_tablespace_name)(r),Module._GetForeignServerExtended=(r,e)=>(Module._GetForeignServerExtended=wasmExports.GetForeignServerExtended)(r,e),Module._GetForeignServer=r=>(Module._GetForeignServer=wasmExports.GetForeignServer)(r),Module._construct_empty_array=r=>(Module._construct_empty_array=wasmExports.construct_empty_array)(r),Module._format_type_be_qualified=r=>(Module._format_type_be_qualified=wasmExports.format_type_be_qualified)(r),Module._get_namespace_name_or_temp=r=>(Module._get_namespace_name_or_temp=wasmExports.get_namespace_name_or_temp)(r),Module._list_make3_impl=(r,e,M,tr)=>(Module._list_make3_impl=wasmExports.list_make3_impl)(r,e,M,tr),Module._construct_md_array=(r,e,M,tr,rr,ir,lr,dr,hr)=>(Module._construct_md_array=wasmExports.construct_md_array)(r,e,M,tr,rr,ir,lr,dr,hr),Module._pull_varattnos=(r,e,M)=>(Module._pull_varattnos=wasmExports.pull_varattnos)(r,e,M),Module._get_func_name=r=>(Module._get_func_name=wasmExports.get_func_name)(r),Module._construct_array_builtin=(r,e,M)=>(Module._construct_array_builtin=wasmExports.construct_array_builtin)(r,e,M),Module._makeObjectName=(r,e,M)=>(Module._makeObjectName=wasmExports.makeObjectName)(r,e,M),Module._get_primary_key_attnos=(r,e,M)=>(Module._get_primary_key_attnos=wasmExports.get_primary_key_attnos)(r,e,M),Module._bms_is_subset=(r,e)=>(Module._bms_is_subset=wasmExports.bms_is_subset)(r,e),Module._getExtensionOfObject=(r,e)=>(Module._getExtensionOfObject=wasmExports.getExtensionOfObject)(r,e),Module._find_inheritance_children=(r,e)=>(Module._find_inheritance_children=wasmExports.find_inheritance_children)(r,e),Module._lappend_int=(r,e)=>(Module._lappend_int=wasmExports.lappend_int)(r,e),Module._has_superclass=r=>(Module._has_superclass=wasmExports.has_superclass)(r),Module._CheckFunctionValidatorAccess=(r,e)=>(Module._CheckFunctionValidatorAccess=wasmExports.CheckFunctionValidatorAccess)(r,e),Module._AcquireRewriteLocks=(r,e,M)=>(Module._AcquireRewriteLocks=wasmExports.AcquireRewriteLocks)(r,e,M),Module._function_parse_error_transpose=r=>(Module._function_parse_error_transpose=wasmExports.function_parse_error_transpose)(r),Module._geterrposition=()=>(Module._geterrposition=wasmExports.geterrposition)(),Module._getinternalerrposition=()=>(Module._getinternalerrposition=wasmExports.getinternalerrposition)(),Module._pg_mblen=r=>(Module._pg_mblen=wasmExports.pg_mblen)(r),Module._pg_mbstrlen_with_len=(r,e)=>(Module._pg_mbstrlen_with_len=wasmExports.pg_mbstrlen_with_len)(r,e),Module._errposition=r=>(Module._errposition=wasmExports.errposition)(r),Module._internalerrposition=r=>(Module._internalerrposition=wasmExports.internalerrposition)(r),Module._internalerrquery=r=>(Module._internalerrquery=wasmExports.internalerrquery)(r),Module._list_delete_nth_cell=(r,e)=>(Module._list_delete_nth_cell=wasmExports.list_delete_nth_cell)(r,e),Module._get_array_type=r=>(Module._get_array_type=wasmExports.get_array_type)(r),Module._smgrtruncate2=(r,e,M,tr,rr)=>(Module._smgrtruncate2=wasmExports.smgrtruncate2)(r,e,M,tr,rr),Module._smgrreadv=(r,e,M,tr,rr)=>(Module._smgrreadv=wasmExports.smgrreadv)(r,e,M,tr,rr),Module._NewRelationCreateToastTable=(r,e)=>(Module._NewRelationCreateToastTable=wasmExports.NewRelationCreateToastTable)(r,e),Module._transformStmt=(r,e)=>(Module._transformStmt=wasmExports.transformStmt)(r,e),Module._exprLocation=r=>(Module._exprLocation=wasmExports.exprLocation)(r),Module._ParseFuncOrColumn=(r,e,M,tr,rr,ir,lr)=>(Module._ParseFuncOrColumn=wasmExports.ParseFuncOrColumn)(r,e,M,tr,rr,ir,lr),Module._exprCollation=r=>(Module._exprCollation=wasmExports.exprCollation)(r),Module._transformDistinctClause=(r,e,M,tr)=>(Module._transformDistinctClause=wasmExports.transformDistinctClause)(r,e,M,tr),Module._makeTargetEntry=(r,e,M,tr)=>(Module._makeTargetEntry=wasmExports.makeTargetEntry)(r,e,M,tr),Module._makeAlias=(r,e)=>(Module._makeAlias=wasmExports.makeAlias)(r,e),Module._addRangeTableEntryForSubquery=(r,e,M,tr,rr)=>(Module._addRangeTableEntryForSubquery=wasmExports.addRangeTableEntryForSubquery)(r,e,M,tr,rr),Module._makeVar=(r,e,M,tr,rr,ir)=>(Module._makeVar=wasmExports.makeVar)(r,e,M,tr,rr,ir),Module._makeBoolean=r=>(Module._makeBoolean=wasmExports.makeBoolean)(r),Module._makeInteger=r=>(Module._makeInteger=wasmExports.makeInteger)(r),Module._makeTypeName=r=>(Module._makeTypeName=wasmExports.makeTypeName)(r),Module._makeFuncCall=(r,e,M,tr)=>(Module._makeFuncCall=wasmExports.makeFuncCall)(r,e,M,tr),Module._list_make4_impl=(r,e,M,tr,rr)=>(Module._list_make4_impl=wasmExports.list_make4_impl)(r,e,M,tr,rr),Module._get_sortgroupclause_tle=(r,e)=>(Module._get_sortgroupclause_tle=wasmExports.get_sortgroupclause_tle)(r,e),Module._flatten_join_alias_vars=(r,e,M)=>(Module._flatten_join_alias_vars=wasmExports.flatten_join_alias_vars)(r,e,M),Module._list_member_int=(r,e)=>(Module._list_member_int=wasmExports.list_member_int)(r,e),Module._addRangeTableEntryForENR=(r,e,M)=>(Module._addRangeTableEntryForENR=wasmExports.addRangeTableEntryForENR)(r,e,M),Module._typenameTypeIdAndMod=(r,e,M,tr)=>(Module._typenameTypeIdAndMod=wasmExports.typenameTypeIdAndMod)(r,e,M,tr),Module._get_typcollation=r=>(Module._get_typcollation=wasmExports.get_typcollation)(r),Module._strip_implicit_coercions=r=>(Module._strip_implicit_coercions=wasmExports.strip_implicit_coercions)(r),Module._get_sortgroupref_tle=(r,e)=>(Module._get_sortgroupref_tle=wasmExports.get_sortgroupref_tle)(r,e),Module._contain_aggs_of_level=(r,e)=>(Module._contain_aggs_of_level=wasmExports.contain_aggs_of_level)(r,e),Module._typeidType=r=>(Module._typeidType=wasmExports.typeidType)(r),Module._typeTypeCollation=r=>(Module._typeTypeCollation=wasmExports.typeTypeCollation)(r),Module._typeLen=r=>(Module._typeLen=wasmExports.typeLen)(r),Module._typeByVal=r=>(Module._typeByVal=wasmExports.typeByVal)(r),Module._makeConst=(r,e,M,tr,rr,ir,lr)=>(Module._makeConst=wasmExports.makeConst)(r,e,M,tr,rr,ir,lr),Module._lookup_rowtype_tupdesc=(r,e)=>(Module._lookup_rowtype_tupdesc=wasmExports.lookup_rowtype_tupdesc)(r,e),Module._bms_del_member=(r,e)=>(Module._bms_del_member=wasmExports.bms_del_member)(r,e),Module._list_member=(r,e)=>(Module._list_member=wasmExports.list_member)(r,e),Module._type_is_rowtype=r=>(Module._type_is_rowtype=wasmExports.type_is_rowtype)(r),Module._bit_in=r=>(Module._bit_in=wasmExports.bit_in)(r),Module._bms_union=(r,e)=>(Module._bms_union=wasmExports.bms_union)(r,e),Module._varstr_levenshtein_less_equal=(r,e,M,tr,rr,ir,lr,dr,hr)=>(Module._varstr_levenshtein_less_equal=wasmExports.varstr_levenshtein_less_equal)(r,e,M,tr,rr,ir,lr,dr,hr),Module._errsave_start=(r,e)=>(Module._errsave_start=wasmExports.errsave_start)(r,e),Module._errsave_finish=(r,e,M,tr)=>(Module._errsave_finish=wasmExports.errsave_finish)(r,e,M,tr),Module._makeColumnDef=(r,e,M,tr)=>(Module._makeColumnDef=wasmExports.makeColumnDef)(r,e,M,tr),Module._GetDefaultOpClass=(r,e)=>(Module._GetDefaultOpClass=wasmExports.GetDefaultOpClass)(r,e),Module._scanner_init=(r,e,M,tr)=>(Module._scanner_init=wasmExports.scanner_init)(r,e,M,tr),Module._scanner_finish=r=>(Module._scanner_finish=wasmExports.scanner_finish)(r),Module._core_yylex=(r,e,M)=>(Module._core_yylex=wasmExports.core_yylex)(r,e,M),Module._isxdigit=r=>(Module._isxdigit=wasmExports.isxdigit)(r),Module._scanner_isspace=r=>(Module._scanner_isspace=wasmExports.scanner_isspace)(r),Module._truncate_identifier=(r,e,M)=>(Module._truncate_identifier=wasmExports.truncate_identifier)(r,e,M),Module._downcase_truncate_identifier=(r,e,M)=>(Module._downcase_truncate_identifier=wasmExports.downcase_truncate_identifier)(r,e,M),Module._pg_database_encoding_max_length=()=>(Module._pg_database_encoding_max_length=wasmExports.pg_database_encoding_max_length)(),Module._namein=r=>(Module._namein=wasmExports.namein)(r),Module._BlockSampler_Init=(r,e,M,tr)=>(Module._BlockSampler_Init=wasmExports.BlockSampler_Init)(r,e,M,tr),Module._reservoir_init_selection_state=(r,e)=>(Module._reservoir_init_selection_state=wasmExports.reservoir_init_selection_state)(r,e),Module._reservoir_get_next_S=(r,e,M)=>(Module._reservoir_get_next_S=wasmExports.reservoir_get_next_S)(r,e,M),Module._sampler_random_fract=r=>(Module._sampler_random_fract=wasmExports.sampler_random_fract)(r),Module._BlockSampler_HasMore=r=>(Module._BlockSampler_HasMore=wasmExports.BlockSampler_HasMore)(r),Module._BlockSampler_Next=r=>(Module._BlockSampler_Next=wasmExports.BlockSampler_Next)(r),Module._Async_Notify=(r,e)=>(Module._Async_Notify=wasmExports.Async_Notify)(r,e),Module._RangeVarCallbackMaintainsTable=(r,e,M,tr)=>(Module._RangeVarCallbackMaintainsTable=wasmExports.RangeVarCallbackMaintainsTable)(r,e,M,tr),Module._make_new_heap=(r,e,M,tr,rr)=>(Module._make_new_heap=wasmExports.make_new_heap)(r,e,M,tr,rr),Module._finish_heap_swap=(r,e,M,tr,rr,ir,lr,dr,hr)=>(Module._finish_heap_swap=wasmExports.finish_heap_swap)(r,e,M,tr,rr,ir,lr,dr,hr),Module._wasm_OpenPipeStream=(r,e)=>(Module._wasm_OpenPipeStream=wasmExports.wasm_OpenPipeStream)(r,e),Module._ClosePipeStream=r=>(Module._ClosePipeStream=wasmExports.ClosePipeStream)(r),Module._BeginCopyFrom=(r,e,M,tr,rr,ir,lr,dr)=>(Module._BeginCopyFrom=wasmExports.BeginCopyFrom)(r,e,M,tr,rr,ir,lr,dr),Module._EndCopyFrom=r=>(Module._EndCopyFrom=wasmExports.EndCopyFrom)(r),Module._ProcessCopyOptions=(r,e,M,tr)=>(Module._ProcessCopyOptions=wasmExports.ProcessCopyOptions)(r,e,M,tr),Module._CopyFromErrorCallback=r=>(Module._CopyFromErrorCallback=wasmExports.CopyFromErrorCallback)(r),Module._NextCopyFrom=(r,e,M,tr)=>(Module._NextCopyFrom=wasmExports.NextCopyFrom)(r,e,M,tr),Module._ExecInitExpr=(r,e)=>(Module._ExecInitExpr=wasmExports.ExecInitExpr)(r,e),Module._tolower=r=>(Module._tolower=wasmExports.tolower)(r),Module._PushCopiedSnapshot=r=>(Module._PushCopiedSnapshot=wasmExports.PushCopiedSnapshot)(r),Module._UpdateActiveSnapshotCommandId=()=>(Module._UpdateActiveSnapshotCommandId=wasmExports.UpdateActiveSnapshotCommandId)(),Module._CreateQueryDesc=(r,e,M,tr,rr,ir,lr,dr)=>(Module._CreateQueryDesc=wasmExports.CreateQueryDesc)(r,e,M,tr,rr,ir,lr,dr),Module._ExecutorStart=(r,e)=>(Module._ExecutorStart=wasmExports.ExecutorStart)(r,e),Module._ExecutorFinish=r=>(Module._ExecutorFinish=wasmExports.ExecutorFinish)(r),Module._ExecutorEnd=r=>(Module._ExecutorEnd=wasmExports.ExecutorEnd)(r),Module._FreeQueryDesc=r=>(Module._FreeQueryDesc=wasmExports.FreeQueryDesc)(r),Module._pg_server_to_any=(r,e,M)=>(Module._pg_server_to_any=wasmExports.pg_server_to_any)(r,e,M),Module._ExecutorRun=(r,e,M,tr)=>(Module._ExecutorRun=wasmExports.ExecutorRun)(r,e,M,tr),Module._CreateTableAsRelExists=r=>(Module._CreateTableAsRelExists=wasmExports.CreateTableAsRelExists)(r),Module._DefineRelation=(r,e,M,tr,rr,ir)=>(Module._DefineRelation=wasmExports.DefineRelation)(r,e,M,tr,rr,ir),Module._oidin=r=>(Module._oidin=wasmExports.oidin)(r),Module._GetCommandTagName=r=>(Module._GetCommandTagName=wasmExports.GetCommandTagName)(r),Module._ExplainBeginOutput=r=>(Module._ExplainBeginOutput=wasmExports.ExplainBeginOutput)(r),Module._NewExplainState=()=>(Module._NewExplainState=wasmExports.NewExplainState)(),Module._ExplainEndOutput=r=>(Module._ExplainEndOutput=wasmExports.ExplainEndOutput)(r),Module._ExplainPrintPlan=(r,e)=>(Module._ExplainPrintPlan=wasmExports.ExplainPrintPlan)(r,e),Module._ExplainPrintTriggers=(r,e)=>(Module._ExplainPrintTriggers=wasmExports.ExplainPrintTriggers)(r,e),Module._ExplainPrintJITSummary=(r,e)=>(Module._ExplainPrintJITSummary=wasmExports.ExplainPrintJITSummary)(r,e),Module._InstrEndLoop=r=>(Module._InstrEndLoop=wasmExports.InstrEndLoop)(r),Module._ExplainPropertyInteger=(r,e,M,tr)=>(Module._ExplainPropertyInteger=wasmExports.ExplainPropertyInteger)(r,e,M,tr),Module._ExplainQueryText=(r,e)=>(Module._ExplainQueryText=wasmExports.ExplainQueryText)(r,e),Module._ExplainPropertyText=(r,e,M)=>(Module._ExplainPropertyText=wasmExports.ExplainPropertyText)(r,e,M),Module._ExplainQueryParameters=(r,e,M)=>(Module._ExplainQueryParameters=wasmExports.ExplainQueryParameters)(r,e,M),Module._get_func_namespace=r=>(Module._get_func_namespace=wasmExports.get_func_namespace)(r),Module._get_rel_type_id=r=>(Module._get_rel_type_id=wasmExports.get_rel_type_id)(r),Module._set_config_option=(r,e,M,tr,rr,ir,lr,dr)=>(Module._set_config_option=wasmExports.set_config_option)(r,e,M,tr,rr,ir,lr,dr),Module._pg_any_to_server=(r,e,M)=>(Module._pg_any_to_server=wasmExports.pg_any_to_server)(r,e,M),Module._DirectFunctionCall4Coll=(r,e,M,tr,rr,ir)=>(Module._DirectFunctionCall4Coll=wasmExports.DirectFunctionCall4Coll)(r,e,M,tr,rr,ir),Module._list_delete_cell=(r,e)=>(Module._list_delete_cell=wasmExports.list_delete_cell)(r,e),Module._GetForeignDataWrapper=r=>(Module._GetForeignDataWrapper=wasmExports.GetForeignDataWrapper)(r),Module._CreateExprContext=r=>(Module._CreateExprContext=wasmExports.CreateExprContext)(r),Module._EnsurePortalSnapshotExists=()=>(Module._EnsurePortalSnapshotExists=wasmExports.EnsurePortalSnapshotExists)(),Module._CheckIndexCompatible=(r,e,M,tr)=>(Module._CheckIndexCompatible=wasmExports.CheckIndexCompatible)(r,e,M,tr),Module._pgstat_count_truncate=r=>(Module._pgstat_count_truncate=wasmExports.pgstat_count_truncate)(r),Module._SPI_connect=()=>(Module._SPI_connect=wasmExports.SPI_connect)(),Module._SPI_exec=(r,e)=>(Module._SPI_exec=wasmExports.SPI_exec)(r,e),Module._SPI_execute=(r,e,M)=>(Module._SPI_execute=wasmExports.SPI_execute)(r,e,M),Module._SPI_getvalue=(r,e,M)=>(Module._SPI_getvalue=wasmExports.SPI_getvalue)(r,e,M),Module._generate_operator_clause=(r,e,M,tr,rr,ir)=>(Module._generate_operator_clause=wasmExports.generate_operator_clause)(r,e,M,tr,rr,ir),Module._SPI_finish=()=>(Module._SPI_finish=wasmExports.SPI_finish)(),Module._CreateTransientRelDestReceiver=r=>(Module._CreateTransientRelDestReceiver=wasmExports.CreateTransientRelDestReceiver)(r),Module._MemoryContextSetIdentifier=(r,e)=>(Module._MemoryContextSetIdentifier=wasmExports.MemoryContextSetIdentifier)(r,e),Module._checkExprHasSubLink=r=>(Module._checkExprHasSubLink=wasmExports.checkExprHasSubLink)(r),Module._SetTuplestoreDestReceiverParams=(r,e,M,tr,rr,ir)=>(Module._SetTuplestoreDestReceiverParams=wasmExports.SetTuplestoreDestReceiverParams)(r,e,M,tr,rr,ir),Module._tuplestore_rescan=r=>(Module._tuplestore_rescan=wasmExports.tuplestore_rescan)(r),Module._MemoryContextDeleteChildren=r=>(Module._MemoryContextDeleteChildren=wasmExports.MemoryContextDeleteChildren)(r),Module._ReleaseCachedPlan=(r,e)=>(Module._ReleaseCachedPlan=wasmExports.ReleaseCachedPlan)(r,e),Module._nextval=r=>(Module._nextval=wasmExports.nextval)(r),Module._textToQualifiedNameList=r=>(Module._textToQualifiedNameList=wasmExports.textToQualifiedNameList)(r),Module._tuplestore_gettupleslot=(r,e,M,tr)=>(Module._tuplestore_gettupleslot=wasmExports.tuplestore_gettupleslot)(r,e,M,tr),Module._list_delete=(r,e)=>(Module._list_delete=wasmExports.list_delete)(r,e),Module._tuplestore_end=r=>(Module._tuplestore_end=wasmExports.tuplestore_end)(r),Module._quote_literal_cstr=r=>(Module._quote_literal_cstr=wasmExports.quote_literal_cstr)(r),Module._contain_mutable_functions=r=>(Module._contain_mutable_functions=wasmExports.contain_mutable_functions)(r),Module._ExecuteTruncateGuts=(r,e,M,tr,rr,ir)=>(Module._ExecuteTruncateGuts=wasmExports.ExecuteTruncateGuts)(r,e,M,tr,rr,ir),Module._bms_make_singleton=r=>(Module._bms_make_singleton=wasmExports.bms_make_singleton)(r),Module._tuplestore_puttupleslot=(r,e)=>(Module._tuplestore_puttupleslot=wasmExports.tuplestore_puttupleslot)(r,e),Module._tuplestore_begin_heap=(r,e,M)=>(Module._tuplestore_begin_heap=wasmExports.tuplestore_begin_heap)(r,e,M),Module._ExecForceStoreHeapTuple=(r,e,M)=>(Module._ExecForceStoreHeapTuple=wasmExports.ExecForceStoreHeapTuple)(r,e,M),Module._strtod=(r,e)=>(Module._strtod=wasmExports.strtod)(r,e),Module._plain_crypt_verify=(r,e,M,tr)=>(Module._plain_crypt_verify=wasmExports.plain_crypt_verify)(r,e,M,tr),Module._ProcessConfigFile=r=>(Module._ProcessConfigFile=wasmExports.ProcessConfigFile)(r),Module._ExecReScan=r=>(Module._ExecReScan=wasmExports.ExecReScan)(r),Module._ExecAsyncResponse=r=>(Module._ExecAsyncResponse=wasmExports.ExecAsyncResponse)(r),Module._ExecAsyncRequestDone=(r,e)=>(Module._ExecAsyncRequestDone=wasmExports.ExecAsyncRequestDone)(r,e),Module._ExecAsyncRequestPending=r=>(Module._ExecAsyncRequestPending=wasmExports.ExecAsyncRequestPending)(r),Module._ExprEvalPushStep=(r,e)=>(Module._ExprEvalPushStep=wasmExports.ExprEvalPushStep)(r,e),Module._ExecInitExprWithParams=(r,e)=>(Module._ExecInitExprWithParams=wasmExports.ExecInitExprWithParams)(r,e),Module._ExecInitExprList=(r,e)=>(Module._ExecInitExprList=wasmExports.ExecInitExprList)(r,e),Module._MakeExpandedObjectReadOnlyInternal=r=>(Module._MakeExpandedObjectReadOnlyInternal=wasmExports.MakeExpandedObjectReadOnlyInternal)(r),Module._tuplesort_puttupleslot=(r,e)=>(Module._tuplesort_puttupleslot=wasmExports.tuplesort_puttupleslot)(r,e),Module._ArrayGetNItems=(r,e)=>(Module._ArrayGetNItems=wasmExports.ArrayGetNItems)(r,e),Module._expanded_record_fetch_tupdesc=r=>(Module._expanded_record_fetch_tupdesc=wasmExports.expanded_record_fetch_tupdesc)(r),Module._expanded_record_fetch_field=(r,e,M)=>(Module._expanded_record_fetch_field=wasmExports.expanded_record_fetch_field)(r,e,M),Module._JsonbValueToJsonb=r=>(Module._JsonbValueToJsonb=wasmExports.JsonbValueToJsonb)(r),Module._boolout=r=>(Module._boolout=wasmExports.boolout)(r),Module._lookup_rowtype_tupdesc_domain=(r,e,M)=>(Module._lookup_rowtype_tupdesc_domain=wasmExports.lookup_rowtype_tupdesc_domain)(r,e,M),Module._MemoryContextGetParent=r=>(Module._MemoryContextGetParent=wasmExports.MemoryContextGetParent)(r),Module._DeleteExpandedObject=r=>(Module._DeleteExpandedObject=wasmExports.DeleteExpandedObject)(r),Module._ExecFindJunkAttributeInTlist=(r,e)=>(Module._ExecFindJunkAttributeInTlist=wasmExports.ExecFindJunkAttributeInTlist)(r,e),Module._standard_ExecutorStart=(r,e)=>(Module._standard_ExecutorStart=wasmExports.standard_ExecutorStart)(r,e),Module._standard_ExecutorRun=(r,e,M,tr)=>(Module._standard_ExecutorRun=wasmExports.standard_ExecutorRun)(r,e,M,tr),Module._standard_ExecutorFinish=r=>(Module._standard_ExecutorFinish=wasmExports.standard_ExecutorFinish)(r),Module._standard_ExecutorEnd=r=>(Module._standard_ExecutorEnd=wasmExports.standard_ExecutorEnd)(r),Module._InstrAlloc=(r,e,M)=>(Module._InstrAlloc=wasmExports.InstrAlloc)(r,e,M),Module._get_typlenbyval=(r,e,M)=>(Module._get_typlenbyval=wasmExports.get_typlenbyval)(r,e,M),Module._InputFunctionCall=(r,e,M,tr)=>(Module._InputFunctionCall=wasmExports.InputFunctionCall)(r,e,M,tr),Module._FreeExprContext=(r,e)=>(Module._FreeExprContext=wasmExports.FreeExprContext)(r,e),Module._ExecOpenScanRelation=(r,e,M)=>(Module._ExecOpenScanRelation=wasmExports.ExecOpenScanRelation)(r,e,M),Module._bms_intersect=(r,e)=>(Module._bms_intersect=wasmExports.bms_intersect)(r,e),Module._ExecGetReturningSlot=(r,e)=>(Module._ExecGetReturningSlot=wasmExports.ExecGetReturningSlot)(r,e),Module._ExecGetResultRelCheckAsUser=(r,e)=>(Module._ExecGetResultRelCheckAsUser=wasmExports.ExecGetResultRelCheckAsUser)(r,e),Module._get_call_expr_argtype=(r,e)=>(Module._get_call_expr_argtype=wasmExports.get_call_expr_argtype)(r,e),Module._tuplestore_clear=r=>(Module._tuplestore_clear=wasmExports.tuplestore_clear)(r),Module._InstrUpdateTupleCount=(r,e)=>(Module._InstrUpdateTupleCount=wasmExports.InstrUpdateTupleCount)(r,e),Module._tuplesort_begin_heap=(r,e,M,tr,rr,ir,lr,dr,hr)=>(Module._tuplesort_begin_heap=wasmExports.tuplesort_begin_heap)(r,e,M,tr,rr,ir,lr,dr,hr),Module._tuplesort_gettupleslot=(r,e,M,tr,rr)=>(Module._tuplesort_gettupleslot=wasmExports.tuplesort_gettupleslot)(r,e,M,tr,rr),Module._AddWaitEventToSet=(r,e,M,tr,rr)=>(Module._AddWaitEventToSet=wasmExports.AddWaitEventToSet)(r,e,M,tr,rr),Module._GetNumRegisteredWaitEvents=r=>(Module._GetNumRegisteredWaitEvents=wasmExports.GetNumRegisteredWaitEvents)(r),Module._get_attstatsslot=(r,e,M,tr,rr)=>(Module._get_attstatsslot=wasmExports.get_attstatsslot)(r,e,M,tr,rr),Module._free_attstatsslot=r=>(Module._free_attstatsslot=wasmExports.free_attstatsslot)(r),Module._tuplesort_reset=r=>(Module._tuplesort_reset=wasmExports.tuplesort_reset)(r),Module._pairingheap_first=r=>(Module._pairingheap_first=wasmExports.pairingheap_first)(r),Module._bms_nonempty_difference=(r,e)=>(Module._bms_nonempty_difference=wasmExports.bms_nonempty_difference)(r,e),Module._SPI_connect_ext=r=>(Module._SPI_connect_ext=wasmExports.SPI_connect_ext)(r),Module._SPI_commit=()=>(Module._SPI_commit=wasmExports.SPI_commit)(),Module._CopyErrorData=()=>(Module._CopyErrorData=wasmExports.CopyErrorData)(),Module._ReThrowError=r=>(Module._ReThrowError=wasmExports.ReThrowError)(r),Module._SPI_commit_and_chain=()=>(Module._SPI_commit_and_chain=wasmExports.SPI_commit_and_chain)(),Module._SPI_rollback=()=>(Module._SPI_rollback=wasmExports.SPI_rollback)(),Module._SPI_rollback_and_chain=()=>(Module._SPI_rollback_and_chain=wasmExports.SPI_rollback_and_chain)(),Module._SPI_freetuptable=r=>(Module._SPI_freetuptable=wasmExports.SPI_freetuptable)(r),Module._SPI_execute_extended=(r,e)=>(Module._SPI_execute_extended=wasmExports.SPI_execute_extended)(r,e),Module._SPI_execute_plan=(r,e,M,tr,rr)=>(Module._SPI_execute_plan=wasmExports.SPI_execute_plan)(r,e,M,tr,rr),Module._SPI_execp=(r,e,M,tr)=>(Module._SPI_execp=wasmExports.SPI_execp)(r,e,M,tr),Module._SPI_execute_plan_extended=(r,e)=>(Module._SPI_execute_plan_extended=wasmExports.SPI_execute_plan_extended)(r,e),Module._SPI_execute_plan_with_paramlist=(r,e,M,tr)=>(Module._SPI_execute_plan_with_paramlist=wasmExports.SPI_execute_plan_with_paramlist)(r,e,M,tr),Module._SPI_prepare=(r,e,M)=>(Module._SPI_prepare=wasmExports.SPI_prepare)(r,e,M),Module._SPI_prepare_extended=(r,e)=>(Module._SPI_prepare_extended=wasmExports.SPI_prepare_extended)(r,e),Module._SPI_keepplan=r=>(Module._SPI_keepplan=wasmExports.SPI_keepplan)(r),Module._SPI_freeplan=r=>(Module._SPI_freeplan=wasmExports.SPI_freeplan)(r),Module._SPI_copytuple=r=>(Module._SPI_copytuple=wasmExports.SPI_copytuple)(r),Module._SPI_returntuple=(r,e)=>(Module._SPI_returntuple=wasmExports.SPI_returntuple)(r,e),Module._SPI_fnumber=(r,e)=>(Module._SPI_fnumber=wasmExports.SPI_fnumber)(r,e),Module._SPI_fname=(r,e)=>(Module._SPI_fname=wasmExports.SPI_fname)(r,e),Module._SPI_getbinval=(r,e,M,tr)=>(Module._SPI_getbinval=wasmExports.SPI_getbinval)(r,e,M,tr),Module._SPI_gettype=(r,e)=>(Module._SPI_gettype=wasmExports.SPI_gettype)(r,e),Module._SPI_gettypeid=(r,e)=>(Module._SPI_gettypeid=wasmExports.SPI_gettypeid)(r,e),Module._SPI_getrelname=r=>(Module._SPI_getrelname=wasmExports.SPI_getrelname)(r),Module._SPI_palloc=r=>(Module._SPI_palloc=wasmExports.SPI_palloc)(r),Module._SPI_datumTransfer=(r,e,M)=>(Module._SPI_datumTransfer=wasmExports.SPI_datumTransfer)(r,e,M),Module._datumTransfer=(r,e,M)=>(Module._datumTransfer=wasmExports.datumTransfer)(r,e,M),Module._SPI_cursor_open_with_paramlist=(r,e,M,tr)=>(Module._SPI_cursor_open_with_paramlist=wasmExports.SPI_cursor_open_with_paramlist)(r,e,M,tr),Module._SPI_cursor_parse_open=(r,e,M)=>(Module._SPI_cursor_parse_open=wasmExports.SPI_cursor_parse_open)(r,e,M),Module._SPI_cursor_find=r=>(Module._SPI_cursor_find=wasmExports.SPI_cursor_find)(r),Module._SPI_cursor_fetch=(r,e,M)=>(Module._SPI_cursor_fetch=wasmExports.SPI_cursor_fetch)(r,e,M),Module._SPI_scroll_cursor_fetch=(r,e,M)=>(Module._SPI_scroll_cursor_fetch=wasmExports.SPI_scroll_cursor_fetch)(r,e,M),Module._SPI_scroll_cursor_move=(r,e,M)=>(Module._SPI_scroll_cursor_move=wasmExports.SPI_scroll_cursor_move)(r,e,M),Module._SPI_cursor_close=r=>(Module._SPI_cursor_close=wasmExports.SPI_cursor_close)(r),Module._SPI_plan_is_valid=r=>(Module._SPI_plan_is_valid=wasmExports.SPI_plan_is_valid)(r),Module._SPI_result_code_string=r=>(Module._SPI_result_code_string=wasmExports.SPI_result_code_string)(r),Module._SPI_plan_get_plan_sources=r=>(Module._SPI_plan_get_plan_sources=wasmExports.SPI_plan_get_plan_sources)(r),Module._SPI_plan_get_cached_plan=r=>(Module._SPI_plan_get_cached_plan=wasmExports.SPI_plan_get_cached_plan)(r),Module._SPI_register_relation=r=>(Module._SPI_register_relation=wasmExports.SPI_register_relation)(r),Module._create_queryEnv=()=>(Module._create_queryEnv=wasmExports.create_queryEnv)(),Module._register_ENR=(r,e)=>(Module._register_ENR=wasmExports.register_ENR)(r,e),Module._SPI_register_trigger_data=r=>(Module._SPI_register_trigger_data=wasmExports.SPI_register_trigger_data)(r),Module._tuplestore_tuple_count=r=>(Module._tuplestore_tuple_count=wasmExports.tuplestore_tuple_count)(r),Module._GetUserMapping=(r,e)=>(Module._GetUserMapping=wasmExports.GetUserMapping)(r,e),Module._GetForeignTable=r=>(Module._GetForeignTable=wasmExports.GetForeignTable)(r),Module._GetForeignColumnOptions=(r,e)=>(Module._GetForeignColumnOptions=wasmExports.GetForeignColumnOptions)(r,e),Module._initClosestMatch=(r,e,M)=>(Module._initClosestMatch=wasmExports.initClosestMatch)(r,e,M),Module._updateClosestMatch=(r,e)=>(Module._updateClosestMatch=wasmExports.updateClosestMatch)(r,e),Module._getClosestMatch=r=>(Module._getClosestMatch=wasmExports.getClosestMatch)(r),Module._GetExistingLocalJoinPath=r=>(Module._GetExistingLocalJoinPath=wasmExports.GetExistingLocalJoinPath)(r),Module._bloom_create=(r,e,M)=>(Module._bloom_create=wasmExports.bloom_create)(r,e,M),Module._bloom_free=r=>(Module._bloom_free=wasmExports.bloom_free)(r),Module._bloom_add_element=(r,e,M)=>(Module._bloom_add_element=wasmExports.bloom_add_element)(r,e,M),Module._bloom_lacks_element=(r,e,M)=>(Module._bloom_lacks_element=wasmExports.bloom_lacks_element)(r,e,M),Module._bloom_prop_bits_set=r=>(Module._bloom_prop_bits_set=wasmExports.bloom_prop_bits_set)(r),Module._gai_strerror=r=>(Module._gai_strerror=wasmExports.gai_strerror)(r),Module._socket=(r,e,M)=>(Module._socket=wasmExports.socket)(r,e,M),Module._connect=(r,e,M)=>(Module._connect=wasmExports.connect)(r,e,M),Module._send=(r,e,M,tr)=>(Module._send=wasmExports.send)(r,e,M,tr),Module._recv=(r,e,M,tr)=>(Module._recv=wasmExports.recv)(r,e,M,tr),Module._be_lo_unlink=r=>(Module._be_lo_unlink=wasmExports.be_lo_unlink)(r),Module._text_to_cstring_buffer=(r,e,M)=>(Module._text_to_cstring_buffer=wasmExports.text_to_cstring_buffer)(r,e,M),Module._set_read_write_cbs=(r,e)=>(Module._set_read_write_cbs=wasmExports.set_read_write_cbs)(r,e),Module._setsockopt=(r,e,M,tr,rr)=>(Module._setsockopt=wasmExports.setsockopt)(r,e,M,tr,rr),Module._getsockopt=(r,e,M,tr,rr)=>(Module._getsockopt=wasmExports.getsockopt)(r,e,M,tr,rr),Module._getsockname=(r,e,M)=>(Module._getsockname=wasmExports.getsockname)(r,e,M),Module._poll=(r,e,M)=>(Module._poll=wasmExports.poll)(r,e,M),Module._pg_mb2wchar_with_len=(r,e,M)=>(Module._pg_mb2wchar_with_len=wasmExports.pg_mb2wchar_with_len)(r,e,M),Module._pg_regcomp=(r,e,M,tr,rr)=>(Module._pg_regcomp=wasmExports.pg_regcomp)(r,e,M,tr,rr),Module._pg_regerror=(r,e,M,tr)=>(Module._pg_regerror=wasmExports.pg_regerror)(r,e,M,tr),Module._strcat=(r,e)=>(Module._strcat=wasmExports.strcat)(r,e),Module._pq_sendtext=(r,e,M)=>(Module._pq_sendtext=wasmExports.pq_sendtext)(r,e,M),Module._pq_sendfloat4=(r,e)=>(Module._pq_sendfloat4=wasmExports.pq_sendfloat4)(r,e),Module._pq_sendfloat8=(r,e)=>(Module._pq_sendfloat8=wasmExports.pq_sendfloat8)(r,e),Module._pq_begintypsend=r=>(Module._pq_begintypsend=wasmExports.pq_begintypsend)(r),Module._pq_endtypsend=r=>(Module._pq_endtypsend=wasmExports.pq_endtypsend)(r),Module._pq_getmsgfloat4=r=>(Module._pq_getmsgfloat4=wasmExports.pq_getmsgfloat4)(r),Module._pq_getmsgfloat8=r=>(Module._pq_getmsgfloat8=wasmExports.pq_getmsgfloat8)(r),Module._pq_getmsgtext=(r,e,M)=>(Module._pq_getmsgtext=wasmExports.pq_getmsgtext)(r,e,M),Module._pg_strtoint32=r=>(Module._pg_strtoint32=wasmExports.pg_strtoint32)(r),Module._bms_membership=r=>(Module._bms_membership=wasmExports.bms_membership)(r),Module._list_make5_impl=(r,e,M,tr,rr,ir)=>(Module._list_make5_impl=wasmExports.list_make5_impl)(r,e,M,tr,rr,ir),Module._list_insert_nth=(r,e,M)=>(Module._list_insert_nth=wasmExports.list_insert_nth)(r,e,M),Module._list_member_ptr=(r,e)=>(Module._list_member_ptr=wasmExports.list_member_ptr)(r,e),Module._list_append_unique_ptr=(r,e)=>(Module._list_append_unique_ptr=wasmExports.list_append_unique_ptr)(r,e),Module._make_opclause=(r,e,M,tr,rr,ir,lr)=>(Module._make_opclause=wasmExports.make_opclause)(r,e,M,tr,rr,ir,lr),Module._exprIsLengthCoercion=(r,e)=>(Module._exprIsLengthCoercion=wasmExports.exprIsLengthCoercion)(r,e),Module._fix_opfuncids=r=>(Module._fix_opfuncids=wasmExports.fix_opfuncids)(r),Module._CleanQuerytext=(r,e,M)=>(Module._CleanQuerytext=wasmExports.CleanQuerytext)(r,e,M),Module._EnableQueryId=()=>(Module._EnableQueryId=wasmExports.EnableQueryId)(),Module._find_base_rel=(r,e)=>(Module._find_base_rel=wasmExports.find_base_rel)(r,e),Module._add_path=(r,e)=>(Module._add_path=wasmExports.add_path)(r,e),Module._pathkeys_contained_in=(r,e)=>(Module._pathkeys_contained_in=wasmExports.pathkeys_contained_in)(r,e),Module._create_sort_path=(r,e,M,tr,rr)=>(Module._create_sort_path=wasmExports.create_sort_path)(r,e,M,tr,rr),Module._set_baserel_size_estimates=(r,e)=>(Module._set_baserel_size_estimates=wasmExports.set_baserel_size_estimates)(r,e),Module._clauselist_selectivity=(r,e,M,tr,rr)=>(Module._clauselist_selectivity=wasmExports.clauselist_selectivity)(r,e,M,tr,rr),Module._get_tablespace_page_costs=(r,e,M)=>(Module._get_tablespace_page_costs=wasmExports.get_tablespace_page_costs)(r,e,M),Module._cost_qual_eval=(r,e,M)=>(Module._cost_qual_eval=wasmExports.cost_qual_eval)(r,e,M),Module._estimate_num_groups=(r,e,M,tr,rr)=>(Module._estimate_num_groups=wasmExports.estimate_num_groups)(r,e,M,tr,rr),Module._cost_sort=(r,e,M,tr,rr,ir,lr,dr,hr)=>(Module._cost_sort=wasmExports.cost_sort)(r,e,M,tr,rr,ir,lr,dr,hr),Module._get_sortgrouplist_exprs=(r,e)=>(Module._get_sortgrouplist_exprs=wasmExports.get_sortgrouplist_exprs)(r,e),Module._make_restrictinfo=(r,e,M,tr,rr,ir,lr,dr,hr,fr)=>(Module._make_restrictinfo=wasmExports.make_restrictinfo)(r,e,M,tr,rr,ir,lr,dr,hr,fr),Module._generate_implied_equalities_for_column=(r,e,M,tr,rr)=>(Module._generate_implied_equalities_for_column=wasmExports.generate_implied_equalities_for_column)(r,e,M,tr,rr),Module._eclass_useful_for_merging=(r,e,M)=>(Module._eclass_useful_for_merging=wasmExports.eclass_useful_for_merging)(r,e,M),Module._join_clause_is_movable_to=(r,e)=>(Module._join_clause_is_movable_to=wasmExports.join_clause_is_movable_to)(r,e),Module._get_plan_rowmark=(r,e)=>(Module._get_plan_rowmark=wasmExports.get_plan_rowmark)(r,e),Module._update_mergeclause_eclasses=(r,e)=>(Module._update_mergeclause_eclasses=wasmExports.update_mergeclause_eclasses)(r,e),Module._find_join_rel=(r,e)=>(Module._find_join_rel=wasmExports.find_join_rel)(r,e),Module._make_canonical_pathkey=(r,e,M,tr,rr)=>(Module._make_canonical_pathkey=wasmExports.make_canonical_pathkey)(r,e,M,tr,rr),Module._get_sortgroupref_clause_noerr=(r,e)=>(Module._get_sortgroupref_clause_noerr=wasmExports.get_sortgroupref_clause_noerr)(r,e),Module._extract_actual_clauses=(r,e)=>(Module._extract_actual_clauses=wasmExports.extract_actual_clauses)(r,e),Module._change_plan_targetlist=(r,e,M)=>(Module._change_plan_targetlist=wasmExports.change_plan_targetlist)(r,e,M),Module._make_foreignscan=(r,e,M,tr,rr,ir,lr,dr)=>(Module._make_foreignscan=wasmExports.make_foreignscan)(r,e,M,tr,rr,ir,lr,dr),Module._tlist_member=(r,e)=>(Module._tlist_member=wasmExports.tlist_member)(r,e),Module._pull_vars_of_level=(r,e)=>(Module._pull_vars_of_level=wasmExports.pull_vars_of_level)(r,e),Module._IncrementVarSublevelsUp=(r,e,M)=>(Module._IncrementVarSublevelsUp=wasmExports.IncrementVarSublevelsUp)(r,e,M),Module._standard_planner=(r,e,M,tr)=>(Module._standard_planner=wasmExports.standard_planner)(r,e,M,tr),Module._get_relids_in_jointree=(r,e,M)=>(Module._get_relids_in_jointree=wasmExports.get_relids_in_jointree)(r,e,M),Module._add_new_columns_to_pathtarget=(r,e)=>(Module._add_new_columns_to_pathtarget=wasmExports.add_new_columns_to_pathtarget)(r,e),Module._get_agg_clause_costs=(r,e,M)=>(Module._get_agg_clause_costs=wasmExports.get_agg_clause_costs)(r,e,M),Module._grouping_is_sortable=r=>(Module._grouping_is_sortable=wasmExports.grouping_is_sortable)(r),Module._copy_pathtarget=r=>(Module._copy_pathtarget=wasmExports.copy_pathtarget)(r),Module._create_projection_path=(r,e,M,tr)=>(Module._create_projection_path=wasmExports.create_projection_path)(r,e,M,tr),Module._GetSysCacheHashValue=(r,e,M,tr,rr)=>(Module._GetSysCacheHashValue=wasmExports.GetSysCacheHashValue)(r,e,M,tr,rr),Module._get_translated_update_targetlist=(r,e,M,tr)=>(Module._get_translated_update_targetlist=wasmExports.get_translated_update_targetlist)(r,e,M,tr),Module._add_row_identity_var=(r,e,M,tr)=>(Module._add_row_identity_var=wasmExports.add_row_identity_var)(r,e,M,tr),Module._get_rel_all_updated_cols=(r,e)=>(Module._get_rel_all_updated_cols=wasmExports.get_rel_all_updated_cols)(r,e),Module._get_baserel_parampathinfo=(r,e,M)=>(Module._get_baserel_parampathinfo=wasmExports.get_baserel_parampathinfo)(r,e,M),Module._create_foreignscan_path=(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr)=>(Module._create_foreignscan_path=wasmExports.create_foreignscan_path)(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr),Module._create_foreign_join_path=(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr)=>(Module._create_foreign_join_path=wasmExports.create_foreign_join_path)(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr),Module._create_foreign_upper_path=(r,e,M,tr,rr,ir,lr,dr,hr,fr)=>(Module._create_foreign_upper_path=wasmExports.create_foreign_upper_path)(r,e,M,tr,rr,ir,lr,dr,hr,fr),Module._adjust_limit_rows_costs=(r,e,M,tr,rr)=>(Module._adjust_limit_rows_costs=wasmExports.adjust_limit_rows_costs)(r,e,M,tr,rr),Module._add_to_flat_tlist=(r,e)=>(Module._add_to_flat_tlist=wasmExports.add_to_flat_tlist)(r,e),Module._get_fn_expr_argtype=(r,e)=>(Module._get_fn_expr_argtype=wasmExports.get_fn_expr_argtype)(r,e),Module._on_shmem_exit=(r,e)=>(Module._on_shmem_exit=wasmExports.on_shmem_exit)(r,e),Module._SignalHandlerForConfigReload=r=>(Module._SignalHandlerForConfigReload=wasmExports.SignalHandlerForConfigReload)(r),Module._SignalHandlerForShutdownRequest=r=>(Module._SignalHandlerForShutdownRequest=wasmExports.SignalHandlerForShutdownRequest)(r),Module._procsignal_sigusr1_handler=r=>(Module._procsignal_sigusr1_handler=wasmExports.procsignal_sigusr1_handler)(r),Module._RegisterBackgroundWorker=r=>(Module._RegisterBackgroundWorker=wasmExports.RegisterBackgroundWorker)(r),Module._WaitForBackgroundWorkerStartup=(r,e)=>(Module._WaitForBackgroundWorkerStartup=wasmExports.WaitForBackgroundWorkerStartup)(r,e),Module._GetConfigOption=(r,e,M)=>(Module._GetConfigOption=wasmExports.GetConfigOption)(r,e,M),Module._toupper=r=>(Module._toupper=wasmExports.toupper)(r),Module._pg_reg_getinitialstate=r=>(Module._pg_reg_getinitialstate=wasmExports.pg_reg_getinitialstate)(r),Module._pg_reg_getfinalstate=r=>(Module._pg_reg_getfinalstate=wasmExports.pg_reg_getfinalstate)(r),Module._pg_reg_getnumoutarcs=(r,e)=>(Module._pg_reg_getnumoutarcs=wasmExports.pg_reg_getnumoutarcs)(r,e),Module._pg_reg_getoutarcs=(r,e,M,tr)=>(Module._pg_reg_getoutarcs=wasmExports.pg_reg_getoutarcs)(r,e,M,tr),Module._pg_reg_getnumcolors=r=>(Module._pg_reg_getnumcolors=wasmExports.pg_reg_getnumcolors)(r),Module._pg_reg_colorisbegin=(r,e)=>(Module._pg_reg_colorisbegin=wasmExports.pg_reg_colorisbegin)(r,e),Module._pg_reg_colorisend=(r,e)=>(Module._pg_reg_colorisend=wasmExports.pg_reg_colorisend)(r,e),Module._pg_reg_getnumcharacters=(r,e)=>(Module._pg_reg_getnumcharacters=wasmExports.pg_reg_getnumcharacters)(r,e),Module._pg_reg_getcharacters=(r,e,M,tr)=>(Module._pg_reg_getcharacters=wasmExports.pg_reg_getcharacters)(r,e,M,tr),Module._OutputPluginPrepareWrite=(r,e)=>(Module._OutputPluginPrepareWrite=wasmExports.OutputPluginPrepareWrite)(r,e),Module._OutputPluginWrite=(r,e)=>(Module._OutputPluginWrite=wasmExports.OutputPluginWrite)(r,e),Module._array_contains_nulls=r=>(Module._array_contains_nulls=wasmExports.array_contains_nulls)(r),Module._hash_seq_term=r=>(Module._hash_seq_term=wasmExports.hash_seq_term)(r),Module._FreeErrorData=r=>(Module._FreeErrorData=wasmExports.FreeErrorData)(r),Module._RelidByRelfilenumber=(r,e)=>(Module._RelidByRelfilenumber=wasmExports.RelidByRelfilenumber)(r,e),Module._WaitLatchOrSocket=(r,e,M,tr,rr)=>(Module._WaitLatchOrSocket=wasmExports.WaitLatchOrSocket)(r,e,M,tr,rr),Module._get_row_security_policies=(r,e,M,tr,rr,ir,lr)=>(Module._get_row_security_policies=wasmExports.get_row_security_policies)(r,e,M,tr,rr,ir,lr),Module._hash_estimate_size=(r,e)=>(Module._hash_estimate_size=wasmExports.hash_estimate_size)(r,e),Module._ShmemInitHash=(r,e,M,tr,rr)=>(Module._ShmemInitHash=wasmExports.ShmemInitHash)(r,e,M,tr,rr),Module._LockBufHdr=r=>(Module._LockBufHdr=wasmExports.LockBufHdr)(r),Module._EvictUnpinnedBuffer=r=>(Module._EvictUnpinnedBuffer=wasmExports.EvictUnpinnedBuffer)(r),Module._have_free_buffer=()=>(Module._have_free_buffer=wasmExports.have_free_buffer)(),Module._copy_file=(r,e)=>(Module._copy_file=wasmExports.copy_file)(r,e),Module._AcquireExternalFD=()=>(Module._AcquireExternalFD=wasmExports.AcquireExternalFD)(),Module._GetNamedDSMSegment=(r,e,M,tr)=>(Module._GetNamedDSMSegment=wasmExports.GetNamedDSMSegment)(r,e,M,tr),Module._RequestAddinShmemSpace=r=>(Module._RequestAddinShmemSpace=wasmExports.RequestAddinShmemSpace)(r),Module._GetRunningTransactionData=()=>(Module._GetRunningTransactionData=wasmExports.GetRunningTransactionData)(),Module._BackendXidGetPid=r=>(Module._BackendXidGetPid=wasmExports.BackendXidGetPid)(r),Module._LWLockRegisterTranche=(r,e)=>(Module._LWLockRegisterTranche=wasmExports.LWLockRegisterTranche)(r,e),Module._GetNamedLWLockTranche=r=>(Module._GetNamedLWLockTranche=wasmExports.GetNamedLWLockTranche)(r),Module._LWLockNewTrancheId=()=>(Module._LWLockNewTrancheId=wasmExports.LWLockNewTrancheId)(),Module._RequestNamedLWLockTranche=(r,e)=>(Module._RequestNamedLWLockTranche=wasmExports.RequestNamedLWLockTranche)(r,e),Module._standard_ProcessUtility=(r,e,M,tr,rr,ir,lr,dr)=>(Module._standard_ProcessUtility=wasmExports.standard_ProcessUtility)(r,e,M,tr,rr,ir,lr,dr),Module._lookup_ts_dictionary_cache=r=>(Module._lookup_ts_dictionary_cache=wasmExports.lookup_ts_dictionary_cache)(r),Module._get_tsearch_config_filename=(r,e)=>(Module._get_tsearch_config_filename=wasmExports.get_tsearch_config_filename)(r,e),Module._lowerstr=r=>(Module._lowerstr=wasmExports.lowerstr)(r),Module._readstoplist=(r,e,M)=>(Module._readstoplist=wasmExports.readstoplist)(r,e,M),Module._lowerstr_with_len=(r,e)=>(Module._lowerstr_with_len=wasmExports.lowerstr_with_len)(r,e),Module._searchstoplist=(r,e)=>(Module._searchstoplist=wasmExports.searchstoplist)(r,e),Module._tsearch_readline_begin=(r,e)=>(Module._tsearch_readline_begin=wasmExports.tsearch_readline_begin)(r,e),Module._tsearch_readline=r=>(Module._tsearch_readline=wasmExports.tsearch_readline)(r),Module._t_isspace=r=>(Module._t_isspace=wasmExports.t_isspace)(r),Module._tsearch_readline_end=r=>(Module._tsearch_readline_end=wasmExports.tsearch_readline_end)(r),Module._stringToQualifiedNameList=(r,e)=>(Module._stringToQualifiedNameList=wasmExports.stringToQualifiedNameList)(r,e),Module._t_isdigit=r=>(Module._t_isdigit=wasmExports.t_isdigit)(r),Module._t_isalnum=r=>(Module._t_isalnum=wasmExports.t_isalnum)(r),Module._get_restriction_variable=(r,e,M,tr,rr,ir)=>(Module._get_restriction_variable=wasmExports.get_restriction_variable)(r,e,M,tr,rr,ir),Module._MemoryContextAllocHuge=(r,e)=>(Module._MemoryContextAllocHuge=wasmExports.MemoryContextAllocHuge)(r,e),Module._WaitEventExtensionNew=r=>(Module._WaitEventExtensionNew=wasmExports.WaitEventExtensionNew)(r),Module._expand_array=(r,e,M)=>(Module._expand_array=wasmExports.expand_array)(r,e,M),Module._arraycontsel=r=>(Module._arraycontsel=wasmExports.arraycontsel)(r),Module._arraycontjoinsel=r=>(Module._arraycontjoinsel=wasmExports.arraycontjoinsel)(r),Module._initArrayResult=(r,e,M)=>(Module._initArrayResult=wasmExports.initArrayResult)(r,e,M),Module._array_create_iterator=(r,e,M)=>(Module._array_create_iterator=wasmExports.array_create_iterator)(r,e,M),Module._array_iterate=(r,e,M)=>(Module._array_iterate=wasmExports.array_iterate)(r,e,M),Module._ArrayGetIntegerTypmods=(r,e)=>(Module._ArrayGetIntegerTypmods=wasmExports.ArrayGetIntegerTypmods)(r,e),Module._boolin=r=>(Module._boolin=wasmExports.boolin)(r),Module._cash_cmp=r=>(Module._cash_cmp=wasmExports.cash_cmp)(r),Module._int64_to_numeric=r=>(Module._int64_to_numeric=wasmExports.int64_to_numeric)(r),Module._numeric_div=r=>(Module._numeric_div=wasmExports.numeric_div)(r),Module._date_eq=r=>(Module._date_eq=wasmExports.date_eq)(r),Module._date_lt=r=>(Module._date_lt=wasmExports.date_lt)(r),Module._date_le=r=>(Module._date_le=wasmExports.date_le)(r),Module._date_gt=r=>(Module._date_gt=wasmExports.date_gt)(r),Module._date_ge=r=>(Module._date_ge=wasmExports.date_ge)(r),Module._date_cmp=r=>(Module._date_cmp=wasmExports.date_cmp)(r),Module._date_mi=r=>(Module._date_mi=wasmExports.date_mi)(r),Module._time_eq=r=>(Module._time_eq=wasmExports.time_eq)(r),Module._time_lt=r=>(Module._time_lt=wasmExports.time_lt)(r),Module._time_le=r=>(Module._time_le=wasmExports.time_le)(r),Module._time_gt=r=>(Module._time_gt=wasmExports.time_gt)(r),Module._time_ge=r=>(Module._time_ge=wasmExports.time_ge)(r),Module._time_cmp=r=>(Module._time_cmp=wasmExports.time_cmp)(r),Module._time_mi_time=r=>(Module._time_mi_time=wasmExports.time_mi_time)(r),Module._timetz_cmp=r=>(Module._timetz_cmp=wasmExports.timetz_cmp)(r),Module._TransferExpandedObject=(r,e)=>(Module._TransferExpandedObject=wasmExports.TransferExpandedObject)(r,e),Module._numeric_lt=r=>(Module._numeric_lt=wasmExports.numeric_lt)(r),Module._numeric_ge=r=>(Module._numeric_ge=wasmExports.numeric_ge)(r),Module._err_generic_string=(r,e)=>(Module._err_generic_string=wasmExports.err_generic_string)(r,e),Module._domain_check=(r,e,M,tr,rr)=>(Module._domain_check=wasmExports.domain_check)(r,e,M,tr,rr),Module._enum_lt=r=>(Module._enum_lt=wasmExports.enum_lt)(r),Module._enum_le=r=>(Module._enum_le=wasmExports.enum_le)(r),Module._enum_ge=r=>(Module._enum_ge=wasmExports.enum_ge)(r),Module._enum_gt=r=>(Module._enum_gt=wasmExports.enum_gt)(r),Module._enum_cmp=r=>(Module._enum_cmp=wasmExports.enum_cmp)(r),Module._make_expanded_record_from_typeid=(r,e,M)=>(Module._make_expanded_record_from_typeid=wasmExports.make_expanded_record_from_typeid)(r,e,M),Module._make_expanded_record_from_tupdesc=(r,e)=>(Module._make_expanded_record_from_tupdesc=wasmExports.make_expanded_record_from_tupdesc)(r,e),Module._make_expanded_record_from_exprecord=(r,e)=>(Module._make_expanded_record_from_exprecord=wasmExports.make_expanded_record_from_exprecord)(r,e),Module._expanded_record_set_tuple=(r,e,M,tr)=>(Module._expanded_record_set_tuple=wasmExports.expanded_record_set_tuple)(r,e,M,tr),Module._expanded_record_get_tuple=r=>(Module._expanded_record_get_tuple=wasmExports.expanded_record_get_tuple)(r),Module._deconstruct_expanded_record=r=>(Module._deconstruct_expanded_record=wasmExports.deconstruct_expanded_record)(r),Module._expanded_record_lookup_field=(r,e,M)=>(Module._expanded_record_lookup_field=wasmExports.expanded_record_lookup_field)(r,e,M),Module._expanded_record_set_field_internal=(r,e,M,tr,rr,ir)=>(Module._expanded_record_set_field_internal=wasmExports.expanded_record_set_field_internal)(r,e,M,tr,rr,ir),Module._expanded_record_set_fields=(r,e,M,tr)=>(Module._expanded_record_set_fields=wasmExports.expanded_record_set_fields)(r,e,M,tr),Module._float4in_internal=(r,e,M,tr,rr)=>(Module._float4in_internal=wasmExports.float4in_internal)(r,e,M,tr,rr),Module._strtof=(r,e)=>(Module._strtof=wasmExports.strtof)(r,e),Module._float8in_internal=(r,e,M,tr,rr)=>(Module._float8in_internal=wasmExports.float8in_internal)(r,e,M,tr,rr),Module._float8out_internal=r=>(Module._float8out_internal=wasmExports.float8out_internal)(r),Module._btfloat4cmp=r=>(Module._btfloat4cmp=wasmExports.btfloat4cmp)(r),Module._btfloat8cmp=r=>(Module._btfloat8cmp=wasmExports.btfloat8cmp)(r),Module._acos=r=>(Module._acos=wasmExports.acos)(r),Module._asin=r=>(Module._asin=wasmExports.asin)(r),Module._cos=r=>(Module._cos=wasmExports.cos)(r),Module._str_tolower=(r,e,M)=>(Module._str_tolower=wasmExports.str_tolower)(r,e,M),Module._pushJsonbValue=(r,e,M)=>(Module._pushJsonbValue=wasmExports.pushJsonbValue)(r,e,M),Module._numeric_float4=r=>(Module._numeric_float4=wasmExports.numeric_float4)(r),Module._numeric_cmp=r=>(Module._numeric_cmp=wasmExports.numeric_cmp)(r),Module._numeric_eq=r=>(Module._numeric_eq=wasmExports.numeric_eq)(r),Module._numeric_is_nan=r=>(Module._numeric_is_nan=wasmExports.numeric_is_nan)(r),Module._timestamp_cmp=r=>(Module._timestamp_cmp=wasmExports.timestamp_cmp)(r),Module._macaddr_cmp=r=>(Module._macaddr_cmp=wasmExports.macaddr_cmp)(r),Module._macaddr_lt=r=>(Module._macaddr_lt=wasmExports.macaddr_lt)(r),Module._macaddr_le=r=>(Module._macaddr_le=wasmExports.macaddr_le)(r),Module._macaddr_eq=r=>(Module._macaddr_eq=wasmExports.macaddr_eq)(r),Module._macaddr_ge=r=>(Module._macaddr_ge=wasmExports.macaddr_ge)(r),Module._macaddr_gt=r=>(Module._macaddr_gt=wasmExports.macaddr_gt)(r),Module._macaddr8_cmp=r=>(Module._macaddr8_cmp=wasmExports.macaddr8_cmp)(r),Module._macaddr8_lt=r=>(Module._macaddr8_lt=wasmExports.macaddr8_lt)(r),Module._macaddr8_le=r=>(Module._macaddr8_le=wasmExports.macaddr8_le)(r),Module._macaddr8_eq=r=>(Module._macaddr8_eq=wasmExports.macaddr8_eq)(r),Module._macaddr8_ge=r=>(Module._macaddr8_ge=wasmExports.macaddr8_ge)(r),Module._macaddr8_gt=r=>(Module._macaddr8_gt=wasmExports.macaddr8_gt)(r),Module._current_query=r=>(Module._current_query=wasmExports.current_query)(r),Module._unpack_sql_state=r=>(Module._unpack_sql_state=wasmExports.unpack_sql_state)(r),Module._get_fn_expr_rettype=r=>(Module._get_fn_expr_rettype=wasmExports.get_fn_expr_rettype)(r),Module._btnamecmp=r=>(Module._btnamecmp=wasmExports.btnamecmp)(r),Module._inet_in=r=>(Module._inet_in=wasmExports.inet_in)(r),Module._network_cmp=r=>(Module._network_cmp=wasmExports.network_cmp)(r),Module._convert_network_to_scalar=(r,e,M)=>(Module._convert_network_to_scalar=wasmExports.convert_network_to_scalar)(r,e,M),Module._numeric_gt=r=>(Module._numeric_gt=wasmExports.numeric_gt)(r),Module._numeric_le=r=>(Module._numeric_le=wasmExports.numeric_le)(r),Module._numeric_float8_no_overflow=r=>(Module._numeric_float8_no_overflow=wasmExports.numeric_float8_no_overflow)(r),Module._oidout=r=>(Module._oidout=wasmExports.oidout)(r),Module._interval_mi=r=>(Module._interval_mi=wasmExports.interval_mi)(r),Module._quote_ident=r=>(Module._quote_ident=wasmExports.quote_ident)(r),Module._pg_wchar2mb_with_len=(r,e,M)=>(Module._pg_wchar2mb_with_len=wasmExports.pg_wchar2mb_with_len)(r,e,M),Module._pg_get_indexdef_columns_extended=(r,e)=>(Module._pg_get_indexdef_columns_extended=wasmExports.pg_get_indexdef_columns_extended)(r,e),Module._pg_get_querydef=(r,e)=>(Module._pg_get_querydef=wasmExports.pg_get_querydef)(r,e),Module._strcspn=(r,e)=>(Module._strcspn=wasmExports.strcspn)(r,e),Module._generic_restriction_selectivity=(r,e,M,tr,rr,ir)=>(Module._generic_restriction_selectivity=wasmExports.generic_restriction_selectivity)(r,e,M,tr,rr,ir),Module._genericcostestimate=(r,e,M,tr)=>(Module._genericcostestimate=wasmExports.genericcostestimate)(r,e,M,tr),Module._tidin=r=>(Module._tidin=wasmExports.tidin)(r),Module._tidout=r=>(Module._tidout=wasmExports.tidout)(r),Module._timestamp_in=r=>(Module._timestamp_in=wasmExports.timestamp_in)(r),Module._timestamp_eq=r=>(Module._timestamp_eq=wasmExports.timestamp_eq)(r),Module._timestamp_lt=r=>(Module._timestamp_lt=wasmExports.timestamp_lt)(r),Module._timestamp_gt=r=>(Module._timestamp_gt=wasmExports.timestamp_gt)(r),Module._timestamp_le=r=>(Module._timestamp_le=wasmExports.timestamp_le)(r),Module._timestamp_ge=r=>(Module._timestamp_ge=wasmExports.timestamp_ge)(r),Module._interval_eq=r=>(Module._interval_eq=wasmExports.interval_eq)(r),Module._interval_lt=r=>(Module._interval_lt=wasmExports.interval_lt)(r),Module._interval_gt=r=>(Module._interval_gt=wasmExports.interval_gt)(r),Module._interval_le=r=>(Module._interval_le=wasmExports.interval_le)(r),Module._interval_ge=r=>(Module._interval_ge=wasmExports.interval_ge)(r),Module._interval_cmp=r=>(Module._interval_cmp=wasmExports.interval_cmp)(r),Module._timestamp_mi=r=>(Module._timestamp_mi=wasmExports.timestamp_mi)(r),Module._interval_um=r=>(Module._interval_um=wasmExports.interval_um)(r),Module._has_fn_opclass_options=r=>(Module._has_fn_opclass_options=wasmExports.has_fn_opclass_options)(r),Module._uuid_in=r=>(Module._uuid_in=wasmExports.uuid_in)(r),Module._uuid_out=r=>(Module._uuid_out=wasmExports.uuid_out)(r),Module._uuid_cmp=r=>(Module._uuid_cmp=wasmExports.uuid_cmp)(r),Module._gen_random_uuid=r=>(Module._gen_random_uuid=wasmExports.gen_random_uuid)(r),Module._varbit_in=r=>(Module._varbit_in=wasmExports.varbit_in)(r),Module._biteq=r=>(Module._biteq=wasmExports.biteq)(r),Module._bitlt=r=>(Module._bitlt=wasmExports.bitlt)(r),Module._bitle=r=>(Module._bitle=wasmExports.bitle)(r),Module._bitgt=r=>(Module._bitgt=wasmExports.bitgt)(r),Module._bitge=r=>(Module._bitge=wasmExports.bitge)(r),Module._bitcmp=r=>(Module._bitcmp=wasmExports.bitcmp)(r),Module._bpchareq=r=>(Module._bpchareq=wasmExports.bpchareq)(r),Module._bpcharlt=r=>(Module._bpcharlt=wasmExports.bpcharlt)(r),Module._bpcharle=r=>(Module._bpcharle=wasmExports.bpcharle)(r),Module._bpchargt=r=>(Module._bpchargt=wasmExports.bpchargt)(r),Module._bpcharge=r=>(Module._bpcharge=wasmExports.bpcharge)(r),Module._bpcharcmp=r=>(Module._bpcharcmp=wasmExports.bpcharcmp)(r),Module._texteq=r=>(Module._texteq=wasmExports.texteq)(r),Module._text_lt=r=>(Module._text_lt=wasmExports.text_lt)(r),Module._text_le=r=>(Module._text_le=wasmExports.text_le)(r),Module._text_gt=r=>(Module._text_gt=wasmExports.text_gt)(r),Module._text_ge=r=>(Module._text_ge=wasmExports.text_ge)(r),Module._bttextcmp=r=>(Module._bttextcmp=wasmExports.bttextcmp)(r),Module._byteaeq=r=>(Module._byteaeq=wasmExports.byteaeq)(r),Module._bytealt=r=>(Module._bytealt=wasmExports.bytealt)(r),Module._byteale=r=>(Module._byteale=wasmExports.byteale)(r),Module._byteagt=r=>(Module._byteagt=wasmExports.byteagt)(r),Module._byteage=r=>(Module._byteage=wasmExports.byteage)(r),Module._byteacmp=r=>(Module._byteacmp=wasmExports.byteacmp)(r),Module._to_hex32=r=>(Module._to_hex32=wasmExports.to_hex32)(r),Module._varstr_levenshtein=(r,e,M,tr,rr,ir,lr,dr)=>(Module._varstr_levenshtein=wasmExports.varstr_levenshtein)(r,e,M,tr,rr,ir,lr,dr),Module._pg_xml_init=r=>(Module._pg_xml_init=wasmExports.pg_xml_init)(r),Module._xmlInitParser=()=>(Module._xmlInitParser=wasmExports.xmlInitParser)(),Module._xml_ereport=(r,e,M,tr)=>(Module._xml_ereport=wasmExports.xml_ereport)(r,e,M,tr),Module._pg_xml_done=(r,e)=>(Module._pg_xml_done=wasmExports.pg_xml_done)(r,e),Module._xmlXPathNewContext=r=>(Module._xmlXPathNewContext=wasmExports.xmlXPathNewContext)(r),Module._xmlXPathFreeContext=r=>(Module._xmlXPathFreeContext=wasmExports.xmlXPathFreeContext)(r),Module._xmlFreeDoc=r=>(Module._xmlFreeDoc=wasmExports.xmlFreeDoc)(r),Module._xmlXPathCtxtCompile=(r,e)=>(Module._xmlXPathCtxtCompile=wasmExports.xmlXPathCtxtCompile)(r,e),Module._xmlXPathCompiledEval=(r,e)=>(Module._xmlXPathCompiledEval=wasmExports.xmlXPathCompiledEval)(r,e),Module._xmlXPathFreeObject=r=>(Module._xmlXPathFreeObject=wasmExports.xmlXPathFreeObject)(r),Module._xmlXPathFreeCompExpr=r=>(Module._xmlXPathFreeCompExpr=wasmExports.xmlXPathFreeCompExpr)(r),Module._pg_do_encoding_conversion=(r,e,M,tr)=>(Module._pg_do_encoding_conversion=wasmExports.pg_do_encoding_conversion)(r,e,M,tr),Module._xmlStrdup=r=>(Module._xmlStrdup=wasmExports.xmlStrdup)(r),Module._xmlEncodeSpecialChars=(r,e)=>(Module._xmlEncodeSpecialChars=wasmExports.xmlEncodeSpecialChars)(r,e),Module._xmlStrlen=r=>(Module._xmlStrlen=wasmExports.xmlStrlen)(r),Module._xmlBufferCreate=()=>(Module._xmlBufferCreate=wasmExports.xmlBufferCreate)(),Module._xmlBufferFree=r=>(Module._xmlBufferFree=wasmExports.xmlBufferFree)(r),Module._xmlXPathCastNodeToString=r=>(Module._xmlXPathCastNodeToString=wasmExports.xmlXPathCastNodeToString)(r),Module._xmlNodeDump=(r,e,M,tr,rr)=>(Module._xmlNodeDump=wasmExports.xmlNodeDump)(r,e,M,tr,rr),Module._get_typsubscript=(r,e)=>(Module._get_typsubscript=wasmExports.get_typsubscript)(r,e),Module._CachedPlanAllowsSimpleValidityCheck=(r,e,M)=>(Module._CachedPlanAllowsSimpleValidityCheck=wasmExports.CachedPlanAllowsSimpleValidityCheck)(r,e,M),Module._CachedPlanIsSimplyValid=(r,e,M)=>(Module._CachedPlanIsSimplyValid=wasmExports.CachedPlanIsSimplyValid)(r,e,M),Module._GetCachedExpression=r=>(Module._GetCachedExpression=wasmExports.GetCachedExpression)(r),Module._FreeCachedExpression=r=>(Module._FreeCachedExpression=wasmExports.FreeCachedExpression)(r),Module._ReleaseAllPlanCacheRefsInOwner=r=>(Module._ReleaseAllPlanCacheRefsInOwner=wasmExports.ReleaseAllPlanCacheRefsInOwner)(r),Module._in_error_recursion_trouble=()=>(Module._in_error_recursion_trouble=wasmExports.in_error_recursion_trouble)(),Module._GetErrorContextStack=()=>(Module._GetErrorContextStack=wasmExports.GetErrorContextStack)(),Module._find_rendezvous_variable=r=>(Module._find_rendezvous_variable=wasmExports.find_rendezvous_variable)(r),Module._CallerFInfoFunctionCall2=(r,e,M,tr,rr)=>(Module._CallerFInfoFunctionCall2=wasmExports.CallerFInfoFunctionCall2)(r,e,M,tr,rr),Module._FunctionCall0Coll=(r,e)=>(Module._FunctionCall0Coll=wasmExports.FunctionCall0Coll)(r,e),Module._resolve_polymorphic_argtypes=(r,e,M,tr)=>(Module._resolve_polymorphic_argtypes=wasmExports.resolve_polymorphic_argtypes)(r,e,M,tr),Module._pg_bindtextdomain=r=>(Module._pg_bindtextdomain=wasmExports.pg_bindtextdomain)(r),Module._DefineCustomBoolVariable=(r,e,M,tr,rr,ir,lr,dr,hr,fr)=>(Module._DefineCustomBoolVariable=wasmExports.DefineCustomBoolVariable)(r,e,M,tr,rr,ir,lr,dr,hr,fr),Module._DefineCustomIntVariable=(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r)=>(Module._DefineCustomIntVariable=wasmExports.DefineCustomIntVariable)(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r),Module._DefineCustomRealVariable=(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r)=>(Module._DefineCustomRealVariable=wasmExports.DefineCustomRealVariable)(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r),Module._DefineCustomStringVariable=(r,e,M,tr,rr,ir,lr,dr,hr,fr)=>(Module._DefineCustomStringVariable=wasmExports.DefineCustomStringVariable)(r,e,M,tr,rr,ir,lr,dr,hr,fr),Module._DefineCustomEnumVariable=(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr)=>(Module._DefineCustomEnumVariable=wasmExports.DefineCustomEnumVariable)(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr),Module._MarkGUCPrefixReserved=r=>(Module._MarkGUCPrefixReserved=wasmExports.MarkGUCPrefixReserved)(r),Module._sampler_random_init_state=(r,e)=>(Module._sampler_random_init_state=wasmExports.sampler_random_init_state)(r,e),Module._pchomp=r=>(Module._pchomp=wasmExports.pchomp)(r),Module._PinPortal=r=>(Module._PinPortal=wasmExports.PinPortal)(r),Module._UnpinPortal=r=>(Module._UnpinPortal=wasmExports.UnpinPortal)(r),Module._xmlBufferWriteCHAR=(r,e)=>(Module._xmlBufferWriteCHAR=wasmExports.xmlBufferWriteCHAR)(r,e),Module._xmlBufferWriteChar=(r,e)=>(Module._xmlBufferWriteChar=wasmExports.xmlBufferWriteChar)(r,e),Module._xmlReadMemory=(r,e,M,tr,rr)=>(Module._xmlReadMemory=wasmExports.xmlReadMemory)(r,e,M,tr,rr),Module._xmlDocGetRootElement=r=>(Module._xmlDocGetRootElement=wasmExports.xmlDocGetRootElement)(r),Module._xmlXPathIsNaN=r=>(Module._xmlXPathIsNaN=wasmExports.xmlXPathIsNaN)(r),Module._xmlXPathCastToBoolean=r=>(Module._xmlXPathCastToBoolean=wasmExports.xmlXPathCastToBoolean)(r),Module._xmlXPathCastToNumber=r=>(Module._xmlXPathCastToNumber=wasmExports.xmlXPathCastToNumber)(r);var ___dl_seterr=(r,e)=>(___dl_seterr=wasmExports.__dl_seterr)(r,e);Module._getgid=()=>(Module._getgid=wasmExports.getgid)(),Module._getuid=()=>(Module._getuid=wasmExports.getuid)(),Module._gmtime=r=>(Module._gmtime=wasmExports.gmtime)(r);var _htonl=r=>(_htonl=wasmExports.htonl)(r),_htons=r=>(_htons=wasmExports.htons)(r);Module._ioctl=(r,e,M)=>(Module._ioctl=wasmExports.ioctl)(r,e,M);var _emscripten_builtin_memalign=(r,e)=>(_emscripten_builtin_memalign=wasmExports.emscripten_builtin_memalign)(r,e),_ntohs=r=>(_ntohs=wasmExports.ntohs)(r);Module._perror=r=>(Module._perror=wasmExports.perror)(r),Module._qsort=(r,e,M,tr)=>(Module._qsort=wasmExports.qsort)(r,e,M,tr),Module._srand=r=>(Module._srand=wasmExports.srand)(r),Module._rand=()=>(Module._rand=wasmExports.rand)();var __emscripten_timeout=(r,e)=>(__emscripten_timeout=wasmExports._emscripten_timeout)(r,e);Module._strerror_r=(r,e,M)=>(Module._strerror_r=wasmExports.strerror_r)(r,e,M),Module._strncat=(r,e,M)=>(Module._strncat=wasmExports.strncat)(r,e,M);var _setThrew=(r,e)=>(_setThrew=wasmExports.setThrew)(r,e),__emscripten_tempret_set=r=>(__emscripten_tempret_set=wasmExports._emscripten_tempret_set)(r),__emscripten_tempret_get=()=>(__emscripten_tempret_get=wasmExports._emscripten_tempret_get)(),__emscripten_stack_restore=r=>(__emscripten_stack_restore=wasmExports._emscripten_stack_restore)(r),__emscripten_stack_alloc=r=>(__emscripten_stack_alloc=wasmExports._emscripten_stack_alloc)(r),_emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports.emscripten_stack_get_current)();Module._stderr=2536848,Module._InterruptPending=2677872,Module._MyLatch=2678060,Module._CritSectionCount=2677924,Module._MyProc=2647676,Module._pg_global_prng_state=2624256,Module._error_context_stack=2676168,Module._GUC_check_errdetail_string=2681820,Module._IsUnderPostmaster=2677953,Module._CurrentMemoryContext=2683248,Module._stdout=2537152,Module._debug_query_string=2538700,Module._MyProcPort=2678048,Module.___THREW__=2698916,Module.___threwValue=2698920,Module._MyDatabaseId=2677932,Module._TopMemoryContext=2683252,Module._PG_exception_stack=2676172,Module._MyProcPid=2678024,Module._stdin=2537e3,Module._ScanKeywords=2374040,Module._pg_number_of_ones=925120,Module._LocalBufferBlockPointers=2644252,Module._BufferBlocks=2638988,Module._wal_level=2387920,Module._SnapshotAnyData=2474096,Module._maintenance_work_mem=2421576,Module._ParallelWorkerNumber=2379480,Module._MainLWLockArray=2645860,Module._CurrentResourceOwner=2683296,Module._work_mem=2421560,Module._NBuffers=2421584,Module._bsysscan=2625492,Module._CheckXidAlive=2625488,Module._RecentXmin=2474188,Module._XactIsoLevel=2387784,Module._pgWalUsage=2628960,Module._pgBufferUsage=2628832,Module._TTSOpsVirtual=2391608,Module._TransamVariables=2625480,Module._TopTransactionContext=2683272,Module._RmgrTable=2379504,Module._process_shared_preload_libraries_in_progress=2681216,Module._wal_segment_size=2387940,Module._TopTransactionResourceOwner=2683304,Module._arch_module_check_errdetail_string=2638372,Module._object_access_hook=2627600,Module._InvalidObjectAddress=1520620,Module._check_function_bodies=2421750,Module._post_parse_analyze_hook=2627640,Module._ScanKeywordTokens=1551648,Module._SPI_processed=2628984,Module._SPI_tuptable=2628992,Module._TTSOpsMinimalTuple=2391712,Module._check_password_hook=2627908,Module._ConfigReloadPending=2638360,Module._max_parallel_maintenance_workers=2421580,Module._DateStyle=2421548,Module._ExecutorStart_hook=2628808,Module._ExecutorRun_hook=2628812,Module._ExecutorFinish_hook=2628816,Module._ExecutorEnd_hook=2628820,Module._SPI_result=2628996,Module._ClientAuthentication_hook=2629168,Module._cpu_tuple_cost=2392168,Module._cpu_operator_cost=2392184,Module._seq_page_cost=2392152,Module._planner_hook=2638056,Module._ShutdownRequestPending=2638364,Module._MyStartTime=2678032,Module._cluster_name=2421800,Module._application_name=2682044,Module._BufferDescriptors=2638984,Module._shmem_startup_hook=2644932,Module._ProcessUtility_hook=2647764,Module._IntervalStyle=2677956,Module._extra_float_digits=2411976,Module._pg_crc32_table=2112288,Module._xmlFree=2523400,Module._shmem_request_hook=2681220;function invoke_iii(r,e,M){var tr=stackSave();try{return getWasmTableEntry(r)(e,M)}catch(rr){if(stackRestore(tr),rr!==rr+0)throw rr;_setThrew(1,0)}}function invoke_viiii(r,e,M,tr,rr){var ir=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr)}catch(lr){if(stackRestore(ir),lr!==lr+0)throw lr;_setThrew(1,0)}}function invoke_vi(r,e){var M=stackSave();try{getWasmTableEntry(r)(e)}catch(tr){if(stackRestore(M),tr!==tr+0)throw tr;_setThrew(1,0)}}function invoke_v(r){var e=stackSave();try{getWasmTableEntry(r)()}catch(M){if(stackRestore(e),M!==M+0)throw M;_setThrew(1,0)}}function invoke_j(r){var e=stackSave();try{return getWasmTableEntry(r)()}catch(M){if(stackRestore(e),M!==M+0)throw M;return _setThrew(1,0),0n}}function invoke_viiiiii(r,e,M,tr,rr,ir,lr){var dr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir,lr)}catch(hr){if(stackRestore(dr),hr!==hr+0)throw hr;_setThrew(1,0)}}function invoke_vii(r,e,M){var tr=stackSave();try{getWasmTableEntry(r)(e,M)}catch(rr){if(stackRestore(tr),rr!==rr+0)throw rr;_setThrew(1,0)}}function invoke_iiiiii(r,e,M,tr,rr,ir){var lr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir)}catch(dr){if(stackRestore(lr),dr!==dr+0)throw dr;_setThrew(1,0)}}function invoke_i(r){var e=stackSave();try{return getWasmTableEntry(r)()}catch(M){if(stackRestore(e),M!==M+0)throw M;_setThrew(1,0)}}function invoke_ii(r,e){var M=stackSave();try{return getWasmTableEntry(r)(e)}catch(tr){if(stackRestore(M),tr!==tr+0)throw tr;_setThrew(1,0)}}function invoke_viii(r,e,M,tr){var rr=stackSave();try{getWasmTableEntry(r)(e,M,tr)}catch(ir){if(stackRestore(rr),ir!==ir+0)throw ir;_setThrew(1,0)}}function invoke_vji(r,e,M){var tr=stackSave();try{getWasmTableEntry(r)(e,M)}catch(rr){if(stackRestore(tr),rr!==rr+0)throw rr;_setThrew(1,0)}}function invoke_iiii(r,e,M,tr){var rr=stackSave();try{return getWasmTableEntry(r)(e,M,tr)}catch(ir){if(stackRestore(rr),ir!==ir+0)throw ir;_setThrew(1,0)}}function invoke_iiiiiiii(r,e,M,tr,rr,ir,lr,dr){var hr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr)}catch(fr){if(stackRestore(hr),fr!==fr+0)throw fr;_setThrew(1,0)}}function invoke_iiiii(r,e,M,tr,rr){var ir=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr)}catch(lr){if(stackRestore(ir),lr!==lr+0)throw lr;_setThrew(1,0)}}function invoke_viiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr,fr){var mr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr,fr)}catch(_r){if(stackRestore(mr),_r!==_r+0)throw _r;_setThrew(1,0)}}function invoke_viiiii(r,e,M,tr,rr,ir){var lr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir)}catch(dr){if(stackRestore(lr),dr!==dr+0)throw dr;_setThrew(1,0)}}function invoke_jii(r,e,M){var tr=stackSave();try{return getWasmTableEntry(r)(e,M)}catch(rr){if(stackRestore(tr),rr!==rr+0)throw rr;return _setThrew(1,0),0n}}function invoke_ji(r,e){var M=stackSave();try{return getWasmTableEntry(r)(e)}catch(tr){if(stackRestore(M),tr!==tr+0)throw tr;return _setThrew(1,0),0n}}function invoke_jiiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr,fr){var mr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr,fr)}catch(_r){if(stackRestore(mr),_r!==_r+0)throw _r;return _setThrew(1,0),0n}}function invoke_jiiiiii(r,e,M,tr,rr,ir,lr){var dr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr)}catch(hr){if(stackRestore(dr),hr!==hr+0)throw hr;return _setThrew(1,0),0n}}function invoke_iiiiiiiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr,wr){var yr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr,wr)}catch(br){if(stackRestore(yr),br!==br+0)throw br;_setThrew(1,0)}}function invoke_iiiijii(r,e,M,tr,rr,ir,lr){var dr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr)}catch(hr){if(stackRestore(dr),hr!==hr+0)throw hr;_setThrew(1,0)}}function invoke_vijiji(r,e,M,tr,rr,ir){var lr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir)}catch(dr){if(stackRestore(lr),dr!==dr+0)throw dr;_setThrew(1,0)}}function invoke_viji(r,e,M,tr){var rr=stackSave();try{getWasmTableEntry(r)(e,M,tr)}catch(ir){if(stackRestore(rr),ir!==ir+0)throw ir;_setThrew(1,0)}}function invoke_iiji(r,e,M,tr){var rr=stackSave();try{return getWasmTableEntry(r)(e,M,tr)}catch(ir){if(stackRestore(rr),ir!==ir+0)throw ir;_setThrew(1,0)}}function invoke_iiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr){var fr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr)}catch(mr){if(stackRestore(fr),mr!==mr+0)throw mr;_setThrew(1,0)}}function invoke_iiiiiiiiiiiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr,wr,yr,br,Mr,vr){var Sr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr,wr,yr,br,Mr,vr)}catch(xr){if(stackRestore(Sr),xr!==xr+0)throw xr;_setThrew(1,0)}}function invoke_iiiij(r,e,M,tr,rr){var ir=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr)}catch(lr){if(stackRestore(ir),lr!==lr+0)throw lr;_setThrew(1,0)}}function invoke_iiiiiii(r,e,M,tr,rr,ir,lr){var dr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr)}catch(hr){if(stackRestore(dr),hr!==hr+0)throw hr;_setThrew(1,0)}}function invoke_vj(r,e){var M=stackSave();try{getWasmTableEntry(r)(e)}catch(tr){if(stackRestore(M),tr!==tr+0)throw tr;_setThrew(1,0)}}function invoke_iiiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr,fr){var mr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr,fr)}catch(_r){if(stackRestore(mr),_r!==_r+0)throw _r;_setThrew(1,0)}}function invoke_viiji(r,e,M,tr,rr){var ir=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr)}catch(lr){if(stackRestore(ir),lr!==lr+0)throw lr;_setThrew(1,0)}}function invoke_viiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr){var fr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr)}catch(mr){if(stackRestore(fr),mr!==mr+0)throw mr;_setThrew(1,0)}}function invoke_vij(r,e,M){var tr=stackSave();try{getWasmTableEntry(r)(e,M)}catch(rr){if(stackRestore(tr),rr!==rr+0)throw rr;_setThrew(1,0)}}function invoke_ij(r,e){var M=stackSave();try{return getWasmTableEntry(r)(e)}catch(tr){if(stackRestore(M),tr!==tr+0)throw tr;_setThrew(1,0)}}function invoke_viiiiiii(r,e,M,tr,rr,ir,lr,dr){var hr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr)}catch(fr){if(stackRestore(hr),fr!==fr+0)throw fr;_setThrew(1,0)}}function invoke_viiiji(r,e,M,tr,rr,ir){var lr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir)}catch(dr){if(stackRestore(lr),dr!==dr+0)throw dr;_setThrew(1,0)}}function invoke_iiij(r,e,M,tr){var rr=stackSave();try{return getWasmTableEntry(r)(e,M,tr)}catch(ir){if(stackRestore(rr),ir!==ir+0)throw ir;_setThrew(1,0)}}function invoke_vid(r,e,M){var tr=stackSave();try{getWasmTableEntry(r)(e,M)}catch(rr){if(stackRestore(tr),rr!==rr+0)throw rr;_setThrew(1,0)}}function invoke_ijiiiiii(r,e,M,tr,rr,ir,lr,dr){var hr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr)}catch(fr){if(stackRestore(hr),fr!==fr+0)throw fr;_setThrew(1,0)}}function invoke_viijii(r,e,M,tr,rr,ir){var lr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir)}catch(dr){if(stackRestore(lr),dr!==dr+0)throw dr;_setThrew(1,0)}}function invoke_iiiiiji(r,e,M,tr,rr,ir,lr){var dr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr)}catch(hr){if(stackRestore(dr),hr!==hr+0)throw hr;_setThrew(1,0)}}function invoke_viijiiii(r,e,M,tr,rr,ir,lr,dr){var hr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr)}catch(fr){if(stackRestore(hr),fr!==fr+0)throw fr;_setThrew(1,0)}}function invoke_viij(r,e,M,tr){var rr=stackSave();try{getWasmTableEntry(r)(e,M,tr)}catch(ir){if(stackRestore(rr),ir!==ir+0)throw ir;_setThrew(1,0)}}function invoke_jiiii(r,e,M,tr,rr){var ir=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr)}catch(lr){if(stackRestore(ir),lr!==lr+0)throw lr;return _setThrew(1,0),0n}}function invoke_viiiiiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr){var wr=stackSave();try{getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr)}catch(yr){if(stackRestore(wr),yr!==yr+0)throw yr;_setThrew(1,0)}}function invoke_di(r,e){var M=stackSave();try{return getWasmTableEntry(r)(e)}catch(tr){if(stackRestore(M),tr!==tr+0)throw tr;_setThrew(1,0)}}function invoke_id(r,e){var M=stackSave();try{return getWasmTableEntry(r)(e)}catch(tr){if(stackRestore(M),tr!==tr+0)throw tr;_setThrew(1,0)}}function invoke_ijiiiii(r,e,M,tr,rr,ir,lr){var dr=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr)}catch(hr){if(stackRestore(dr),hr!==hr+0)throw hr;_setThrew(1,0)}}function invoke_iiiiiiiiiii(r,e,M,tr,rr,ir,lr,dr,hr,fr,mr){var _r=stackSave();try{return getWasmTableEntry(r)(e,M,tr,rr,ir,lr,dr,hr,fr,mr)}catch(gr){if(stackRestore(_r),gr!==gr+0)throw gr;_setThrew(1,0)}}Module.addRunDependency=addRunDependency,Module.removeRunDependency=removeRunDependency,Module.wasmTable=wasmTable,Module.addFunction=addFunction,Module.removeFunction=removeFunction,Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToNewUTF8=stringToNewUTF8,Module.stringToUTF8OnStack=stringToUTF8OnStack,Module.FS_createPreloadedFile=FS_createPreloadedFile,Module.FS_unlink=FS_unlink,Module.FS_createPath=FS_createPath,Module.FS_createDevice=FS_createDevice,Module.FS=FS,Module.FS_createDataFile=FS_createDataFile,Module.FS_createLazyFile=FS_createLazyFile,Module.MEMFS=MEMFS,Module.IDBFS=IDBFS;var calledRun;dependenciesFulfilled=function r(){calledRun||run(),calledRun||(dependenciesFulfilled=r)};function callMain(r=[]){var e=resolveGlobalSymbol("main").sym;if(e){r.unshift(thisProgram);var M=r.length,tr=stackAlloc((M+1)*4),rr=tr;r.forEach(lr=>{HEAPU32[rr>>2]=stringToUTF8OnStack(lr),rr+=4}),HEAPU32[rr>>2]=0;try{var ir=e(M,tr);return exitJS(ir,!0),ir}catch(lr){return handleException(lr)}}}function run(r=arguments_){if(runDependencies>0||(preRun(),runDependencies>0))return;function e(){calledRun||(calledRun=!0,Module.calledRun=!0,!ABORT&&(initRuntime(),preMain(),readyPromiseResolve(Module),Module.onRuntimeInitialized?.(),shouldRunNow&&callMain(r),postRun()))}Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),e()},1)):e()}if(Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var shouldRunNow=!0;return Module.noInitialRun&&(shouldRunNow=!1),run(),moduleRtn=readyPromise,moduleRtn}})(),He=pt,je=He,ne,te,re,ie,_e,xe,we,Se,ye,le,pe,he,de,ae,$,I,oe,me,B,Q,K,ue,se,J,O,Z,q,G,C,Ve,Xe,fe,Ke,Ye,L=class as extends k{constructor(e={},M={}){super(),R$1(this,C),R$1(this,ne,!1),R$1(this,te,!1),R$1(this,re,!1),R$1(this,ie,!1),R$1(this,_e,!1),R$1(this,xe,new Y),R$1(this,we,new Y),R$1(this,Se,new Y),R$1(this,ye,new Y),R$1(this,le,!1),this.debug=0,R$1(this,pe),R$1(this,he,[]),R$1(this,de,new ye$1),R$1(this,ae),R$1(this,$),R$1(this,I,new Map),R$1(this,oe,new Set),R$1(this,me,-1),R$1(this,B,[]),R$1(this,Q,!1),R$1(this,K),R$1(this,ue,-1),R$1(this,se,[]),R$1(this,J,0),R$1(this,O,null),R$1(this,Z,!0),R$1(this,q,new Uint8Array(0)),R$1(this,G,0),typeof e=="string"?M={dataDir:e,...M}:M=e,this.dataDir=M.dataDir,M.parsers!==void 0&&(this.parsers={...this.parsers,...M.parsers}),M.serializers!==void 0&&(this.serializers={...this.serializers,...M.serializers}),M?.debug!==void 0&&(this.debug=M.debug),M?.relaxedDurability!==void 0&&x$3(this,_e,M.relaxedDurability),x$3(this,pe,M.extensions??{}),this.waitReady=T$2(this,C,Ve).call(this,M??{})}static async create(e,M){let tr=typeof e=="string"?{dataDir:e,...M??{}}:e??{},rr=new as(tr);return await rr.waitReady,rr}get Module(){return this.mod}get ready(){return h$1(this,ne)&&!h$1(this,te)&&!h$1(this,re)}get closed(){return h$1(this,re)}async close(){await this._checkReady(),x$3(this,te,!0);for(let e of h$1(this,he))await e();try{await this.execProtocol(k$1.end()),this.mod._pgl_shutdown(),this.mod.removeFunction(h$1(this,ue)),this.mod.removeFunction(h$1(this,me))}catch(e){let M=e;if(!(M.name==="ExitStatus"&&M.status===0))throw e}await this.fs.closeFs(),x$3(this,re,!0),x$3(this,te,!1)}async[Symbol.asyncDispose](){await this.close()}async _handleBlob(e){x$3(this,ae,e?await e.arrayBuffer():void 0)}async _cleanupBlob(){x$3(this,ae,void 0)}async _getWrittenBlob(){if(!h$1(this,$))return;let e=new Blob(h$1(this,$));return x$3(this,$,void 0),e}async _checkReady(){if(h$1(this,te))throw new Error("PGlite is closing");if(h$1(this,re))throw new Error("PGlite is closed");h$1(this,ne)||await this.waitReady}execProtocolRawSync(e){let M=this.mod;return x$3(this,J,0),x$3(this,G,0),x$3(this,se,e),h$1(this,Z)&&h$1(this,q).length!==as.DEFAULT_RECV_BUF_SIZE&&x$3(this,q,new Uint8Array(as.DEFAULT_RECV_BUF_SIZE)),M._interactive_one(e.length,e[0]),x$3(this,se,[]),h$1(this,Z)&&h$1(this,G)?h$1(this,q).subarray(0,h$1(this,G)):new Uint8Array(0)}async execProtocolRaw(e,{syncToFs:M=!0}={}){let tr=this.execProtocolRawSync(e);return M&&await this.syncToFs(),tr}async execProtocol(e,{syncToFs:M=!0,throwOnError:tr=!0,onNotice:rr}={}){x$3(this,Q,tr),x$3(this,K,rr),x$3(this,B,[]),x$3(this,O,null);let ir=await this.execProtocolRaw(e,{syncToFs:M}),lr=h$1(this,O);x$3(this,Q,!1),x$3(this,K,void 0),x$3(this,O,null);let dr={messages:h$1(this,B),data:ir};if(x$3(this,B,[]),tr&&lr)throw x$3(this,de,new ye$1),lr;return dr}async execProtocolStream(e,{syncToFs:M,throwOnError:tr=!0,onNotice:rr}={}){x$3(this,Q,tr),x$3(this,K,rr),x$3(this,B,[]),x$3(this,O,null),x$3(this,Z,!1),await this.execProtocolRaw(e,{syncToFs:M}),x$3(this,Z,!0);let ir=h$1(this,O);x$3(this,Q,!1),x$3(this,K,void 0),x$3(this,O,null);let lr=h$1(this,B);if(x$3(this,B,[]),tr&&ir)throw x$3(this,de,new ye$1),ir;return lr}isInTransaction(){return h$1(this,ie)}async syncToFs(){if(h$1(this,le))return;x$3(this,le,!0);let e=async()=>{await h$1(this,ye).runExclusive(async()=>{x$3(this,le,!1),await this.fs.syncToFs(h$1(this,_e))})};h$1(this,_e)?e():await e()}async listen(e,M,tr){return this._runExclusiveListen(()=>T$2(this,C,Ke).call(this,e,M,tr))}async unlisten(e,M,tr){return this._runExclusiveListen(()=>T$2(this,C,Ye).call(this,e,M,tr))}onNotification(e){return h$1(this,oe).add(e),()=>{h$1(this,oe).delete(e)}}offNotification(e){h$1(this,oe).delete(e)}async dumpDataDir(e){await this._checkReady();let M=this.dataDir?.split("/").pop()??"pgdata";return this.fs.dumpTar(M,e)}_runExclusiveQuery(e){return h$1(this,xe).runExclusive(e)}_runExclusiveTransaction(e){return h$1(this,we).runExclusive(e)}async clone(){let e=await this.dumpDataDir("none");return as.create({loadDataDir:e,extensions:h$1(this,pe)})}_runExclusiveListen(e){return h$1(this,Se).runExclusive(e)}};ne=new WeakMap,te=new WeakMap,re=new WeakMap,ie=new WeakMap,_e=new WeakMap,xe=new WeakMap,we=new WeakMap,Se=new WeakMap,ye=new WeakMap,le=new WeakMap,pe=new WeakMap,he=new WeakMap,de=new WeakMap,ae=new WeakMap,$=new WeakMap,I=new WeakMap,oe=new WeakMap,me=new WeakMap,B=new WeakMap,Q=new WeakMap,K=new WeakMap,ue=new WeakMap,se=new WeakMap,J=new WeakMap,O=new WeakMap,Z=new WeakMap,q=new WeakMap,G=new WeakMap,C=new WeakSet,Ve=async function(r){if(r.fs)this.fs=r.fs;else{let{dataDir:fr,fsType:mr}=Ge(r.dataDir);this.fs=await Ue(fr,mr)}let e={},M=[],tr=[`PGDATA=${C$1}`,`PREFIX=${Vr}`,`PGUSER=${r.username??"postgres"}`,`PGDATABASE=${r.database??"template1"}`,"MODE=REACT","REPL=N",...this.debug?["-d",this.debug.toString()]:[]];r.wasmModule||Rr();let rr=r.fsBundle?r.fsBundle.arrayBuffer():Er(),ir;rr.then(fr=>{ir=fr});let lr={WASM_PREFIX:Vr,arguments:tr,INITIAL_MEMORY:r.initialMemory,noExitRuntime:!0,...this.debug>0?{print:console.info,printErr:console.error}:{print:()=>{},printErr:()=>{}},instantiateWasm:(fr,mr)=>(Tr(fr,r.wasmModule).then(({instance:_r,module:gr})=>{mr(_r,gr)}),{}),getPreloadedPackage:(fr,mr)=>{if(fr==="pglite.data"){if(ir.byteLength!==mr)throw new Error(`Invalid FS bundle size: ${ir.byteLength} !== ${mr}`);return ir}throw new Error(`Unknown package: ${fr}`)},preRun:[fr=>{let mr=fr.FS.makedev(64,0),_r={open:gr=>{},close:gr=>{},read:(gr,wr,yr,br,Mr)=>{let vr=h$1(this,ae);if(!vr)throw new Error("No /dev/blob File or Blob provided to read from");let Sr=new Uint8Array(vr);if(Mr>=Sr.length)return 0;let xr=Math.min(Sr.length-Mr,br);for(let Ar=0;Ar<xr;Ar++)wr[yr+Ar]=Sr[Mr+Ar];return xr},write:(gr,wr,yr,br,Mr)=>(h$1(this,$)??x$3(this,$,[]),h$1(this,$).push(wr.slice(yr,yr+br)),br),llseek:(gr,wr,yr)=>{let br=h$1(this,ae);if(!br)throw new Error("No /dev/blob File or Blob provided to llseek");let Mr=wr;if(yr===1?Mr+=gr.position:yr===2&&(Mr=new Uint8Array(br).length),Mr<0)throw new fr.FS.ErrnoError(28);return Mr}};fr.FS.registerDevice(mr,_r),fr.FS.mkdev("/dev/blob",mr)}]},{emscriptenOpts:dr}=await this.fs.init(this,lr);lr=dr;for(let[fr,mr]of Object.entries(h$1(this,pe)))if(mr instanceof URL)e[fr]=ke(mr);else{let _r=await mr.setup(this,lr);if(_r.emscriptenOpts&&(lr=_r.emscriptenOpts),_r.namespaceObj){let gr=this;gr[fr]=_r.namespaceObj}_r.bundlePath&&(e[fr]=ke(_r.bundlePath)),_r.init&&M.push(_r.init),_r.close&&h$1(this,he).push(_r.close)}if(lr.pg_extensions=e,await rr,this.mod=await je(lr),x$3(this,me,this.mod.addFunction((fr,mr)=>{let _r;try{_r=this.mod.HEAPU8.subarray(fr,fr+mr)}catch(gr){throw console.error("error",gr),gr}if(h$1(this,de).parse(_r,gr=>{T$2(this,C,Xe).call(this,gr)}),h$1(this,Z)){let gr=_r.slice(),wr=h$1(this,G)+gr.length;if(wr>h$1(this,q).length){let yr=h$1(this,q).length+(h$1(this,q).length>>1)+wr;wr>L.MAX_BUFFER_SIZE&&(wr=L.MAX_BUFFER_SIZE);let br=new Uint8Array(yr);br.set(h$1(this,q).subarray(0,h$1(this,G))),x$3(this,q,br)}return h$1(this,q).set(gr,h$1(this,G)),x$3(this,G,h$1(this,G)+gr.length),h$1(this,q).length}return mr},"iii")),x$3(this,ue,this.mod.addFunction((fr,mr)=>{let _r=h$1(this,se).length-h$1(this,J);_r>mr&&(_r=mr);try{this.mod.HEAP8.set(h$1(this,se).subarray(h$1(this,J),h$1(this,J)+_r),fr),x$3(this,J,h$1(this,J)+_r)}catch(gr){console.log(gr)}return _r},"iii")),this.mod._set_read_write_cbs(h$1(this,ue),h$1(this,me)),await this.fs.initialSyncFs(),r.loadDataDir){if(this.mod.FS.analyzePath(C$1+"/PG_VERSION").exists)throw new Error("Database already exists, cannot load from tarball");T$2(this,C,fe).call(this,"pglite: loading data from tarball"),await ce$1(this.mod.FS,r.loadDataDir,C$1)}this.mod.FS.analyzePath(C$1+"/PG_VERSION").exists?T$2(this,C,fe).call(this,"pglite: found DB, resuming"):T$2(this,C,fe).call(this,"pglite: no db"),await Be(this.mod,(...fr)=>T$2(this,C,fe).call(this,...fr));let hr=this.mod._pgl_initdb();if(!hr)throw new Error("INITDB failed to return value");if(hr&1)throw new Error("INITDB: failed to execute");if(hr&2){let fr=r.username??"postgres",mr=r.database??"template1";if(hr&4){if(!(hr&12))throw new Error(`INITDB: Invalid db ${mr}/user ${fr} combination`)}else if(mr!=="template1"&&fr!=="postgres")throw new Error(`INITDB: created a new datadir ${C$1}, but an alternative db ${mr}/user ${fr} was requested`)}this.mod._pgl_backend(),await this.syncToFs(),x$3(this,ne,!0),await this.exec("SET search_path TO public;"),await this._initArrayTypes();for(let fr of M)await fr()},Xe=function(r){if(!h$1(this,O)){if(r instanceof C$2)h$1(this,Q)&&x$3(this,O,r);else if(r instanceof te$1)this.debug>0&&console.warn(r),h$1(this,K)&&h$1(this,K).call(this,r);else if(r instanceof Z$1)switch(r.text){case"BEGIN":x$3(this,ie,!0);break;case"COMMIT":case"ROLLBACK":x$3(this,ie,!1);break}else if(r instanceof J$1){let e=h$1(this,I).get(r.channel);e&&e.forEach(M=>{queueMicrotask(()=>M(r.payload))}),h$1(this,oe).forEach(M=>{queueMicrotask(()=>M(r.channel,r.payload))})}h$1(this,B).push(r)}},fe=function(...r){this.debug>0&&console.log(...r)},Ke=async function(r,e,M){let tr=Nr(r),rr=M??this;h$1(this,I).has(tr)||h$1(this,I).set(tr,new Set),h$1(this,I).get(tr).add(e);try{await rr.exec(`LISTEN ${r}`)}catch(ir){throw h$1(this,I).get(tr).delete(e),h$1(this,I).get(tr)?.size===0&&h$1(this,I).delete(tr),ir}return async ir=>{await this.unlisten(tr,e,ir)}},Ye=async function(r,e,M){let tr=Nr(r),rr=M??this,ir=async()=>{await rr.exec(`UNLISTEN ${r}`),h$1(this,I).get(tr)?.size===0&&h$1(this,I).delete(tr)};e?(h$1(this,I).get(tr)?.delete(e),h$1(this,I).get(tr)?.size===0&&await ir()):await ir()},L.DEFAULT_RECV_BUF_SIZE=1*1024*1024,L.MAX_BUFFER_SIZE=Math.pow(2,30);var We=L;u();function isUndefined$1(r){return typeof r>"u"||r===void 0}function isString$1(r){return typeof r=="string"}function isNumber$1(r){return typeof r=="number"}function isBoolean(r){return typeof r=="boolean"}function isNull(r){return r===null}function isDate$1(r){return r instanceof Date}function isBigInt(r){return typeof r=="bigint"}function isFunction(r){return typeof r=="function"}function isObject(r){return typeof r=="object"&&r!==null}function getLast(r){return r[r.length-1]}function freeze(r){return Object.freeze(r)}function asArray$1(r){return isReadonlyArray(r)?r:[r]}function isReadonlyArray(r){return Array.isArray(r)}function noop$1(r){return r}const AlterTableNode=freeze({is(r){return r.kind==="AlterTableNode"},create(r){return freeze({kind:"AlterTableNode",table:r})},cloneWithTableProps(r,e){return freeze({...r,...e})},cloneWithColumnAlteration(r,e){return freeze({...r,columnAlterations:r.columnAlterations?[...r.columnAlterations,e]:[e]})}}),IdentifierNode=freeze({is(r){return r.kind==="IdentifierNode"},create(r){return freeze({kind:"IdentifierNode",name:r})}}),CreateIndexNode=freeze({is(r){return r.kind==="CreateIndexNode"},create(r){return freeze({kind:"CreateIndexNode",name:IdentifierNode.create(r)})},cloneWith(r,e){return freeze({...r,...e})},cloneWithColumns(r,e){return freeze({...r,columns:[...r.columns||[],...e]})}}),CreateSchemaNode=freeze({is(r){return r.kind==="CreateSchemaNode"},create(r,e){return freeze({kind:"CreateSchemaNode",schema:IdentifierNode.create(r),...e})},cloneWith(r,e){return freeze({...r,...e})}}),ON_COMMIT_ACTIONS=["preserve rows","delete rows","drop"],CreateTableNode=freeze({is(r){return r.kind==="CreateTableNode"},create(r){return freeze({kind:"CreateTableNode",table:r,columns:freeze([])})},cloneWithColumn(r,e){return freeze({...r,columns:freeze([...r.columns,e])})},cloneWithConstraint(r,e){return freeze({...r,constraints:r.constraints?freeze([...r.constraints,e]):freeze([e])})},cloneWithFrontModifier(r,e){return freeze({...r,frontModifiers:r.frontModifiers?freeze([...r.frontModifiers,e]):freeze([e])})},cloneWithEndModifier(r,e){return freeze({...r,endModifiers:r.endModifiers?freeze([...r.endModifiers,e]):freeze([e])})},cloneWith(r,e){return freeze({...r,...e})}}),SchemableIdentifierNode=freeze({is(r){return r.kind==="SchemableIdentifierNode"},create(r){return freeze({kind:"SchemableIdentifierNode",identifier:IdentifierNode.create(r)})},createWithSchema(r,e){return freeze({kind:"SchemableIdentifierNode",schema:IdentifierNode.create(r),identifier:IdentifierNode.create(e)})}}),DropIndexNode=freeze({is(r){return r.kind==="DropIndexNode"},create(r,e){return freeze({kind:"DropIndexNode",name:SchemableIdentifierNode.create(r),...e})},cloneWith(r,e){return freeze({...r,...e})}}),DropSchemaNode=freeze({is(r){return r.kind==="DropSchemaNode"},create(r,e){return freeze({kind:"DropSchemaNode",schema:IdentifierNode.create(r),...e})},cloneWith(r,e){return freeze({...r,...e})}}),DropTableNode=freeze({is(r){return r.kind==="DropTableNode"},create(r,e){return freeze({kind:"DropTableNode",table:r,...e})},cloneWith(r,e){return freeze({...r,...e})}}),AliasNode=freeze({is(r){return r.kind==="AliasNode"},create(r,e){return freeze({kind:"AliasNode",node:r,alias:e})}}),TableNode=freeze({is(r){return r.kind==="TableNode"},create(r){return freeze({kind:"TableNode",table:SchemableIdentifierNode.create(r)})},createWithSchema(r,e){return freeze({kind:"TableNode",table:SchemableIdentifierNode.createWithSchema(r,e)})}});function isOperationNodeSource(r){return isObject(r)&&isFunction(r.toOperationNode)}function isExpression(r){return isObject(r)&&"expressionType"in r&&isOperationNodeSource(r)}function isAliasedExpression(r){return isObject(r)&&"expression"in r&&isString$1(r.alias)&&isOperationNodeSource(r)}const SelectModifierNode=freeze({is(r){return r.kind==="SelectModifierNode"},create(r,e){return freeze({kind:"SelectModifierNode",modifier:r,of:e})},createWithExpression(r){return freeze({kind:"SelectModifierNode",rawModifier:r})}}),AndNode=freeze({is(r){return r.kind==="AndNode"},create(r,e){return freeze({kind:"AndNode",left:r,right:e})}}),OrNode=freeze({is(r){return r.kind==="OrNode"},create(r,e){return freeze({kind:"OrNode",left:r,right:e})}}),OnNode=freeze({is(r){return r.kind==="OnNode"},create(r){return freeze({kind:"OnNode",on:r})},cloneWithOperation(r,e,M){return freeze({...r,on:e==="And"?AndNode.create(r.on,M):OrNode.create(r.on,M)})}}),JoinNode=freeze({is(r){return r.kind==="JoinNode"},create(r,e){return freeze({kind:"JoinNode",joinType:r,table:e,on:void 0})},createWithOn(r,e,M){return freeze({kind:"JoinNode",joinType:r,table:e,on:OnNode.create(M)})},cloneWithOn(r,e){return freeze({...r,on:r.on?OnNode.cloneWithOperation(r.on,"And",e):OnNode.create(e)})}}),BinaryOperationNode=freeze({is(r){return r.kind==="BinaryOperationNode"},create(r,e,M){return freeze({kind:"BinaryOperationNode",leftOperand:r,operator:e,rightOperand:M})}}),COMPARISON_OPERATORS=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],ARITHMETIC_OPERATORS=["+","-","*","/","%","^","&","|","#","<<",">>"],JSON_OPERATORS=["->","->>"],BINARY_OPERATORS=[...COMPARISON_OPERATORS,...ARITHMETIC_OPERATORS,"&&","||"],UNARY_FILTER_OPERATORS=["exists","not exists"],UNARY_OPERATORS=["not","-",...UNARY_FILTER_OPERATORS],OPERATORS=[...BINARY_OPERATORS,...JSON_OPERATORS,...UNARY_OPERATORS,"between","between symmetric"],OperatorNode=freeze({is(r){return r.kind==="OperatorNode"},create(r){return freeze({kind:"OperatorNode",operator:r})}});function isJSONOperator(r){return isString$1(r)&&JSON_OPERATORS.includes(r)}const ColumnNode=freeze({is(r){return r.kind==="ColumnNode"},create(r){return freeze({kind:"ColumnNode",column:IdentifierNode.create(r)})}}),SelectAllNode=freeze({is(r){return r.kind==="SelectAllNode"},create(){return freeze({kind:"SelectAllNode"})}}),ReferenceNode=freeze({is(r){return r.kind==="ReferenceNode"},create(r,e){return freeze({kind:"ReferenceNode",table:e,column:r})},createSelectAll(r){return freeze({kind:"ReferenceNode",table:r,column:SelectAllNode.create()})}});class DynamicReferenceBuilder{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return parseSimpleReferenceExpression(this.#e)}}function isDynamicReferenceBuilder(r){return isObject(r)&&isOperationNodeSource(r)&&isString$1(r.dynamicReference)}const OrderByItemNode=freeze({is(r){return r.kind==="OrderByItemNode"},create(r,e){return freeze({kind:"OrderByItemNode",orderBy:r,direction:e})},cloneWith(r,e){return freeze({...r,...e})}}),RawNode=freeze({is(r){return r.kind==="RawNode"},create(r,e){return freeze({kind:"RawNode",sqlFragments:freeze(r),parameters:freeze(e)})},createWithSql(r){return RawNode.create([r],[])},createWithChild(r){return RawNode.create(["",""],[r])},createWithChildren(r){return RawNode.create(new Array(r.length+1).fill(""),r)}}),CollateNode=freeze({is(r){return r.kind==="CollateNode"},create(r){return freeze({kind:"CollateNode",collation:IdentifierNode.create(r)})}});class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:OrderByItemNode.cloneWith(this.#e.node,{direction:RawNode.createWithSql("desc")})})}asc(){return new OrderByItemBuilder({node:OrderByItemNode.cloneWith(this.#e.node,{direction:RawNode.createWithSql("asc")})})}nullsLast(){return new OrderByItemBuilder({node:OrderByItemNode.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new OrderByItemBuilder({node:OrderByItemNode.cloneWith(this.#e.node,{nulls:"first"})})}collate(e){return new OrderByItemBuilder({node:OrderByItemNode.cloneWith(this.#e.node,{collation:CollateNode.create(e)})})}toOperationNode(){return this.#e.node}}const LOGGED_MESSAGES=new Set;function logOnce(r){LOGGED_MESSAGES.has(r)||(LOGGED_MESSAGES.add(r),console.log(r))}function isOrderByDirection(r){return r==="asc"||r==="desc"}function parseOrderBy(r){if(r.length===2)return[parseOrderByItem(r[0],r[1])];if(r.length===1){const[e]=r;return Array.isArray(e)?(logOnce("orderBy(array) is deprecated, use multiple orderBy calls instead."),e.map(M=>parseOrderByItem(M))):[parseOrderByItem(e)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${r.length}`)}function parseOrderByItem(r,e){const M=parseOrderByExpression(r);if(OrderByItemNode.is(M)){if(e)throw new Error("Cannot specify direction twice!");return M}return parseOrderByWithModifiers(M,e)}function parseOrderByExpression(r){if(isExpressionOrFactory(r))return parseExpression(r);if(isDynamicReferenceBuilder(r))return r.toOperationNode();const[e,M]=r.split(" ");return M?(logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),parseOrderByWithModifiers(parseStringReference(e),M)):parseStringReference(r)}function parseOrderByWithModifiers(r,e){if(typeof e=="string"){if(!isOrderByDirection(e))throw new Error(`Invalid order by direction: ${e}`);return OrderByItemNode.create(r,RawNode.createWithSql(e))}if(isExpression(e))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),OrderByItemNode.create(r,e.toOperationNode());const M=OrderByItemNode.create(r);return e?e(new OrderByItemBuilder({node:M})).toOperationNode():M}const JSONReferenceNode=freeze({is(r){return r.kind==="JSONReferenceNode"},create(r,e){return freeze({kind:"JSONReferenceNode",reference:r,traversal:e})},cloneWithTraversal(r,e){return freeze({...r,traversal:e})}}),JSONOperatorChainNode=freeze({is(r){return r.kind==="JSONOperatorChainNode"},create(r){return freeze({kind:"JSONOperatorChainNode",operator:r,values:freeze([])})},cloneWithValue(r,e){return freeze({...r,values:freeze([...r.values,e])})}}),JSONPathNode=freeze({is(r){return r.kind==="JSONPathNode"},create(r){return freeze({kind:"JSONPathNode",inOperator:r,pathLegs:freeze([])})},cloneWithLeg(r,e){return freeze({...r,pathLegs:freeze([...r.pathLegs,e])})}});function parseSimpleReferenceExpression(r){return isString$1(r)?parseStringReference(r):r.toOperationNode()}function parseReferenceExpressionOrList(r){return isReadonlyArray(r)?r.map(e=>parseReferenceExpression(e)):[parseReferenceExpression(r)]}function parseReferenceExpression(r){return isExpressionOrFactory(r)?parseExpression(r):parseSimpleReferenceExpression(r)}function parseJSONReference(r,e){const M=parseStringReference(r);if(isJSONOperator(e))return JSONReferenceNode.create(M,JSONOperatorChainNode.create(OperatorNode.create(e)));const tr=e.slice(0,-1);if(isJSONOperator(tr))return JSONReferenceNode.create(M,JSONPathNode.create(OperatorNode.create(tr)));throw new Error(`Invalid JSON operator: ${e}`)}function parseStringReference(r){if(!r.includes("."))return ReferenceNode.create(ColumnNode.create(r));const M=r.split(".").map(trim$2);if(M.length===3)return parseStringReferenceWithTableAndSchema(M);if(M.length===2)return parseStringReferenceWithTable(M);throw new Error(`invalid column reference ${r}`)}function parseAliasedStringReference(r){const e=" as ";if(r.includes(e)){const[M,tr]=r.split(e).map(trim$2);return AliasNode.create(parseStringReference(M),IdentifierNode.create(tr))}else return parseStringReference(r)}function parseColumnName(r){return ColumnNode.create(r)}function parseOrderedColumnName(r){if(r.includes(" ")){const[M,tr]=r.split(" ").map(trim$2);if(!isOrderByDirection(tr))throw new Error(`invalid order direction "${tr}" next to "${M}"`);return parseOrderBy([M,tr])[0]}else return parseColumnName(r)}function parseStringReferenceWithTableAndSchema(r){const[e,M,tr]=r;return ReferenceNode.create(ColumnNode.create(tr),TableNode.createWithSchema(e,M))}function parseStringReferenceWithTable(r){const[e,M]=r;return ReferenceNode.create(ColumnNode.create(M),TableNode.create(e))}function trim$2(r){return r.trim()}const PrimitiveValueListNode=freeze({is(r){return r.kind==="PrimitiveValueListNode"},create(r){return freeze({kind:"PrimitiveValueListNode",values:freeze([...r])})}}),ValueListNode=freeze({is(r){return r.kind==="ValueListNode"},create(r){return freeze({kind:"ValueListNode",values:freeze(r)})}}),ValueNode=freeze({is(r){return r.kind==="ValueNode"},create(r){return freeze({kind:"ValueNode",value:r})},createImmediate(r){return freeze({kind:"ValueNode",value:r,immediate:!0})}});function parseValueExpressionOrList(r){return isReadonlyArray(r)?parseValueExpressionList(r):parseValueExpression(r)}function parseValueExpression(r){return isExpressionOrFactory(r)?parseExpression(r):ValueNode.create(r)}function isSafeImmediateValue(r){return isNumber$1(r)||isBoolean(r)||isNull(r)}function parseSafeImmediateValue(r){if(!isSafeImmediateValue(r))throw new Error(`unsafe immediate value ${JSON.stringify(r)}`);return ValueNode.createImmediate(r)}function parseValueExpressionList(r){return r.some(isExpressionOrFactory)?ValueListNode.create(r.map(e=>parseValueExpression(e))):PrimitiveValueListNode.create(r)}const ParensNode=freeze({is(r){return r.kind==="ParensNode"},create(r){return freeze({kind:"ParensNode",node:r})}});function parseValueBinaryOperationOrExpression(r){if(r.length===3)return parseValueBinaryOperation(r[0],r[1],r[2]);if(r.length===1)return parseValueExpression(r[0]);throw new Error(`invalid arguments: ${JSON.stringify(r)}`)}function parseValueBinaryOperation(r,e,M){return isIsOperator(e)&&needsIsOperator(M)?BinaryOperationNode.create(parseReferenceExpression(r),parseOperator(e),ValueNode.createImmediate(M)):BinaryOperationNode.create(parseReferenceExpression(r),parseOperator(e),parseValueExpressionOrList(M))}function parseReferentialBinaryOperation(r,e,M){return BinaryOperationNode.create(parseReferenceExpression(r),parseOperator(e),parseReferenceExpression(M))}function parseFilterObject(r,e){return parseFilterList(Object.entries(r).filter(([,M])=>!isUndefined$1(M)).map(([M,tr])=>parseValueBinaryOperation(M,needsIsOperator(tr)?"is":"=",tr)),e)}function parseFilterList(r,e,M=!0){const tr=e==="and"?AndNode.create:OrNode.create;if(r.length===0)return BinaryOperationNode.create(ValueNode.createImmediate(1),OperatorNode.create("="),ValueNode.createImmediate(e==="and"?1:0));let rr=toOperationNode(r[0]);for(let ir=1;ir<r.length;++ir)rr=tr(rr,toOperationNode(r[ir]));return r.length>1&&M?ParensNode.create(rr):rr}function isIsOperator(r){return r==="is"||r==="is not"}function needsIsOperator(r){return isNull(r)||isBoolean(r)}function parseOperator(r){if(isString$1(r)&&OPERATORS.includes(r))return OperatorNode.create(r);if(isOperationNodeSource(r))return r.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(r)}`)}function toOperationNode(r){return isOperationNodeSource(r)?r.toOperationNode():r}const OrderByNode=freeze({is(r){return r.kind==="OrderByNode"},create(r){return freeze({kind:"OrderByNode",items:freeze([...r])})},cloneWithItems(r,e){return freeze({...r,items:freeze([...r.items,...e])})}}),PartitionByNode=freeze({is(r){return r.kind==="PartitionByNode"},create(r){return freeze({kind:"PartitionByNode",items:freeze(r)})},cloneWithItems(r,e){return freeze({...r,items:freeze([...r.items,...e])})}}),OverNode=freeze({is(r){return r.kind==="OverNode"},create(){return freeze({kind:"OverNode"})},cloneWithOrderByItems(r,e){return freeze({...r,orderBy:r.orderBy?OrderByNode.cloneWithItems(r.orderBy,e):OrderByNode.create(e)})},cloneWithPartitionByItems(r,e){return freeze({...r,partitionBy:r.partitionBy?PartitionByNode.cloneWithItems(r.partitionBy,e):PartitionByNode.create(e)})}}),FromNode=freeze({is(r){return r.kind==="FromNode"},create(r){return freeze({kind:"FromNode",froms:freeze(r)})},cloneWithFroms(r,e){return freeze({...r,froms:freeze([...r.froms,...e])})}}),GroupByNode=freeze({is(r){return r.kind==="GroupByNode"},create(r){return freeze({kind:"GroupByNode",items:freeze(r)})},cloneWithItems(r,e){return freeze({...r,items:freeze([...r.items,...e])})}}),HavingNode=freeze({is(r){return r.kind==="HavingNode"},create(r){return freeze({kind:"HavingNode",having:r})},cloneWithOperation(r,e,M){return freeze({...r,having:e==="And"?AndNode.create(r.having,M):OrNode.create(r.having,M)})}}),InsertQueryNode=freeze({is(r){return r.kind==="InsertQueryNode"},create(r,e,M){return freeze({kind:"InsertQueryNode",into:r,...e&&{with:e},replace:M})},createWithoutInto(){return freeze({kind:"InsertQueryNode"})},cloneWith(r,e){return freeze({...r,...e})}}),ListNode=freeze({is(r){return r.kind==="ListNode"},create(r){return freeze({kind:"ListNode",items:freeze(r)})}}),UpdateQueryNode=freeze({is(r){return r.kind==="UpdateQueryNode"},create(r,e){return freeze({kind:"UpdateQueryNode",table:r.length===1?r[0]:ListNode.create(r),...e&&{with:e}})},createWithoutTable(){return freeze({kind:"UpdateQueryNode"})},cloneWithFromItems(r,e){return freeze({...r,from:r.from?FromNode.cloneWithFroms(r.from,e):FromNode.create(e)})},cloneWithUpdates(r,e){return freeze({...r,updates:r.updates?freeze([...r.updates,...e]):e})},cloneWithLimit(r,e){return freeze({...r,limit:e})}}),UsingNode=freeze({is(r){return r.kind==="UsingNode"},create(r){return freeze({kind:"UsingNode",tables:freeze(r)})},cloneWithTables(r,e){return freeze({...r,tables:freeze([...r.tables,...e])})}}),DeleteQueryNode=freeze({is(r){return r.kind==="DeleteQueryNode"},create(r,e){return freeze({kind:"DeleteQueryNode",from:FromNode.create(r),...e&&{with:e}})},cloneWithOrderByItems:(r,e)=>QueryNode.cloneWithOrderByItems(r,e),cloneWithoutOrderBy:r=>QueryNode.cloneWithoutOrderBy(r),cloneWithLimit(r,e){return freeze({...r,limit:e})},cloneWithoutLimit(r){return freeze({...r,limit:void 0})},cloneWithUsing(r,e){return freeze({...r,using:r.using!==void 0?UsingNode.cloneWithTables(r.using,e):UsingNode.create(e)})}}),WhereNode=freeze({is(r){return r.kind==="WhereNode"},create(r){return freeze({kind:"WhereNode",where:r})},cloneWithOperation(r,e,M){return freeze({...r,where:e==="And"?AndNode.create(r.where,M):OrNode.create(r.where,M)})}}),ReturningNode=freeze({is(r){return r.kind==="ReturningNode"},create(r){return freeze({kind:"ReturningNode",selections:freeze(r)})},cloneWithSelections(r,e){return freeze({...r,selections:r.selections?freeze([...r.selections,...e]):freeze(e)})}}),ExplainNode=freeze({is(r){return r.kind==="ExplainNode"},create(r,e){return freeze({kind:"ExplainNode",format:r,options:e})}}),WhenNode=freeze({is(r){return r.kind==="WhenNode"},create(r){return freeze({kind:"WhenNode",condition:r})},cloneWithResult(r,e){return freeze({...r,result:e})}}),MergeQueryNode=freeze({is(r){return r.kind==="MergeQueryNode"},create(r,e){return freeze({kind:"MergeQueryNode",into:r,...e&&{with:e}})},cloneWithUsing(r,e){return freeze({...r,using:e})},cloneWithWhen(r,e){return freeze({...r,whens:r.whens?freeze([...r.whens,e]):freeze([e])})},cloneWithThen(r,e){return freeze({...r,whens:r.whens?freeze([...r.whens.slice(0,-1),WhenNode.cloneWithResult(r.whens[r.whens.length-1],e)]):void 0})}}),OutputNode=freeze({is(r){return r.kind==="OutputNode"},create(r){return freeze({kind:"OutputNode",selections:freeze(r)})},cloneWithSelections(r,e){return freeze({...r,selections:r.selections?freeze([...r.selections,...e]):freeze(e)})}}),QueryNode=freeze({is(r){return SelectQueryNode.is(r)||InsertQueryNode.is(r)||UpdateQueryNode.is(r)||DeleteQueryNode.is(r)||MergeQueryNode.is(r)},cloneWithEndModifier(r,e){return freeze({...r,endModifiers:r.endModifiers?freeze([...r.endModifiers,e]):freeze([e])})},cloneWithWhere(r,e){return freeze({...r,where:r.where?WhereNode.cloneWithOperation(r.where,"And",e):WhereNode.create(e)})},cloneWithJoin(r,e){return freeze({...r,joins:r.joins?freeze([...r.joins,e]):freeze([e])})},cloneWithReturning(r,e){return freeze({...r,returning:r.returning?ReturningNode.cloneWithSelections(r.returning,e):ReturningNode.create(e)})},cloneWithoutReturning(r){return freeze({...r,returning:void 0})},cloneWithoutWhere(r){return freeze({...r,where:void 0})},cloneWithExplain(r,e,M){return freeze({...r,explain:ExplainNode.create(e,M?.toOperationNode())})},cloneWithTop(r,e){return freeze({...r,top:e})},cloneWithOutput(r,e){return freeze({...r,output:r.output?OutputNode.cloneWithSelections(r.output,e):OutputNode.create(e)})},cloneWithOrderByItems(r,e){return freeze({...r,orderBy:r.orderBy?OrderByNode.cloneWithItems(r.orderBy,e):OrderByNode.create(e)})},cloneWithoutOrderBy(r){return freeze({...r,orderBy:void 0})}}),SelectQueryNode=freeze({is(r){return r.kind==="SelectQueryNode"},create(r){return freeze({kind:"SelectQueryNode",...r&&{with:r}})},createFrom(r,e){return freeze({kind:"SelectQueryNode",from:FromNode.create(r),...e&&{with:e}})},cloneWithSelections(r,e){return freeze({...r,selections:r.selections?freeze([...r.selections,...e]):freeze(e)})},cloneWithDistinctOn(r,e){return freeze({...r,distinctOn:r.distinctOn?freeze([...r.distinctOn,...e]):freeze(e)})},cloneWithFrontModifier(r,e){return freeze({...r,frontModifiers:r.frontModifiers?freeze([...r.frontModifiers,e]):freeze([e])})},cloneWithOrderByItems:(r,e)=>QueryNode.cloneWithOrderByItems(r,e),cloneWithGroupByItems(r,e){return freeze({...r,groupBy:r.groupBy?GroupByNode.cloneWithItems(r.groupBy,e):GroupByNode.create(e)})},cloneWithLimit(r,e){return freeze({...r,limit:e})},cloneWithOffset(r,e){return freeze({...r,offset:e})},cloneWithFetch(r,e){return freeze({...r,fetch:e})},cloneWithHaving(r,e){return freeze({...r,having:r.having?HavingNode.cloneWithOperation(r.having,"And",e):HavingNode.create(e)})},cloneWithSetOperations(r,e){return freeze({...r,setOperations:r.setOperations?freeze([...r.setOperations,...e]):freeze([...e])})},cloneWithoutSelections(r){return freeze({...r,selections:[]})},cloneWithoutLimit(r){return freeze({...r,limit:void 0})},cloneWithoutOffset(r){return freeze({...r,offset:void 0})},cloneWithoutOrderBy:r=>QueryNode.cloneWithoutOrderBy(r),cloneWithoutGroupBy(r){return freeze({...r,groupBy:void 0})}});class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:JoinNode.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,M,tr){return new JoinBuilder({...this.#e,joinNode:JoinNode.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,M,tr))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:JoinNode.cloneWithOn(this.#e.joinNode,RawNode.createWithSql("true"))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}}const PartitionByItemNode=freeze({is(r){return r.kind==="PartitionByItemNode"},create(r){return freeze({kind:"PartitionByItemNode",partitionBy:r})}});function parsePartitionBy(r){return parseReferenceExpressionOrList(r).map(PartitionByItemNode.create)}class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:OverNode.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:QueryNode.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:OverNode.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}}const SelectionNode=freeze({is(r){return r.kind==="SelectionNode"},create(r){return freeze({kind:"SelectionNode",selection:r})},createSelectAll(){return freeze({kind:"SelectionNode",selection:SelectAllNode.create()})},createSelectAllFromTable(r){return freeze({kind:"SelectionNode",selection:ReferenceNode.createSelectAll(r)})}});function parseSelectArg(r){return isFunction(r)?parseSelectArg(r(expressionBuilder())):isReadonlyArray(r)?r.map(e=>parseSelectExpression(e)):[parseSelectExpression(r)]}function parseSelectExpression(r){return isString$1(r)?SelectionNode.create(parseAliasedStringReference(r)):isDynamicReferenceBuilder(r)?SelectionNode.create(r.toOperationNode()):SelectionNode.create(parseAliasedExpression(r))}function parseSelectAll(r){return r?Array.isArray(r)?r.map(parseSelectAllArg):[parseSelectAllArg(r)]:[SelectionNode.createSelectAll()]}function parseSelectAllArg(r){if(isString$1(r))return SelectionNode.createSelectAllFromTable(parseTable(r));throw new Error(`invalid value selectAll expression: ${JSON.stringify(r)}`)}const ValuesNode=freeze({is(r){return r.kind==="ValuesNode"},create(r){return freeze({kind:"ValuesNode",values:freeze(r)})}}),DefaultInsertValueNode=freeze({is(r){return r.kind==="DefaultInsertValueNode"},create(){return freeze({kind:"DefaultInsertValueNode"})}});function parseInsertExpression(r){const e=isFunction(r)?r(expressionBuilder()):r,M=isReadonlyArray(e)?e:freeze([e]);return parseInsertColumnsAndValues(M)}function parseInsertColumnsAndValues(r){const e=parseColumnNamesAndIndexes(r);return[freeze([...e.keys()].map(ColumnNode.create)),ValuesNode.create(r.map(M=>parseRowValues(M,e)))]}function parseColumnNamesAndIndexes(r){const e=new Map;for(const M of r){const tr=Object.keys(M);for(const rr of tr)!e.has(rr)&&M[rr]!==void 0&&e.set(rr,e.size)}return e}function parseRowValues(r,e){const M=Object.keys(r),tr=Array.from({length:e.size});let rr=!1,ir=M.length;for(const dr of M){const hr=e.get(dr);if(isUndefined$1(hr)){ir--;continue}const fr=r[dr];(isUndefined$1(fr)||isExpressionOrFactory(fr))&&(rr=!0),tr[hr]=fr}if(ir<e.size||rr){const dr=DefaultInsertValueNode.create();return ValueListNode.create(tr.map(hr=>isUndefined$1(hr)?dr:parseValueExpression(hr)))}return PrimitiveValueListNode.create(tr)}const ColumnUpdateNode=freeze({is(r){return r.kind==="ColumnUpdateNode"},create(r,e){return freeze({kind:"ColumnUpdateNode",column:r,value:e})}});function parseUpdate(...r){return r.length===2?[ColumnUpdateNode.create(parseReferenceExpression(r[0]),parseValueExpression(r[1]))]:parseUpdateObjectExpression(r[0])}function parseUpdateObjectExpression(r){const e=isFunction(r)?r(expressionBuilder()):r;return Object.entries(e).filter(([M,tr])=>tr!==void 0).map(([M,tr])=>ColumnUpdateNode.create(ColumnNode.create(M),parseValueExpression(tr)))}const OnDuplicateKeyNode=freeze({is(r){return r.kind==="OnDuplicateKeyNode"},create(r){return freeze({kind:"OnDuplicateKeyNode",updates:r})}});class InsertResult{insertId;numInsertedOrUpdatedRows;constructor(e,M){this.insertId=e,this.numInsertedOrUpdatedRows=M}}class NoResultError extends Error{node;constructor(e){super("no result"),this.node=e}}function isNoResultErrorConstructor(r){return Object.prototype.hasOwnProperty.call(r,"prototype")}const OnConflictNode=freeze({is(r){return r.kind==="OnConflictNode"},create(){return freeze({kind:"OnConflictNode"})},cloneWith(r,e){return freeze({...r,...e})},cloneWithIndexWhere(r,e){return freeze({...r,indexWhere:r.indexWhere?WhereNode.cloneWithOperation(r.indexWhere,"And",e):WhereNode.create(e)})},cloneWithIndexOrWhere(r,e){return freeze({...r,indexWhere:r.indexWhere?WhereNode.cloneWithOperation(r.indexWhere,"Or",e):WhereNode.create(e)})},cloneWithUpdateWhere(r,e){return freeze({...r,updateWhere:r.updateWhere?WhereNode.cloneWithOperation(r.updateWhere,"And",e):WhereNode.create(e)})},cloneWithUpdateOrWhere(r,e){return freeze({...r,updateWhere:r.updateWhere?WhereNode.cloneWithOperation(r.updateWhere,"Or",e):WhereNode.create(e)})},cloneWithoutIndexWhere(r){return freeze({...r,indexWhere:void 0})},cloneWithoutUpdateWhere(r){return freeze({...r,updateWhere:void 0})}});class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){const M=ColumnNode.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,M]):freeze([M])})})}columns(e){const M=e.map(ColumnNode.create);return new OnConflictBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,...M]):freeze(M)})})}constraint(e){return new OnConflictBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWith(this.#e.onConflictNode,{constraint:IdentifierNode.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,M,tr){return new OnConflictBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,M,tr))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWith(this.#e.onConflictNode,{updates:parseUpdateObjectExpression(e)})})}$call(e){return e(this)}}class OnConflictDoNothingBuilder{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.onConflictNode}}class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,M,tr){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,M,tr))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:OnConflictNode.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}}const TopNode=freeze({is(r){return r.kind==="TopNode"},create(r,e){return freeze({kind:"TopNode",expression:r,modifiers:e})}});function parseTop(r,e){if(!isNumber$1(r)&&!isBigInt(r))throw new Error(`Invalid top expression: ${r}`);if(!isUndefined$1(e)&&!isTopModifiers(e))throw new Error(`Invalid top modifiers: ${e}`);return TopNode.create(r,e)}function isTopModifiers(r){return r==="percent"||r==="with ties"||r==="percent with ties"}const OrActionNode=freeze({is(r){return r.kind==="OrActionNode"},create(r){return freeze({kind:"OrActionNode",action:r})}});class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){const[M,tr]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{columns:M,values:tr})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{columns:freeze(e.map(ColumnNode.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{orAction:OrActionNode.create("ignore")})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{orAction:OrActionNode.create("ignore")})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{orAction:OrActionNode.create("abort")})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{orAction:OrActionNode.create("fail")})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{orAction:OrActionNode.create("replace")})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{orAction:OrActionNode.create("rollback")})})}top(e,M){return new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithTop(this.#e.queryNode,parseTop(e,M))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{onConflict:e(new OnConflictBuilder({onConflictNode:OnConflictNode.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:InsertQueryNode.cloneWith(this.#e.queryNode,{onDuplicateKey:OnDuplicateKeyNode.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,M){return e?M(this):new InsertQueryBuilder({...this.#e})}$castTo(){return new InsertQueryBuilder(this.#e)}$narrowType(){return new InsertQueryBuilder(this.#e)}$assertType(){return new InsertQueryBuilder(this.#e)}withPlugin(e){return new InsertQueryBuilder({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),M=await this.#e.executor.executeQuery(e),{adapter:tr}=this.#e.executor,rr=e.query;return rr.returning&&tr.supportsReturning||rr.output&&tr.supportsOutput?M.rows:[new InsertResult(M.insertId,M.numAffectedRows??BigInt(0))]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=NoResultError){const M=await this.executeTakeFirst();if(M===void 0)throw isNoResultErrorConstructor(e)?new e(this.toOperationNode()):e(this.toOperationNode());return M}async*stream(e=100){const M=this.compile(),tr=this.#e.executor.stream(M,e);for await(const rr of tr)yield*rr.rows}async explain(e,M){return await new InsertQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithExplain(this.#e.queryNode,e,M)}).execute()}}class DeleteResult{numDeletedRows;constructor(e){this.numDeletedRows=e}}const LimitNode=freeze({is(r){return r.kind==="LimitNode"},create(r){return freeze({kind:"LimitNode",limit:r})}});class DeleteQueryBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,M,tr){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,M,tr))})}clearWhere(){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithoutWhere(this.#e.queryNode)})}top(e,M){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithTop(this.#e.queryNode,parseTop(e,M))})}using(e){return new DeleteQueryBuilder({...this.#e,queryNode:DeleteQueryNode.cloneWithUsing(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}#t(e,M){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithJoin(this.#e.queryNode,parseJoin(e,M))})}returning(e){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new DeleteQueryBuilder({...this.#e,queryNode:DeleteQueryNode.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new DeleteQueryBuilder({...this.#e,queryNode:DeleteQueryNode.cloneWithLimit(this.#e.queryNode,LimitNode.create(parseValueExpression(e)))})}modifyEnd(e){return new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,M){return e?M(this):new DeleteQueryBuilder({...this.#e})}$castTo(){return new DeleteQueryBuilder(this.#e)}$narrowType(){return new DeleteQueryBuilder(this.#e)}$assertType(){return new DeleteQueryBuilder(this.#e)}withPlugin(e){return new DeleteQueryBuilder({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),M=await this.#e.executor.executeQuery(e),{adapter:tr}=this.#e.executor,rr=e.query;return rr.returning&&tr.supportsReturning||rr.output&&tr.supportsOutput?M.rows:[new DeleteResult(M.numAffectedRows??BigInt(0))]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=NoResultError){const M=await this.executeTakeFirst();if(M===void 0)throw isNoResultErrorConstructor(e)?new e(this.toOperationNode()):e(this.toOperationNode());return M}async*stream(e=100){const M=this.compile(),tr=this.#e.executor.stream(M,e);for await(const rr of tr)yield*rr.rows}async explain(e,M){return await new DeleteQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithExplain(this.#e.queryNode,e,M)}).execute()}}class UpdateResult{numUpdatedRows;numChangedRows;constructor(e,M){this.numUpdatedRows=e,this.numChangedRows=M}}class UpdateQueryBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,M,tr){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,M,tr))})}clearWhere(){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithoutWhere(this.#e.queryNode)})}top(e,M){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithTop(this.#e.queryNode,parseTop(e,M))})}from(e){return new UpdateQueryBuilder({...this.#e,queryNode:UpdateQueryNode.cloneWithFromItems(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}#t(e,M){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithJoin(this.#e.queryNode,parseJoin(e,M))})}orderBy(...e){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new UpdateQueryBuilder({...this.#e,queryNode:UpdateQueryNode.cloneWithLimit(this.#e.queryNode,LimitNode.create(parseValueExpression(e)))})}set(...e){return new UpdateQueryBuilder({...this.#e,queryNode:UpdateQueryNode.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,M){return e?M(this):new UpdateQueryBuilder({...this.#e})}$castTo(){return new UpdateQueryBuilder(this.#e)}$narrowType(){return new UpdateQueryBuilder(this.#e)}$assertType(){return new UpdateQueryBuilder(this.#e)}withPlugin(e){return new UpdateQueryBuilder({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),M=await this.#e.executor.executeQuery(e),{adapter:tr}=this.#e.executor,rr=e.query;return rr.returning&&tr.supportsReturning||rr.output&&tr.supportsOutput?M.rows:[new UpdateResult(M.numAffectedRows??BigInt(0),M.numChangedRows)]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=NoResultError){const M=await this.executeTakeFirst();if(M===void 0)throw isNoResultErrorConstructor(e)?new e(this.toOperationNode()):e(this.toOperationNode());return M}async*stream(e=100){const M=this.compile(),tr=this.#e.executor.stream(M,e);for await(const rr of tr)yield*rr.rows}async explain(e,M){return await new UpdateQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithExplain(this.#e.queryNode,e,M)}).execute()}}const CommonTableExpressionNameNode=freeze({is(r){return r.kind==="CommonTableExpressionNameNode"},create(r,e){return freeze({kind:"CommonTableExpressionNameNode",table:TableNode.create(r),columns:e?freeze(e.map(ColumnNode.create)):void 0})}}),CommonTableExpressionNode=freeze({is(r){return r.kind==="CommonTableExpressionNode"},create(r,e){return freeze({kind:"CommonTableExpressionNode",name:r,expression:e})},cloneWith(r,e){return freeze({...r,...e})}});class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:CommonTableExpressionNode.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:CommonTableExpressionNode.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}}function parseCommonTableExpression(r,e){const M=e(createQueryCreator()).toOperationNode();return isFunction(r)?r(cteBuilderFactory(M)).toOperationNode():CommonTableExpressionNode.create(parseCommonTableExpressionName(r),M)}function cteBuilderFactory(r){return e=>new CTEBuilder({node:CommonTableExpressionNode.create(parseCommonTableExpressionName(e),r)})}function parseCommonTableExpressionName(r){if(r.includes("(")){const e=r.split(/[\(\)]/),M=e[0],tr=e[1].split(",").map(rr=>rr.trim());return CommonTableExpressionNameNode.create(M,tr)}else return CommonTableExpressionNameNode.create(r)}const WithNode=freeze({is(r){return r.kind==="WithNode"},create(r,e){return freeze({kind:"WithNode",expressions:freeze([r]),...e})},cloneWithExpression(r,e){return freeze({...r,expressions:freeze([...r.expressions,e])})}}),CHARS=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function randomString(r){let e="";for(let M=0;M<r;++M)e+=randomChar();return e}function randomChar(){return CHARS[~~(Math.random()*CHARS.length)]}function createQueryId(){return new LazyQueryId}class LazyQueryId{#e;get queryId(){return this.#e===void 0&&(this.#e=randomString(8)),this.#e}}function requireAllProps(r){return r}class OperationNodeTransformer{nodeStack=[];#e=freeze({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(e,M){if(!e)return e;this.nodeStack.push(e);const tr=this.transformNodeImpl(e,M);return this.nodeStack.pop(),freeze(tr)}transformNodeImpl(e,M){return this.#e[e.kind](e,M)}transformNodeList(e,M){return e&&freeze(e.map(tr=>this.transformNode(tr,M)))}transformSelectQuery(e,M){return{kind:"SelectQueryNode",from:this.transformNode(e.from,M),selections:this.transformNodeList(e.selections,M),distinctOn:this.transformNodeList(e.distinctOn,M),joins:this.transformNodeList(e.joins,M),groupBy:this.transformNode(e.groupBy,M),orderBy:this.transformNode(e.orderBy,M),where:this.transformNode(e.where,M),frontModifiers:this.transformNodeList(e.frontModifiers,M),endModifiers:this.transformNodeList(e.endModifiers,M),limit:this.transformNode(e.limit,M),offset:this.transformNode(e.offset,M),with:this.transformNode(e.with,M),having:this.transformNode(e.having,M),explain:this.transformNode(e.explain,M),setOperations:this.transformNodeList(e.setOperations,M),fetch:this.transformNode(e.fetch,M),top:this.transformNode(e.top,M)}}transformSelection(e,M){return{kind:"SelectionNode",selection:this.transformNode(e.selection,M)}}transformColumn(e,M){return{kind:"ColumnNode",column:this.transformNode(e.column,M)}}transformAlias(e,M){return{kind:"AliasNode",node:this.transformNode(e.node,M),alias:this.transformNode(e.alias,M)}}transformTable(e,M){return{kind:"TableNode",table:this.transformNode(e.table,M)}}transformFrom(e,M){return{kind:"FromNode",froms:this.transformNodeList(e.froms,M)}}transformReference(e,M){return{kind:"ReferenceNode",column:this.transformNode(e.column,M),table:this.transformNode(e.table,M)}}transformAnd(e,M){return{kind:"AndNode",left:this.transformNode(e.left,M),right:this.transformNode(e.right,M)}}transformOr(e,M){return{kind:"OrNode",left:this.transformNode(e.left,M),right:this.transformNode(e.right,M)}}transformValueList(e,M){return{kind:"ValueListNode",values:this.transformNodeList(e.values,M)}}transformParens(e,M){return{kind:"ParensNode",node:this.transformNode(e.node,M)}}transformJoin(e,M){return{kind:"JoinNode",joinType:e.joinType,table:this.transformNode(e.table,M),on:this.transformNode(e.on,M)}}transformRaw(e,M){return{kind:"RawNode",sqlFragments:freeze([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,M)}}transformWhere(e,M){return{kind:"WhereNode",where:this.transformNode(e.where,M)}}transformInsertQuery(e,M){return{kind:"InsertQueryNode",into:this.transformNode(e.into,M),columns:this.transformNodeList(e.columns,M),values:this.transformNode(e.values,M),returning:this.transformNode(e.returning,M),onConflict:this.transformNode(e.onConflict,M),onDuplicateKey:this.transformNode(e.onDuplicateKey,M),endModifiers:this.transformNodeList(e.endModifiers,M),with:this.transformNode(e.with,M),ignore:e.ignore,orAction:this.transformNode(e.orAction,M),replace:e.replace,explain:this.transformNode(e.explain,M),defaultValues:e.defaultValues,top:this.transformNode(e.top,M),output:this.transformNode(e.output,M)}}transformValues(e,M){return{kind:"ValuesNode",values:this.transformNodeList(e.values,M)}}transformDeleteQuery(e,M){return{kind:"DeleteQueryNode",from:this.transformNode(e.from,M),using:this.transformNode(e.using,M),joins:this.transformNodeList(e.joins,M),where:this.transformNode(e.where,M),returning:this.transformNode(e.returning,M),endModifiers:this.transformNodeList(e.endModifiers,M),with:this.transformNode(e.with,M),orderBy:this.transformNode(e.orderBy,M),limit:this.transformNode(e.limit,M),explain:this.transformNode(e.explain,M),top:this.transformNode(e.top,M),output:this.transformNode(e.output,M)}}transformReturning(e,M){return{kind:"ReturningNode",selections:this.transformNodeList(e.selections,M)}}transformCreateTable(e,M){return{kind:"CreateTableNode",table:this.transformNode(e.table,M),columns:this.transformNodeList(e.columns,M),constraints:this.transformNodeList(e.constraints,M),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,M),endModifiers:this.transformNodeList(e.endModifiers,M),selectQuery:this.transformNode(e.selectQuery,M)}}transformColumnDefinition(e,M){return{kind:"ColumnDefinitionNode",column:this.transformNode(e.column,M),dataType:this.transformNode(e.dataType,M),references:this.transformNode(e.references,M),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,M),check:this.transformNode(e.check,M),generated:this.transformNode(e.generated,M),frontModifiers:this.transformNodeList(e.frontModifiers,M),endModifiers:this.transformNodeList(e.endModifiers,M),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists}}transformAddColumn(e,M){return{kind:"AddColumnNode",column:this.transformNode(e.column,M)}}transformDropTable(e,M){return{kind:"DropTableNode",table:this.transformNode(e.table,M),ifExists:e.ifExists,cascade:e.cascade}}transformOrderBy(e,M){return{kind:"OrderByNode",items:this.transformNodeList(e.items,M)}}transformOrderByItem(e,M){return{kind:"OrderByItemNode",orderBy:this.transformNode(e.orderBy,M),direction:this.transformNode(e.direction,M),collation:this.transformNode(e.collation,M),nulls:e.nulls}}transformGroupBy(e,M){return{kind:"GroupByNode",items:this.transformNodeList(e.items,M)}}transformGroupByItem(e,M){return{kind:"GroupByItemNode",groupBy:this.transformNode(e.groupBy,M)}}transformUpdateQuery(e,M){return{kind:"UpdateQueryNode",table:this.transformNode(e.table,M),from:this.transformNode(e.from,M),joins:this.transformNodeList(e.joins,M),where:this.transformNode(e.where,M),updates:this.transformNodeList(e.updates,M),returning:this.transformNode(e.returning,M),endModifiers:this.transformNodeList(e.endModifiers,M),with:this.transformNode(e.with,M),explain:this.transformNode(e.explain,M),limit:this.transformNode(e.limit,M),top:this.transformNode(e.top,M),output:this.transformNode(e.output,M),orderBy:this.transformNode(e.orderBy,M)}}transformColumnUpdate(e,M){return{kind:"ColumnUpdateNode",column:this.transformNode(e.column,M),value:this.transformNode(e.value,M)}}transformLimit(e,M){return{kind:"LimitNode",limit:this.transformNode(e.limit,M)}}transformOffset(e,M){return{kind:"OffsetNode",offset:this.transformNode(e.offset,M)}}transformOnConflict(e,M){return{kind:"OnConflictNode",columns:this.transformNodeList(e.columns,M),constraint:this.transformNode(e.constraint,M),indexExpression:this.transformNode(e.indexExpression,M),indexWhere:this.transformNode(e.indexWhere,M),updates:this.transformNodeList(e.updates,M),updateWhere:this.transformNode(e.updateWhere,M),doNothing:e.doNothing}}transformOnDuplicateKey(e,M){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(e.updates,M)}}transformCreateIndex(e,M){return{kind:"CreateIndexNode",name:this.transformNode(e.name,M),table:this.transformNode(e.table,M),columns:this.transformNodeList(e.columns,M),unique:e.unique,using:this.transformNode(e.using,M),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,M),nullsNotDistinct:e.nullsNotDistinct}}transformList(e,M){return{kind:"ListNode",items:this.transformNodeList(e.items,M)}}transformDropIndex(e,M){return{kind:"DropIndexNode",name:this.transformNode(e.name,M),table:this.transformNode(e.table,M),ifExists:e.ifExists,cascade:e.cascade}}transformPrimaryKeyConstraint(e,M){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(e.columns,M),name:this.transformNode(e.name,M),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformUniqueConstraint(e,M){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(e.columns,M),name:this.transformNode(e.name,M),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformForeignKeyConstraint(e,M){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(e.columns,M),references:this.transformNode(e.references,M),name:this.transformNode(e.name,M),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformSetOperation(e,M){return{kind:"SetOperationNode",operator:e.operator,expression:this.transformNode(e.expression,M),all:e.all}}transformReferences(e,M){return{kind:"ReferencesNode",table:this.transformNode(e.table,M),columns:this.transformNodeList(e.columns,M),onDelete:e.onDelete,onUpdate:e.onUpdate}}transformCheckConstraint(e,M){return{kind:"CheckConstraintNode",expression:this.transformNode(e.expression,M),name:this.transformNode(e.name,M)}}transformWith(e,M){return{kind:"WithNode",expressions:this.transformNodeList(e.expressions,M),recursive:e.recursive}}transformCommonTableExpression(e,M){return{kind:"CommonTableExpressionNode",name:this.transformNode(e.name,M),materialized:e.materialized,expression:this.transformNode(e.expression,M)}}transformCommonTableExpressionName(e,M){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(e.table,M),columns:this.transformNodeList(e.columns,M)}}transformHaving(e,M){return{kind:"HavingNode",having:this.transformNode(e.having,M)}}transformCreateSchema(e,M){return{kind:"CreateSchemaNode",schema:this.transformNode(e.schema,M),ifNotExists:e.ifNotExists}}transformDropSchema(e,M){return{kind:"DropSchemaNode",schema:this.transformNode(e.schema,M),ifExists:e.ifExists,cascade:e.cascade}}transformAlterTable(e,M){return{kind:"AlterTableNode",table:this.transformNode(e.table,M),renameTo:this.transformNode(e.renameTo,M),setSchema:this.transformNode(e.setSchema,M),columnAlterations:this.transformNodeList(e.columnAlterations,M),addConstraint:this.transformNode(e.addConstraint,M),dropConstraint:this.transformNode(e.dropConstraint,M),renameConstraint:this.transformNode(e.renameConstraint,M),addIndex:this.transformNode(e.addIndex,M),dropIndex:this.transformNode(e.dropIndex,M)}}transformDropColumn(e,M){return{kind:"DropColumnNode",column:this.transformNode(e.column,M)}}transformRenameColumn(e,M){return{kind:"RenameColumnNode",column:this.transformNode(e.column,M),renameTo:this.transformNode(e.renameTo,M)}}transformAlterColumn(e,M){return{kind:"AlterColumnNode",column:this.transformNode(e.column,M),dataType:this.transformNode(e.dataType,M),dataTypeExpression:this.transformNode(e.dataTypeExpression,M),setDefault:this.transformNode(e.setDefault,M),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull}}transformModifyColumn(e,M){return{kind:"ModifyColumnNode",column:this.transformNode(e.column,M)}}transformAddConstraint(e,M){return{kind:"AddConstraintNode",constraint:this.transformNode(e.constraint,M)}}transformDropConstraint(e,M){return{kind:"DropConstraintNode",constraintName:this.transformNode(e.constraintName,M),ifExists:e.ifExists,modifier:e.modifier}}transformRenameConstraint(e,M){return{kind:"RenameConstraintNode",oldName:this.transformNode(e.oldName,M),newName:this.transformNode(e.newName,M)}}transformCreateView(e,M){return{kind:"CreateViewNode",name:this.transformNode(e.name,M),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,M),as:this.transformNode(e.as,M)}}transformRefreshMaterializedView(e,M){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(e.name,M),concurrently:e.concurrently,withNoData:e.withNoData}}transformDropView(e,M){return{kind:"DropViewNode",name:this.transformNode(e.name,M),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade}}transformGenerated(e,M){return{kind:"GeneratedNode",byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,M)}}transformDefaultValue(e,M){return{kind:"DefaultValueNode",defaultValue:this.transformNode(e.defaultValue,M)}}transformOn(e,M){return{kind:"OnNode",on:this.transformNode(e.on,M)}}transformSelectModifier(e,M){return{kind:"SelectModifierNode",modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,M),of:this.transformNodeList(e.of,M)}}transformCreateType(e,M){return{kind:"CreateTypeNode",name:this.transformNode(e.name,M),enum:this.transformNode(e.enum,M)}}transformDropType(e,M){return{kind:"DropTypeNode",name:this.transformNode(e.name,M),ifExists:e.ifExists}}transformExplain(e,M){return{kind:"ExplainNode",format:e.format,options:this.transformNode(e.options,M)}}transformSchemableIdentifier(e,M){return{kind:"SchemableIdentifierNode",schema:this.transformNode(e.schema,M),identifier:this.transformNode(e.identifier,M)}}transformAggregateFunction(e,M){return{kind:"AggregateFunctionNode",func:e.func,aggregated:this.transformNodeList(e.aggregated,M),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,M),withinGroup:this.transformNode(e.withinGroup,M),filter:this.transformNode(e.filter,M),over:this.transformNode(e.over,M)}}transformOver(e,M){return{kind:"OverNode",orderBy:this.transformNode(e.orderBy,M),partitionBy:this.transformNode(e.partitionBy,M)}}transformPartitionBy(e,M){return{kind:"PartitionByNode",items:this.transformNodeList(e.items,M)}}transformPartitionByItem(e,M){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(e.partitionBy,M)}}transformBinaryOperation(e,M){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(e.leftOperand,M),operator:this.transformNode(e.operator,M),rightOperand:this.transformNode(e.rightOperand,M)}}transformUnaryOperation(e,M){return{kind:"UnaryOperationNode",operator:this.transformNode(e.operator,M),operand:this.transformNode(e.operand,M)}}transformUsing(e,M){return{kind:"UsingNode",tables:this.transformNodeList(e.tables,M)}}transformFunction(e,M){return{kind:"FunctionNode",func:e.func,arguments:this.transformNodeList(e.arguments,M)}}transformCase(e,M){return{kind:"CaseNode",value:this.transformNode(e.value,M),when:this.transformNodeList(e.when,M),else:this.transformNode(e.else,M),isStatement:e.isStatement}}transformWhen(e,M){return{kind:"WhenNode",condition:this.transformNode(e.condition,M),result:this.transformNode(e.result,M)}}transformJSONReference(e,M){return{kind:"JSONReferenceNode",reference:this.transformNode(e.reference,M),traversal:this.transformNode(e.traversal,M)}}transformJSONPath(e,M){return{kind:"JSONPathNode",inOperator:this.transformNode(e.inOperator,M),pathLegs:this.transformNodeList(e.pathLegs,M)}}transformJSONPathLeg(e,M){return{kind:"JSONPathLegNode",type:e.type,value:e.value}}transformJSONOperatorChain(e,M){return{kind:"JSONOperatorChainNode",operator:this.transformNode(e.operator,M),values:this.transformNodeList(e.values,M)}}transformTuple(e,M){return{kind:"TupleNode",values:this.transformNodeList(e.values,M)}}transformMergeQuery(e,M){return{kind:"MergeQueryNode",into:this.transformNode(e.into,M),using:this.transformNode(e.using,M),whens:this.transformNodeList(e.whens,M),with:this.transformNode(e.with,M),top:this.transformNode(e.top,M),endModifiers:this.transformNodeList(e.endModifiers,M),output:this.transformNode(e.output,M),returning:this.transformNode(e.returning,M)}}transformMatched(e,M){return{kind:"MatchedNode",not:e.not,bySource:e.bySource}}transformAddIndex(e,M){return{kind:"AddIndexNode",name:this.transformNode(e.name,M),columns:this.transformNodeList(e.columns,M),unique:e.unique,using:this.transformNode(e.using,M),ifNotExists:e.ifNotExists}}transformCast(e,M){return{kind:"CastNode",expression:this.transformNode(e.expression,M),dataType:this.transformNode(e.dataType,M)}}transformFetch(e,M){return{kind:"FetchNode",rowCount:this.transformNode(e.rowCount,M),modifier:e.modifier}}transformTop(e,M){return{kind:"TopNode",expression:e.expression,modifiers:e.modifiers}}transformOutput(e,M){return{kind:"OutputNode",selections:this.transformNodeList(e.selections,M)}}transformDataType(e,M){return e}transformSelectAll(e,M){return e}transformIdentifier(e,M){return e}transformValue(e,M){return e}transformPrimitiveValueList(e,M){return e}transformOperator(e,M){return e}transformDefaultInsertValue(e,M){return e}transformOrAction(e,M){return e}transformCollate(e,M){return e}}const ROOT_OPERATION_NODES=freeze({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),SCHEMALESS_FUNCTIONS={json_agg:!0,to_json:!0};class WithSchemaTransformer extends OperationNodeTransformer{#e;#t=new Set;#r=new Set;constructor(e){super(),this.#e=e}transformNodeImpl(e,M){if(!this.#n(e))return super.transformNodeImpl(e,M);const tr=this.#o(e);for(const lr of tr)this.#r.add(lr);const rr=this.#a(e);for(const lr of rr)this.#t.add(lr);const ir=super.transformNodeImpl(e,M);for(const lr of rr)this.#t.delete(lr);for(const lr of tr)this.#r.delete(lr);return ir}transformSchemableIdentifier(e,M){const tr=super.transformSchemableIdentifier(e,M);return tr.schema||!this.#t.has(e.identifier.name)?tr:{...tr,schema:IdentifierNode.create(this.#e)}}transformReferences(e,M){const tr=super.transformReferences(e,M);return tr.table.table.schema?tr:{...tr,table:TableNode.createWithSchema(this.#e,tr.table.table.identifier.name)}}transformAggregateFunction(e,M){return{...super.transformAggregateFunction({...e,aggregated:[]},M),aggregated:this.#s(e,M,"aggregated")}}transformFunction(e,M){return{...super.transformFunction({...e,arguments:[]},M),arguments:this.#s(e,M,"arguments")}}transformSelectModifier(e,M){return{...super.transformSelectModifier({...e,of:void 0},M),of:e.of?.map(tr=>TableNode.is(tr)&&!tr.table.schema?{...tr,table:this.transformIdentifier(tr.table.identifier,M)}:this.transformNode(tr,M))}}#s(e,M,tr){return SCHEMALESS_FUNCTIONS[e.func]?e[tr].map(rr=>!TableNode.is(rr)||rr.table.schema?this.transformNode(rr,M):{...rr,table:this.transformIdentifier(rr.table.identifier,M)}):this.transformNodeList(e[tr],M)}#n(e){return e.kind in ROOT_OPERATION_NODES}#a(e){const M=new Set;if("name"in e&&e.name&&SchemableIdentifierNode.is(e.name)&&this.#l(e.name,M),"from"in e&&e.from)for(const tr of e.from.froms)this.#i(tr,M);if("into"in e&&e.into&&this.#i(e.into,M),"table"in e&&e.table&&this.#i(e.table,M),"joins"in e&&e.joins)for(const tr of e.joins)this.#i(tr.table,M);return"using"in e&&e.using&&(JoinNode.is(e.using)?this.#i(e.using.table,M):this.#i(e.using,M)),M}#o(e){const M=new Set;return"with"in e&&e.with&&this.#c(e.with,M),M}#i(e,M){if(TableNode.is(e))return this.#l(e.table,M);if(AliasNode.is(e)&&TableNode.is(e.node))return this.#l(e.node.table,M);if(ListNode.is(e)){for(const tr of e.items)this.#i(tr,M);return}if(UsingNode.is(e)){for(const tr of e.tables)this.#i(tr,M);return}}#l(e,M){const tr=e.identifier.name;!this.#t.has(tr)&&!this.#r.has(tr)&&M.add(tr)}#c(e,M){for(const tr of e.expressions){const rr=tr.name.table.table.identifier.name;this.#r.has(rr)||M.add(rr)}}}class WithSchemaPlugin{#e;constructor(e){this.#e=new WithSchemaTransformer(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}}const MatchedNode=freeze({is(r){return r.kind==="MatchedNode"},create(r,e=!1){return freeze({kind:"MatchedNode",not:r,bySource:e})}});function parseMergeWhen(r,e,M){return WhenNode.create(parseFilterList([MatchedNode.create(!r.isMatched,r.bySource),...e&&e.length>0?[e.length===3&&M?parseReferentialBinaryOperation(e[0],e[1],e[2]):parseValueBinaryOperationOrExpression(e)]:[]],"and",!1))}function parseMergeThen(r){return isString$1(r)?RawNode.create([r],[]):isOperationNodeSource(r)?r.toOperationNode():r}class Deferred{#e;#t;#r;constructor(){this.#e=new Promise((e,M)=>{this.#r=M,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t&&this.#t(e)};reject=e=>{this.#r&&this.#r(e)}}async function provideControlledConnection(r){const e=new Deferred,M=new Deferred;return r.provideConnection(async tr=>(e.resolve(tr),await M.promise)).catch(tr=>e.reject(tr)),freeze({connection:await e.promise,release:M.resolve})}const NO_PLUGINS=freeze([]);class QueryExecutorBase{#e;constructor(e=NO_PLUGINS){this.#e=e}get plugins(){return this.#e}transformQuery(e,M){for(const tr of this.#e){const rr=tr.transformQuery({node:e,queryId:M});if(rr.kind===e.kind)e=rr;else throw new Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${e.kind}`,`but it returned a ${rr.kind}`].join(" "))}return e}async executeQuery(e){return await this.provideConnection(async M=>{const tr=await M.executeQuery(e);return"numUpdatedOrDeletedRows"in tr&&logOnce("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."),await this.#t(tr,e.queryId)})}async*stream(e,M){const{connection:tr,release:rr}=await provideControlledConnection(this);try{for await(const ir of tr.streamQuery(e,M))yield await this.#t(ir,e.queryId)}finally{rr()}}async#t(e,M){for(const tr of this.#e)e=await tr.transformResult({result:e,queryId:M});return e}}class NoopQueryExecutor extends QueryExecutorBase{get adapter(){throw new Error("this query cannot be compiled to SQL")}compileQuery(){throw new Error("this query cannot be compiled to SQL")}provideConnection(){throw new Error("this query cannot be executed")}withConnectionProvider(){throw new Error("this query cannot have a connection provider")}withPlugin(e){return new NoopQueryExecutor([...this.plugins,e])}withPlugins(e){return new NoopQueryExecutor([...this.plugins,...e])}withPluginAtFront(e){return new NoopQueryExecutor([e,...this.plugins])}withoutPlugins(){return new NoopQueryExecutor([])}}const NOOP_QUERY_EXECUTOR=new NoopQueryExecutor;class MergeResult{numChangedRows;constructor(e){this.numChangedRows=e}}class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,M){return new MergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithTop(this.#e.queryNode,parseTop(e,M))})}using(...e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:MergeQueryNode.cloneWithUsing(this.#e.queryNode,parseJoin("Using",e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}}class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,M){return new WheneableMergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithTop(this.#e.queryNode,parseTop(e,M))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,M,tr){return this.#t([e,M,tr],!0)}#t(e,M){return new MatchedThenableMergeQueryBuilder({...this.#e,queryNode:MergeQueryNode.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!0},e,M))})}whenNotMatched(){return this.#r([])}whenNotMatchedAnd(...e){return this.#r(e)}whenNotMatchedAndRef(e,M,tr){return this.#r([e,M,tr],!0)}whenNotMatchedBySource(){return this.#r([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#r(e,!1,!0)}whenNotMatchedBySourceAndRef(e,M,tr){return this.#r([e,M,tr],!0,!0)}returning(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:QueryNode.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#r(e,M=!1,tr=!1){const rr={...this.#e,queryNode:MergeQueryNode.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!1,bySource:tr},e,M))},ir=tr?MatchedThenableMergeQueryBuilder:NotMatchedThenableMergeQueryBuilder;return new ir(rr)}$call(e){return e(this)}$if(e,M){return e?M(this):new WheneableMergeQueryBuilder({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),M=await this.#e.executor.executeQuery(e),{adapter:tr}=this.#e.executor,rr=e.query;return rr.returning&&tr.supportsReturning||rr.output&&tr.supportsOutput?M.rows:[new MergeResult(M.numAffectedRows)]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=NoResultError){const M=await this.executeTakeFirst();if(M===void 0)throw isNoResultErrorConstructor(e)?new e(this.toOperationNode()):e(this.toOperationNode());return M}}class MatchedThenableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}thenDelete(){return new WheneableMergeQueryBuilder({...this.#e,queryNode:MergeQueryNode.cloneWithThen(this.#e.queryNode,parseMergeThen("delete"))})}thenDoNothing(){return new WheneableMergeQueryBuilder({...this.#e,queryNode:MergeQueryNode.cloneWithThen(this.#e.queryNode,parseMergeThen("do nothing"))})}thenUpdate(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:MergeQueryNode.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:NOOP_QUERY_EXECUTOR,queryNode:UpdateQueryNode.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(M=>M.set(...e))}}class NotMatchedThenableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new WheneableMergeQueryBuilder({...this.#e,queryNode:MergeQueryNode.cloneWithThen(this.#e.queryNode,parseMergeThen("do nothing"))})}thenInsertValues(e){const[M,tr]=parseInsertExpression(e);return new WheneableMergeQueryBuilder({...this.#e,queryNode:MergeQueryNode.cloneWithThen(this.#e.queryNode,parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(),{columns:M,values:tr})))})}}class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:SelectQueryNode.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:SelectQueryNode.cloneWithSelections(SelectQueryNode.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new InsertQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:InsertQueryNode.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new InsertQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:InsertQueryNode.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:DeleteQueryNode.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:UpdateQueryNode.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new MergeQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:MergeQueryNode.create(parseAliasedTable(e),this.#e.withNode)})}with(e,M){const tr=parseCommonTableExpression(e,M);return new QueryCreator({...this.#e,withNode:this.#e.withNode?WithNode.cloneWithExpression(this.#e.withNode,tr):WithNode.create(tr)})}withRecursive(e,M){const tr=parseCommonTableExpression(e,M);return new QueryCreator({...this.#e,withNode:this.#e.withNode?WithNode.cloneWithExpression(this.#e.withNode,tr):WithNode.create(tr,{recursive:!0})})}withPlugin(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new QueryCreator({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}}function createQueryCreator(){return new QueryCreator({executor:NOOP_QUERY_EXECUTOR})}function createJoinBuilder(r,e){return new JoinBuilder({joinNode:JoinNode.create(r,parseTableExpression(e))})}function createOverBuilder(){return new OverBuilder({overNode:OverNode.create()})}function parseJoin(r,e){if(e.length===3)return parseSingleOnJoin(r,e[0],e[1],e[2]);if(e.length===2)return parseCallbackJoin(r,e[0],e[1]);if(e.length===1)return parseOnlessJoin(r,e[0]);throw new Error("not implemented")}function parseCallbackJoin(r,e,M){return M(createJoinBuilder(r,e)).toOperationNode()}function parseSingleOnJoin(r,e,M,tr){return JoinNode.createWithOn(r,parseTableExpression(e),parseReferentialBinaryOperation(M,"=",tr))}function parseOnlessJoin(r,e){return JoinNode.create(r,parseTableExpression(e))}const OffsetNode=freeze({is(r){return r.kind==="OffsetNode"},create(r){return freeze({kind:"OffsetNode",offset:r})}}),GroupByItemNode=freeze({is(r){return r.kind==="GroupByItemNode"},create(r){return freeze({kind:"GroupByItemNode",groupBy:r})}});function parseGroupBy(r){return r=isFunction(r)?r(expressionBuilder()):r,parseReferenceExpressionOrList(r).map(GroupByItemNode.create)}const SetOperationNode=freeze({is(r){return r.kind==="SetOperationNode"},create(r,e,M){return freeze({kind:"SetOperationNode",operator:r,expression:e,all:M})}});function parseSetOperations(r,e,M){return isFunction(e)&&(e=e(createExpressionBuilder())),isReadonlyArray(e)||(e=[e]),e.map(tr=>SetOperationNode.create(r,parseExpression(tr),M))}class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(OrNode.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new AndWrapper(AndNode.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new ExpressionWrapper(this.#e)}$notNull(){return new ExpressionWrapper(this.#e)}toOperationNode(){return this.#e}}class AliasedExpressionWrapper{#e;#t;constructor(e,M){this.#e=e,this.#t=M}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return AliasNode.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():IdentifierNode.create(this.#t))}}class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(OrNode.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return ParensNode.create(this.#e)}}class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(AndNode.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return ParensNode.create(this.#e)}}const FetchNode=freeze({is(r){return r.kind==="FetchNode"},create(r,e){return{kind:"FetchNode",rowCount:ValueNode.create(r),modifier:e}}});function parseFetch(r,e){if(!isNumber$1(r)&&!isBigInt(r))throw new Error(`Invalid fetch row count: ${r}`);if(!isFetchModifier(e))throw new Error(`Invalid fetch modifier: ${e}`);return FetchNode.create(r,e)}function isFetchModifier(r){return r==="only"||r==="with ties"}class SelectQueryBuilderImpl{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,M,tr){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,M,tr))})}having(...e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,M,tr){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,M,tr))})}select(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithFrontModifier(this.#e.queryNode,SelectModifierNode.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,SelectModifierNode.createWithExpression(e.toOperationNode()))})}distinct(){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithFrontModifier(this.#e.queryNode,SelectModifierNode.create("Distinct"))})}forUpdate(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,SelectModifierNode.create("ForUpdate",e?asArray$1(e).map(parseTable):void 0))})}forShare(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,SelectModifierNode.create("ForShare",e?asArray$1(e).map(parseTable):void 0))})}forKeyShare(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,SelectModifierNode.create("ForKeyShare",e?asArray$1(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,SelectModifierNode.create("ForNoKeyUpdate",e?asArray$1(e).map(parseTable):void 0))})}skipLocked(){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,SelectModifierNode.create("SkipLocked"))})}noWait(){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithEndModifier(this.#e.queryNode,SelectModifierNode.create("NoWait"))})}selectAll(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSelections(this.#e.queryNode,parseSelectAll(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}crossJoin(...e){return this.#t("CrossJoin",e)}innerJoinLateral(...e){return this.#t("LateralInnerJoin",e)}leftJoinLateral(...e){return this.#t("LateralLeftJoin",e)}crossJoinLateral(...e){return this.#t("LateralCrossJoin",e)}crossApply(...e){return this.#t("CrossApply",e)}outerApply(...e){return this.#t("OuterApply",e)}#t(e,M){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithJoin(this.#e.queryNode,parseJoin(e,M))})}orderBy(...e){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithLimit(this.#e.queryNode,LimitNode.create(parseValueExpression(e)))})}offset(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithOffset(this.#e.queryNode,OffsetNode.create(parseValueExpression(e)))})}fetch(e,M="only"){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithFetch(this.#e.queryNode,parseFetch(e,M))})}top(e,M){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithTop(this.#e.queryNode,parseTop(e,M))})}union(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSetOperations(this.#e.queryNode,parseSetOperations("union",e,!1))})}unionAll(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSetOperations(this.#e.queryNode,parseSetOperations("union",e,!0))})}intersect(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSetOperations(this.#e.queryNode,parseSetOperations("intersect",e,!1))})}intersectAll(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSetOperations(this.#e.queryNode,parseSetOperations("intersect",e,!0))})}except(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSetOperations(this.#e.queryNode,parseSetOperations("except",e,!1))})}exceptAll(e){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithSetOperations(this.#e.queryNode,parseSetOperations("except",e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new SelectQueryBuilderImpl({...this.#e,queryNode:SelectQueryNode.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,M){return e?M(this):new SelectQueryBuilderImpl({...this.#e})}$castTo(){return new SelectQueryBuilderImpl(this.#e)}$narrowType(){return new SelectQueryBuilderImpl(this.#e)}$assertType(){return new SelectQueryBuilderImpl(this.#e)}$asTuple(){return new ExpressionWrapper(this.toOperationNode())}$asScalar(){return new ExpressionWrapper(this.toOperationNode())}withPlugin(e){return new SelectQueryBuilderImpl({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile();return(await this.#e.executor.executeQuery(e)).rows}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=NoResultError){const M=await this.executeTakeFirst();if(M===void 0)throw isNoResultErrorConstructor(e)?new e(this.toOperationNode()):e(this.toOperationNode());return M}async*stream(e=100){const M=this.compile(),tr=this.#e.executor.stream(M,e);for await(const rr of tr)yield*rr.rows}async explain(e,M){return await new SelectQueryBuilderImpl({...this.#e,queryNode:QueryNode.cloneWithExplain(this.#e.queryNode,e,M)}).execute()}}function createSelectQueryBuilder(r){return new SelectQueryBuilderImpl(r)}class AliasedSelectQueryBuilderImpl{#e;#t;constructor(e,M){this.#e=e,this.#t=M}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return AliasNode.create(this.#e.toOperationNode(),IdentifierNode.create(this.#t))}}const AggregateFunctionNode=freeze({is(r){return r.kind==="AggregateFunctionNode"},create(r,e=[]){return freeze({kind:"AggregateFunctionNode",func:r,aggregated:e})},cloneWithDistinct(r){return freeze({...r,distinct:!0})},cloneWithOrderBy(r,e,M=!1){const tr=M?"withinGroup":"orderBy";return freeze({...r,[tr]:r[tr]?OrderByNode.cloneWithItems(r[tr],e):OrderByNode.create(e)})},cloneWithFilter(r,e){return freeze({...r,filter:r.filter?WhereNode.cloneWithOperation(r.filter,"And",e):WhereNode.create(e)})},cloneWithOrFilter(r,e){return freeze({...r,filter:r.filter?WhereNode.cloneWithOperation(r.filter,"Or",e):WhereNode.create(e)})},cloneWithOver(r,e){return freeze({...r,over:e})}}),FunctionNode=freeze({is(r){return r.kind==="FunctionNode"},create(r,e){return freeze({kind:"FunctionNode",func:r,arguments:e})}});class AggregateFunctionBuilder{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}as(e){return new AliasedAggregateFunctionBuilder(this,e)}distinct(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:AggregateFunctionNode.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:QueryNode.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:QueryNode.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:AggregateFunctionNode.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:AggregateFunctionNode.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,M,tr){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:AggregateFunctionNode.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,M,tr))})}over(e){const M=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:AggregateFunctionNode.cloneWithOver(this.#e.aggregateFunctionNode,(e?e(M):M).toOperationNode())})}$call(e){return e(this)}$castTo(){return new AggregateFunctionBuilder(this.#e)}$notNull(){return new AggregateFunctionBuilder(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}}class AliasedAggregateFunctionBuilder{#e;#t;constructor(e,M){this.#e=e,this.#t=M}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return AliasNode.create(this.#e.toOperationNode(),IdentifierNode.create(this.#t))}}function createFunctionModule(){const r=(M,tr)=>new ExpressionWrapper(FunctionNode.create(M,parseReferenceExpressionOrList(tr??[]))),e=(M,tr)=>new AggregateFunctionBuilder({aggregateFunctionNode:AggregateFunctionNode.create(M,tr?parseReferenceExpressionOrList(tr):void 0)});return Object.assign(r,{agg:e,avg(M){return e("avg",[M])},coalesce(...M){return r("coalesce",M)},count(M){return e("count",[M])},countAll(M){return new AggregateFunctionBuilder({aggregateFunctionNode:AggregateFunctionNode.create("count",parseSelectAll(M))})},max(M){return e("max",[M])},min(M){return e("min",[M])},sum(M){return e("sum",[M])},any(M){return r("any",[M])},jsonAgg(M){return new AggregateFunctionBuilder({aggregateFunctionNode:AggregateFunctionNode.create("json_agg",[isString$1(M)?parseTable(M):M.toOperationNode()])})},toJson(M){return new ExpressionWrapper(FunctionNode.create("to_json",[isString$1(M)?parseTable(M):M.toOperationNode()]))}})}const UnaryOperationNode=freeze({is(r){return r.kind==="UnaryOperationNode"},create(r,e){return freeze({kind:"UnaryOperationNode",operator:r,operand:e})}});function parseUnaryOperation(r,e){return UnaryOperationNode.create(OperatorNode.create(r),parseReferenceExpression(e))}const CaseNode=freeze({is(r){return r.kind==="CaseNode"},create(r){return freeze({kind:"CaseNode",value:r})},cloneWithWhen(r,e){return freeze({...r,when:freeze(r.when?[...r.when,e]:[e])})},cloneWithThen(r,e){return freeze({...r,when:r.when?freeze([...r.when.slice(0,-1),WhenNode.cloneWithResult(r.when[r.when.length-1],e)]):void 0})},cloneWith(r,e){return freeze({...r,...e})}});class CaseBuilder{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:CaseNode.cloneWithWhen(this.#e.node,WhenNode.create(parseValueBinaryOperationOrExpression(e)))})}}class CaseThenBuilder{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:CaseNode.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}}class CaseWhenBuilder{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:CaseNode.cloneWithWhen(this.#e.node,WhenNode.create(parseValueBinaryOperationOrExpression(e)))})}else(e){return new CaseEndBuilder({...this.#e,node:CaseNode.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}end(){return new ExpressionWrapper(CaseNode.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new ExpressionWrapper(CaseNode.cloneWith(this.#e.node,{isStatement:!0}))}}class CaseEndBuilder{#e;constructor(e){this.#e=freeze(e)}end(){return new ExpressionWrapper(CaseNode.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new ExpressionWrapper(CaseNode.cloneWith(this.#e.node,{isStatement:!0}))}}const JSONPathLegNode=freeze({is(r){return r.kind==="JSONPathLegNode"},create(r,e){return freeze({kind:"JSONPathLegNode",type:r,value:e})}});class JSONPathBuilder{#e;constructor(e){this.#e=e}at(e){return this.#t("ArrayLocation",e)}key(e){return this.#t("Member",e)}#t(e,M){return JSONReferenceNode.is(this.#e)?new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#e,JSONPathNode.is(this.#e.traversal)?JSONPathNode.cloneWithLeg(this.#e.traversal,JSONPathLegNode.create(e,M)):JSONOperatorChainNode.cloneWithValue(this.#e.traversal,ValueNode.createImmediate(M)))):new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#e,JSONPathLegNode.create(e,M)))}}class TraversedJSONPathBuilder extends JSONPathBuilder{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new AliasedJSONPathBuilder(this,e)}$castTo(){return new TraversedJSONPathBuilder(this.#e)}$notNull(){return new TraversedJSONPathBuilder(this.#e)}toOperationNode(){return this.#e}}class AliasedJSONPathBuilder{#e;#t;constructor(e,M){this.#e=e,this.#t=M}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return AliasNode.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():IdentifierNode.create(this.#t))}}const TupleNode=freeze({is(r){return r.kind==="TupleNode"},create(r){return freeze({kind:"TupleNode",values:freeze(r)})}}),SIMPLE_COLUMN_DATA_TYPES=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],COLUMN_DATA_TYPE_REGEX=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],DataTypeNode=freeze({is(r){return r.kind==="DataTypeNode"},create(r){return freeze({kind:"DataTypeNode",dataType:r})}});function isColumnDataType(r){return!!(SIMPLE_COLUMN_DATA_TYPES.includes(r)||COLUMN_DATA_TYPE_REGEX.some(e=>e.test(r)))}function parseDataTypeExpression(r){if(isOperationNodeSource(r))return r.toOperationNode();if(isColumnDataType(r))return DataTypeNode.create(r);throw new Error(`invalid column data type ${JSON.stringify(r)}`)}const CastNode=freeze({is(r){return r.kind==="CastNode"},create(r,e){return freeze({kind:"CastNode",expression:r,dataType:e})}});function createExpressionBuilder(r=NOOP_QUERY_EXECUTOR){function e(rr,ir,lr){return new ExpressionWrapper(parseValueBinaryOperation(rr,ir,lr))}function M(rr,ir){return new ExpressionWrapper(parseUnaryOperation(rr,ir))}const tr=Object.assign(e,{fn:void 0,eb:void 0,selectFrom(rr){return createSelectQueryBuilder({queryId:createQueryId(),executor:r,queryNode:SelectQueryNode.createFrom(parseTableExpressionOrList(rr))})},case(rr){return new CaseBuilder({node:CaseNode.create(isUndefined$1(rr)?void 0:parseReferenceExpression(rr))})},ref(rr,ir){return isUndefined$1(ir)?new ExpressionWrapper(parseStringReference(rr)):new JSONPathBuilder(parseJSONReference(rr,ir))},jsonPath(){return new JSONPathBuilder(JSONPathNode.create())},table(rr){return new ExpressionWrapper(parseTable(rr))},val(rr){return new ExpressionWrapper(parseValueExpression(rr))},refTuple(...rr){return new ExpressionWrapper(TupleNode.create(rr.map(parseReferenceExpression)))},tuple(...rr){return new ExpressionWrapper(TupleNode.create(rr.map(parseValueExpression)))},lit(rr){return new ExpressionWrapper(parseSafeImmediateValue(rr))},unary:M,not(rr){return M("not",rr)},exists(rr){return M("exists",rr)},neg(rr){return M("-",rr)},between(rr,ir,lr){return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(rr),OperatorNode.create("between"),AndNode.create(parseValueExpression(ir),parseValueExpression(lr))))},betweenSymmetric(rr,ir,lr){return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(rr),OperatorNode.create("between symmetric"),AndNode.create(parseValueExpression(ir),parseValueExpression(lr))))},and(rr){return isReadonlyArray(rr)?new ExpressionWrapper(parseFilterList(rr,"and")):new ExpressionWrapper(parseFilterObject(rr,"and"))},or(rr){return isReadonlyArray(rr)?new ExpressionWrapper(parseFilterList(rr,"or")):new ExpressionWrapper(parseFilterObject(rr,"or"))},parens(...rr){const ir=parseValueBinaryOperationOrExpression(rr);return ParensNode.is(ir)?new ExpressionWrapper(ir):new ExpressionWrapper(ParensNode.create(ir))},cast(rr,ir){return new ExpressionWrapper(CastNode.create(parseReferenceExpression(rr),parseDataTypeExpression(ir)))},withSchema(rr){return createExpressionBuilder(r.withPluginAtFront(new WithSchemaPlugin(rr)))}});return tr.fn=createFunctionModule(),tr.eb=tr,tr}function expressionBuilder(r){return createExpressionBuilder()}function parseExpression(r){if(isOperationNodeSource(r))return r.toOperationNode();if(isFunction(r))return r(expressionBuilder()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(r)}`)}function parseAliasedExpression(r){if(isOperationNodeSource(r))return r.toOperationNode();if(isFunction(r))return r(expressionBuilder()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(r)}`)}function isExpressionOrFactory(r){return isExpression(r)||isAliasedExpression(r)||isFunction(r)}class DynamicTableBuilder{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new AliasedDynamicTableBuilder(this.#e,e)}}class AliasedDynamicTableBuilder{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,M){this.#e=e,this.#t=M}toOperationNode(){return AliasNode.create(parseTable(this.#e),IdentifierNode.create(this.#t))}}function isAliasedDynamicTableBuilder(r){return isObject(r)&&isOperationNodeSource(r)&&isString$1(r.table)&&isString$1(r.alias)}function parseTableExpressionOrList(r){return isReadonlyArray(r)?r.map(e=>parseTableExpression(e)):[parseTableExpression(r)]}function parseTableExpression(r){return isString$1(r)?parseAliasedTable(r):isAliasedDynamicTableBuilder(r)?r.toOperationNode():parseAliasedExpression(r)}function parseAliasedTable(r){const e=" as ";if(r.includes(e)){const[M,tr]=r.split(e).map(trim$1);return AliasNode.create(parseTable(M),IdentifierNode.create(tr))}else return parseTable(r)}function parseTable(r){if(r.includes(".")){const[M,tr]=r.split(".").map(trim$1);return TableNode.createWithSchema(M,tr)}else return TableNode.create(r)}function trim$1(r){return r.trim()}const AddColumnNode=freeze({is(r){return r.kind==="AddColumnNode"},create(r){return freeze({kind:"AddColumnNode",column:r})}}),ColumnDefinitionNode=freeze({is(r){return r.kind==="ColumnDefinitionNode"},create(r,e){return freeze({kind:"ColumnDefinitionNode",column:ColumnNode.create(r),dataType:e})},cloneWithFrontModifier(r,e){return freeze({...r,frontModifiers:r.frontModifiers?freeze([...r.frontModifiers,e]):[e]})},cloneWithEndModifier(r,e){return freeze({...r,endModifiers:r.endModifiers?freeze([...r.endModifiers,e]):[e]})},cloneWith(r,e){return freeze({...r,...e})}}),DropColumnNode=freeze({is(r){return r.kind==="DropColumnNode"},create(r){return freeze({kind:"DropColumnNode",column:ColumnNode.create(r)})}}),RenameColumnNode=freeze({is(r){return r.kind==="RenameColumnNode"},create(r,e){return freeze({kind:"RenameColumnNode",column:ColumnNode.create(r),renameTo:ColumnNode.create(e)})}}),CheckConstraintNode=freeze({is(r){return r.kind==="CheckConstraintNode"},create(r,e){return freeze({kind:"CheckConstraintNode",expression:r,name:e?IdentifierNode.create(e):void 0})}}),ON_MODIFY_FOREIGN_ACTIONS=["no action","restrict","cascade","set null","set default"],ReferencesNode=freeze({is(r){return r.kind==="ReferencesNode"},create(r,e){return freeze({kind:"ReferencesNode",table:r,columns:freeze([...e])})},cloneWithOnDelete(r,e){return freeze({...r,onDelete:e})},cloneWithOnUpdate(r,e){return freeze({...r,onUpdate:e})}});function parseDefaultValueExpression(r){return isOperationNodeSource(r)?r.toOperationNode():ValueNode.createImmediate(r)}const GeneratedNode=freeze({is(r){return r.kind==="GeneratedNode"},create(r){return freeze({kind:"GeneratedNode",...r})},createWithExpression(r){return freeze({kind:"GeneratedNode",always:!0,expression:r})},cloneWith(r,e){return freeze({...r,...e})}}),DefaultValueNode=freeze({is(r){return r.kind==="DefaultValueNode"},create(r){return freeze({kind:"DefaultValueNode",defaultValue:r})}});function parseOnModifyForeignAction(r){if(ON_MODIFY_FOREIGN_ACTIONS.includes(r))return r;throw new Error(`invalid OnModifyForeignAction ${r}`)}class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{primaryKey:!0}))}references(e){const M=parseStringReference(e);if(!M.table||SelectAllNode.is(M.column))throw new Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{references:ReferencesNode.create(M.table,[M.column])}))}onDelete(e){if(!this.#e.references)throw new Error("on delete constraint can only be added for foreign keys");return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{references:ReferencesNode.cloneWithOnDelete(this.#e.references,parseOnModifyForeignAction(e))}))}onUpdate(e){if(!this.#e.references)throw new Error("on update constraint can only be added for foreign keys");return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{references:ReferencesNode.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{defaultTo:DefaultValueNode.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{check:CheckConstraintNode.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{generated:GeneratedNode.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{generated:GeneratedNode.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{generated:GeneratedNode.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw new Error("stored() can only be called after generatedAlwaysAs");return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{generated:GeneratedNode.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}}const ModifyColumnNode=freeze({is(r){return r.kind==="ModifyColumnNode"},create(r){return freeze({kind:"ModifyColumnNode",column:r})}}),ForeignKeyConstraintNode=freeze({is(r){return r.kind==="ForeignKeyConstraintNode"},create(r,e,M,tr){return freeze({kind:"ForeignKeyConstraintNode",columns:r,references:ReferencesNode.create(e,M),name:tr?IdentifierNode.create(tr):void 0})},cloneWith(r,e){return freeze({...r,...e})}});class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}const AddConstraintNode=freeze({is(r){return r.kind==="AddConstraintNode"},create(r){return freeze({kind:"AddConstraintNode",constraint:r})}}),UniqueConstraintNode=freeze({is(r){return r.kind==="UniqueConstraintNode"},create(r,e,M){return freeze({kind:"UniqueConstraintNode",columns:freeze(r.map(ColumnNode.create)),name:e?IdentifierNode.create(e):void 0,nullsNotDistinct:M})},cloneWith(r,e){return freeze({...r,...e})}}),DropConstraintNode=freeze({is(r){return r.kind==="DropConstraintNode"},create(r){return freeze({kind:"DropConstraintNode",constraintName:IdentifierNode.create(r)})},cloneWith(r,e){return freeze({...r,...e})}}),AlterColumnNode=freeze({is(r){return r.kind==="AlterColumnNode"},create(r,e,M){return freeze({kind:"AlterColumnNode",column:ColumnNode.create(r),[e]:M})}});class AlterColumnBuilder{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(AlterColumnNode.create(this.#e,"dataType",parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(AlterColumnNode.create(this.#e,"setDefault",parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(AlterColumnNode.create(this.#e,"dropDefault",!0))}setNotNull(){return new AlteredColumnBuilder(AlterColumnNode.create(this.#e,"setNotNull",!0))}dropNotNull(){return new AlteredColumnBuilder(AlterColumnNode.create(this.#e,"dropNotNull",!0))}$call(e){return e(this)}}class AlteredColumnBuilder{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}}class AlterTableExecutor{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class AlterTableAddForeignKeyConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}onDelete(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(AlterTableNode.cloneWithTableProps(this.#e.node,{addConstraint:AddConstraintNode.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{dropConstraint:DropConstraintNode.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{dropConstraint:DropConstraintNode.cloneWith(this.#e.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{dropConstraint:DropConstraintNode.cloneWith(this.#e.node.dropConstraint,{modifier:"restrict"})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const PrimaryKeyConstraintNode=freeze({is(r){return r.kind==="PrimaryKeyConstraintNode"},create(r,e){return freeze({kind:"PrimaryKeyConstraintNode",columns:freeze(r.map(ColumnNode.create)),name:e?IdentifierNode.create(e):void 0})},cloneWith(r,e){return freeze({...r,...e})}}),AddIndexNode=freeze({is(r){return r.kind==="AddIndexNode"},create(r){return freeze({kind:"AddIndexNode",name:IdentifierNode.create(r)})},cloneWith(r,e){return freeze({...r,...e})},cloneWithColumns(r,e){return freeze({...r,columns:[...r.columns||[],...e]})}});class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addIndex:AddIndexNode.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addIndex:AddIndexNode.cloneWithColumns(this.#e.node.addIndex,[parseOrderedColumnName(e)])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addIndex:AddIndexNode.cloneWithColumns(this.#e.node.addIndex,e.map(parseOrderedColumnName))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addIndex:AddIndexNode.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addIndex:AddIndexNode.cloneWith(this.#e.node.addIndex,{using:RawNode.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class CheckConstraintBuilder{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}}const RenameConstraintNode=freeze({is(r){return r.kind==="RenameConstraintNode"},create(r,e){return freeze({kind:"RenameConstraintNode",oldName:IdentifierNode.create(r),newName:IdentifierNode.create(e)})}});class AlterTableBuilder{#e;constructor(e){this.#e=freeze(e)}renameTo(e){return new AlterTableExecutor({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{setSchema:IdentifierNode.create(e)})})}alterColumn(e,M){const tr=M(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,tr.toOperationNode())})}dropColumn(e){return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,DropColumnNode.create(e))})}renameColumn(e,M){return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,RenameColumnNode.create(e,M))})}addColumn(e,M,tr=noop$1){const rr=tr(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(e,parseDataTypeExpression(M))));return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,AddColumnNode.create(rr.toOperationNode()))})}modifyColumn(e,M,tr=noop$1){const rr=tr(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(e,parseDataTypeExpression(M))));return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,ModifyColumnNode.create(rr.toOperationNode()))})}addUniqueConstraint(e,M,tr=noop$1){const rr=tr(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(M,e)));return new AlterTableExecutor({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addConstraint:AddConstraintNode.create(rr.toOperationNode())})})}addCheckConstraint(e,M,tr=noop$1){const rr=tr(new CheckConstraintBuilder(CheckConstraintNode.create(M.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addConstraint:AddConstraintNode.create(rr.toOperationNode())})})}addForeignKeyConstraint(e,M,tr,rr,ir=noop$1){const lr=ir(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(M.map(ColumnNode.create),parseTable(tr),rr.map(ColumnNode.create),e)));return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:lr})}addPrimaryKeyConstraint(e,M,tr=noop$1){const rr=tr(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(M,e)));return new AlterTableExecutor({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addConstraint:AddConstraintNode.create(rr.toOperationNode())})})}dropConstraint(e){return new AlterTableDropConstraintBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{dropConstraint:DropConstraintNode.create(e)})})}renameConstraint(e,M){return new AlterTableDropConstraintBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{renameConstraint:RenameConstraintNode.create(e,M)})})}addIndex(e){return new AlterTableAddIndexBuilder({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{addIndex:AddIndexNode.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:AlterTableNode.cloneWithTableProps(this.#e.node,{dropIndex:DropIndexNode.create(e)})})}$call(e){return e(this)}}class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,M){const tr=M(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,tr.toOperationNode())})}dropColumn(e){return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,DropColumnNode.create(e))})}renameColumn(e,M){return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,RenameColumnNode.create(e,M))})}addColumn(e,M,tr=noop$1){const rr=tr(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(e,parseDataTypeExpression(M))));return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,AddColumnNode.create(rr.toOperationNode()))})}modifyColumn(e,M,tr=noop$1){const rr=tr(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(e,parseDataTypeExpression(M))));return new AlterTableColumnAlteringBuilder({...this.#e,node:AlterTableNode.cloneWithColumnAlteration(this.#e.node,ModifyColumnNode.create(rr.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class ImmediateValueTransformer extends OperationNodeTransformer{transformPrimitiveValueList(e){return ValueListNode.create(e.values.map(ValueNode.createImmediate))}transformValue(e){return ValueNode.createImmediate(e.value)}}class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWithColumns(this.#e.node,[parseOrderedColumnName(e)])})}columns(e){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWithColumns(this.#e.node,e.map(parseOrderedColumnName))})}expression(e){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:CreateIndexNode.cloneWith(this.#e.node,{using:RawNode.createWithSql(e)})})}where(...e){const M=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:QueryNode.cloneWithWhere(this.#e.node,M.transformNode(parseValueBinaryOperationOrExpression(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:CreateSchemaNode.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function parseOnCommitAction(r){if(ON_COMMIT_ACTIONS.includes(r))return r;throw new Error(`invalid OnCommitAction ${r}`)}class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,M,tr=noop$1){const rr=tr(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(e,parseDataTypeExpression(M))));return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWithColumn(this.#e.node,rr.toOperationNode())})}addPrimaryKeyConstraint(e,M,tr=noop$1){const rr=tr(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(M,e)));return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWithConstraint(this.#e.node,rr.toOperationNode())})}addUniqueConstraint(e,M,tr=noop$1){const rr=tr(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(M,e)));return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWithConstraint(this.#e.node,rr.toOperationNode())})}addCheckConstraint(e,M,tr=noop$1){const rr=tr(new CheckConstraintBuilder(CheckConstraintNode.create(M.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWithConstraint(this.#e.node,rr.toOperationNode())})}addForeignKeyConstraint(e,M,tr,rr,ir=noop$1){const lr=ir(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(M.map(ColumnNode.create),parseTable(tr),rr.map(ColumnNode.create),e)));return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWithConstraint(this.#e.node,lr.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:CreateTableNode.cloneWith(this.#e.node,{selectQuery:parseExpression(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:DropIndexNode.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:DropIndexNode.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:DropIndexNode.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:DropSchemaNode.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:DropSchemaNode.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTableBuilder({...this.#e,node:DropTableNode.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:DropTableNode.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const CreateViewNode=freeze({is(r){return r.kind==="CreateViewNode"},create(r){return freeze({kind:"CreateViewNode",name:SchemableIdentifierNode.create(r)})},cloneWith(r,e){return freeze({...r,...e})}});class ImmediateValuePlugin{#e=new ImmediateValueTransformer;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}}class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:CreateViewNode.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:CreateViewNode.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:CreateViewNode.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:CreateViewNode.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:CreateViewNode.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){const M=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:CreateViewNode.cloneWith(this.#e.node,{as:M})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const DropViewNode=freeze({is(r){return r.kind==="DropViewNode"},create(r){return freeze({kind:"DropViewNode",name:SchemableIdentifierNode.create(r)})},cloneWith(r,e){return freeze({...r,...e})}});class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:DropViewNode.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:DropViewNode.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:DropViewNode.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const CreateTypeNode=freeze({is(r){return r.kind==="CreateTypeNode"},create(r){return freeze({kind:"CreateTypeNode",name:r})},cloneWithEnum(r,e){return freeze({...r,enum:ValueListNode.create(e.map(ValueNode.createImmediate))})}});class CreateTypeBuilder{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new CreateTypeBuilder({...this.#e,node:CreateTypeNode.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const DropTypeNode=freeze({is(r){return r.kind==="DropTypeNode"},create(r){return freeze({kind:"DropTypeNode",name:r})},cloneWith(r,e){return freeze({...r,...e})}});class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:DropTypeNode.cloneWith(this.#e.node,{ifExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function parseSchemableIdentifier(r){if(r.includes(".")){const M=r.split(".").map(trim);if(M.length===2)return SchemableIdentifierNode.createWithSchema(M[0],M[1]);throw new Error(`invalid schemable identifier ${r}`)}else return SchemableIdentifierNode.create(r)}function trim(r){return r.trim()}const RefreshMaterializedViewNode=freeze({is(r){return r.kind==="RefreshMaterializedViewNode"},create(r){return freeze({kind:"RefreshMaterializedViewNode",name:SchemableIdentifierNode.create(r)})},cloneWith(r,e){return freeze({...r,...e})}});class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:RefreshMaterializedViewNode.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:RefreshMaterializedViewNode.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:RefreshMaterializedViewNode.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new CreateTableBuilder({queryId:createQueryId(),executor:this.#e,node:CreateTableNode.create(parseTable(e))})}dropTable(e){return new DropTableBuilder({queryId:createQueryId(),executor:this.#e,node:DropTableNode.create(parseTable(e))})}createIndex(e){return new CreateIndexBuilder({queryId:createQueryId(),executor:this.#e,node:CreateIndexNode.create(e)})}dropIndex(e){return new DropIndexBuilder({queryId:createQueryId(),executor:this.#e,node:DropIndexNode.create(e)})}createSchema(e){return new CreateSchemaBuilder({queryId:createQueryId(),executor:this.#e,node:CreateSchemaNode.create(e)})}dropSchema(e){return new DropSchemaBuilder({queryId:createQueryId(),executor:this.#e,node:DropSchemaNode.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:AlterTableNode.create(parseTable(e))})}createView(e){return new CreateViewBuilder({queryId:createQueryId(),executor:this.#e,node:CreateViewNode.create(e)})}refreshMaterializedView(e){return new RefreshMaterializedViewBuilder({queryId:createQueryId(),executor:this.#e,node:RefreshMaterializedViewNode.create(e)})}dropView(e){return new DropViewBuilder({queryId:createQueryId(),executor:this.#e,node:DropViewNode.create(e)})}createType(e){return new CreateTypeBuilder({queryId:createQueryId(),executor:this.#e,node:CreateTypeNode.create(parseSchemableIdentifier(e))})}dropType(e){return new DropTypeBuilder({queryId:createQueryId(),executor:this.#e,node:DropTypeNode.create(parseSchemableIdentifier(e))})}withPlugin(e){return new SchemaModule(this.#e.withPlugin(e))}withoutPlugins(){return new SchemaModule(this.#e.withoutPlugins())}withSchema(e){return new SchemaModule(this.#e.withPluginAtFront(new WithSchemaPlugin(e)))}}class DynamicModule{ref(e){return new DynamicReferenceBuilder(e)}table(e){return new DynamicTableBuilder(e)}}class DefaultConnectionProvider{#e;constructor(e){this.#e=e}async provideConnection(e){const M=await this.#e.acquireConnection();try{return await e(M)}finally{await this.#e.releaseConnection(M)}}}class DefaultQueryExecutor extends QueryExecutorBase{#e;#t;#r;constructor(e,M,tr,rr=[]){super(rr),this.#e=e,this.#t=M,this.#r=tr}get adapter(){return this.#t}compileQuery(e,M){return this.#e.compileQuery(e,M)}provideConnection(e){return this.#r.provideConnection(e)}withPlugins(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#r,[...this.plugins,...e])}withPlugin(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#r,[...this.plugins,e])}withPluginAtFront(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#r,[e,...this.plugins])}withConnectionProvider(e){return new DefaultQueryExecutor(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new DefaultQueryExecutor(this.#e,this.#t,this.#r,[])}}function performanceNow(){return typeof performance<"u"&&isFunction(performance.now)?performance.now():Date.now()}class RuntimeDriver{#e;#t;#r;#s;#n;#a=new WeakSet;constructor(e,M){this.#s=!1,this.#e=e,this.#t=M}async init(){if(this.#n)throw new Error("driver has already been destroyed");this.#r||(this.#r=this.#e.init().then(()=>{this.#s=!0}).catch(e=>(this.#r=void 0,Promise.reject(e)))),await this.#r}async acquireConnection(){if(this.#n)throw new Error("driver has already been destroyed");this.#s||await this.init();const e=await this.#e.acquireConnection();return this.#a.has(e)||(this.#o()&&this.#i(e),this.#a.add(e)),e}async releaseConnection(e){await this.#e.releaseConnection(e)}beginTransaction(e,M){return this.#e.beginTransaction(e,M)}commitTransaction(e){return this.#e.commitTransaction(e)}rollbackTransaction(e){return this.#e.rollbackTransaction(e)}savepoint(e,M,tr){if(this.#e.savepoint)return this.#e.savepoint(e,M,tr);throw new Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(e,M,tr){if(this.#e.rollbackToSavepoint)return this.#e.rollbackToSavepoint(e,M,tr);throw new Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(e,M,tr){if(this.#e.releaseSavepoint)return this.#e.releaseSavepoint(e,M,tr);throw new Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){this.#r&&(await this.#r,this.#n||(this.#n=this.#e.destroy().catch(e=>(this.#n=void 0,Promise.reject(e)))),await this.#n)}#o(){return this.#t.isLevelEnabled("query")||this.#t.isLevelEnabled("error")}#i(e){const M=e.executeQuery,tr=e.streamQuery,rr=this;e.executeQuery=async ir=>{let lr;const dr=performanceNow();try{return await M.call(e,ir)}catch(hr){throw lr=hr,await rr.#l(hr,ir,dr),hr}finally{lr||await rr.#c(ir,dr)}},e.streamQuery=async function*(ir,lr){let dr;const hr=performanceNow();try{for await(const fr of tr.call(e,ir,lr))yield fr}catch(fr){throw dr=fr,await rr.#l(fr,ir,hr),fr}finally{dr||await rr.#c(ir,hr,!0)}}}async#l(e,M,tr){await this.#t.error(()=>({level:"error",error:e,query:M,queryDurationMillis:this.#d(tr)}))}async#c(e,M,tr=!1){await this.#t.query(()=>({level:"query",isStream:tr,query:e,queryDurationMillis:this.#d(M)}))}#d(e){return performanceNow()-e}}const ignoreError=()=>{};class SingleConnectionProvider{#e;#t;constructor(e){this.#e=e}async provideConnection(e){for(;this.#t;)await this.#t.catch(ignoreError);return this.#t=this.#r(e).finally(()=>{this.#t=void 0}),this.#t}async#r(e){return await e(this.#e)}}const TRANSACTION_ACCESS_MODES=["read only","read write"],TRANSACTION_ISOLATION_LEVELS=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function validateTransactionSettings(r){if(r.accessMode&&!TRANSACTION_ACCESS_MODES.includes(r.accessMode))throw new Error(`invalid transaction access mode ${r.accessMode}`);if(r.isolationLevel&&!TRANSACTION_ISOLATION_LEVELS.includes(r.isolationLevel))throw new Error(`invalid transaction isolation level ${r.isolationLevel}`)}const logLevels=["query","error"];freeze(logLevels);class Log{#e;#t;constructor(e){isFunction(e)?(this.#t=e,this.#e=freeze({query:!0,error:!0})):(this.#t=defaultLogger,this.#e=freeze({query:e.includes("query"),error:e.includes("error")}))}isLevelEnabled(e){return this.#e[e]}async query(e){this.#e.query&&await this.#t(e())}async error(e){this.#e.error&&await this.#t(e())}}function defaultLogger(r){if(r.level==="query"){const e=`kysely:query:${r.isStream?"stream:":""}`;console.log(`${e} ${r.query.sql}`),console.log(`${e} duration: ${r.queryDurationMillis.toFixed(1)}ms`)}else r.level==="error"&&(r.error instanceof Error?console.error(`kysely:error: ${r.error.stack??r.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:r.error,query:r.query.sql,queryDurationMillis:r.queryDurationMillis})}`))}function isCompilable(r){return isObject(r)&&isFunction(r.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class Kysely extends QueryCreator{#e;constructor(e){let M,tr;if(isKyselyProps(e))M={executor:e.executor},tr={...e};else{const rr=e.dialect,ir=rr.createDriver(),lr=rr.createQueryCompiler(),dr=rr.createAdapter(),hr=new Log(e.log??[]),fr=new RuntimeDriver(ir,hr),mr=new DefaultConnectionProvider(fr),_r=new DefaultQueryExecutor(lr,dr,mr,e.plugins??[]);M={executor:_r},tr={config:e,executor:_r,dialect:rr,driver:fr}}super(M),this.#e=freeze(tr)}get schema(){return new SchemaModule(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:CaseNode.create(isUndefined$1(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new TransactionBuilder({...this.#e})}startTransaction(){return new ControlledTransactionBuilder({...this.#e})}connection(){return new ConnectionBuilder({...this.#e})}withPlugin(e){return new Kysely({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Kysely({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Kysely({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new Kysely({...this.#e})}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}executeQuery(e,M){M!==void 0&&logOnce("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");const tr=isCompilable(e)?e.compile():e;return this.getExecutor().executeQuery(tr)}async[Symbol.asyncDispose](){await this.destroy()}}class Transaction extends Kysely{#e;constructor(e){super(e),this.#e=e}get isTransaction(){return!0}transaction(){throw new Error("calling the transaction method for a Transaction is not supported")}connection(){throw new Error("calling the connection method for a Transaction is not supported")}async destroy(){throw new Error("calling the destroy method for a Transaction is not supported")}withPlugin(e){return new Transaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Transaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Transaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new Transaction({...this.#e})}}function isKyselyProps(r){return isObject(r)&&isObject(r.config)&&isObject(r.driver)&&isObject(r.executor)&&isObject(r.dialect)}class ConnectionBuilder{#e;constructor(e){this.#e=freeze(e)}async execute(e){return this.#e.executor.provideConnection(async M=>{const tr=this.#e.executor.withConnectionProvider(new SingleConnectionProvider(M)),rr=new Kysely({...this.#e,executor:tr});return await e(rr)})}}class TransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new TransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new TransactionBuilder({...this.#e,isolationLevel:e})}async execute(e){const{isolationLevel:M,accessMode:tr,...rr}=this.#e,ir={isolationLevel:M,accessMode:tr};return validateTransactionSettings(ir),this.#e.executor.provideConnection(async lr=>{const dr={isCommitted:!1,isRolledBack:!1},hr=new NotCommittedOrRolledBackAssertingExecutor(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(lr)),dr),fr=new Transaction({...rr,executor:hr});let mr=!1;try{await this.#e.driver.beginTransaction(lr,ir),mr=!0;const _r=await e(fr);return await this.#e.driver.commitTransaction(lr),dr.isCommitted=!0,_r}catch(_r){throw mr&&(await this.#e.driver.rollbackTransaction(lr),dr.isRolledBack=!0),_r}})}}class ControlledTransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new ControlledTransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new ControlledTransactionBuilder({...this.#e,isolationLevel:e})}async execute(){const{isolationLevel:e,accessMode:M,...tr}=this.#e,rr={isolationLevel:e,accessMode:M};validateTransactionSettings(rr);const ir=await provideControlledConnection(this.#e.executor);return await this.#e.driver.beginTransaction(ir.connection,rr),new ControlledTransaction({...tr,connection:ir,executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(ir.connection))})}}class ControlledTransaction extends Transaction{#e;#t;#r;constructor(e){const M={isCommitted:!1,isRolledBack:!1};e={...e,executor:new NotCommittedOrRolledBackAssertingExecutor(e.executor,M)};const{connection:tr,...rr}=e;super(rr),this.#e=freeze(e),this.#r=M;const ir=createQueryId();this.#t=lr=>e.executor.compileQuery(lr,ir)}get isCommitted(){return this.#r.isCommitted}get isRolledBack(){return this.#r.isRolledBack}commit(){return assertNotCommittedOrRolledBack(this.#r),new Command(async()=>{await this.#e.driver.commitTransaction(this.#e.connection.connection),this.#r.isCommitted=!0,this.#e.connection.release()})}rollback(){return assertNotCommittedOrRolledBack(this.#r),new Command(async()=>{await this.#e.driver.rollbackTransaction(this.#e.connection.connection),this.#r.isRolledBack=!0,this.#e.connection.release()})}savepoint(e){return assertNotCommittedOrRolledBack(this.#r),new Command(async()=>(await this.#e.driver.savepoint?.(this.#e.connection.connection,e,this.#t),new ControlledTransaction({...this.#e})))}rollbackToSavepoint(e){return assertNotCommittedOrRolledBack(this.#r),new Command(async()=>(await this.#e.driver.rollbackToSavepoint?.(this.#e.connection.connection,e,this.#t),new ControlledTransaction({...this.#e})))}releaseSavepoint(e){return assertNotCommittedOrRolledBack(this.#r),new Command(async()=>(await this.#e.driver.releaseSavepoint?.(this.#e.connection.connection,e,this.#t),new ControlledTransaction({...this.#e})))}withPlugin(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new ControlledTransaction({...this.#e})}}class Command{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}}function assertNotCommittedOrRolledBack(r){if(r.isCommitted)throw new Error("Transaction is already committed");if(r.isRolledBack)throw new Error("Transaction is already rolled back")}class NotCommittedOrRolledBackAssertingExecutor{#e;#t;constructor(e,M){e instanceof NotCommittedOrRolledBackAssertingExecutor?this.#e=e.#e:this.#e=e,this.#t=M}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,M){return this.#e.transformQuery(e,M)}compileQuery(e,M){return this.#e.compileQuery(e,M)}provideConnection(e){return this.#e.provideConnection(e)}executeQuery(e){return assertNotCommittedOrRolledBack(this.#t),this.#e.executeQuery(e)}stream(e,M){return assertNotCommittedOrRolledBack(this.#t),this.#e.stream(e,M)}withConnectionProvider(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withoutPlugins(),this.#t)}}class RawBuilderImpl{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new AliasedRawBuilderImpl(this,e)}$castTo(){return new RawBuilderImpl({...this.#e})}$notNull(){return new RawBuilderImpl(this.#e)}withPlugin(e){return new RawBuilderImpl({...this.#e,plugins:this.#e.plugins!==void 0?freeze([...this.#e.plugins,e]):freeze([e])})}toOperationNode(){return this.#r(this.#t())}compile(e){return this.#s(this.#t(e))}async execute(e){const M=this.#t(e);return M.executeQuery(this.#s(M))}#t(e){const M=e!==void 0?e.getExecutor():NOOP_QUERY_EXECUTOR;return this.#e.plugins!==void 0?M.withPlugins(this.#e.plugins):M}#r(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#s(e){return e.compileQuery(this.#r(e),this.#e.queryId)}}function createRawBuilder(r){return new RawBuilderImpl(r)}class AliasedRawBuilderImpl{#e;#t;constructor(e,M){this.#e=e,this.#t=M}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return AliasNode.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():IdentifierNode.create(this.#t))}}const sql=Object.assign((r,...e)=>createRawBuilder({queryId:createQueryId(),rawNode:RawNode.create(r,e?.map(parseParameter)??[])}),{ref(r){return createRawBuilder({queryId:createQueryId(),rawNode:RawNode.createWithChild(parseStringReference(r))})},val(r){return createRawBuilder({queryId:createQueryId(),rawNode:RawNode.createWithChild(parseValueExpression(r))})},value(r){return this.val(r)},table(r){return createRawBuilder({queryId:createQueryId(),rawNode:RawNode.createWithChild(parseTable(r))})},id(...r){const e=new Array(r.length+1).fill(".");return e[0]="",e[e.length-1]="",createRawBuilder({queryId:createQueryId(),rawNode:RawNode.create(e,r.map(IdentifierNode.create))})},lit(r){return createRawBuilder({queryId:createQueryId(),rawNode:RawNode.createWithChild(ValueNode.createImmediate(r))})},literal(r){return this.lit(r)},raw(r){return createRawBuilder({queryId:createQueryId(),rawNode:RawNode.createWithSql(r)})},join(r,e=sql`, `){const M=new Array(Math.max(2*r.length-1,0)),tr=e.toOperationNode();for(let rr=0;rr<r.length;++rr)M[2*rr]=parseParameter(r[rr]),rr!==r.length-1&&(M[2*rr+1]=tr);return createRawBuilder({queryId:createQueryId(),rawNode:RawNode.createWithChildren(M)})}});function parseParameter(r){return isOperationNodeSource(r)?r.toOperationNode():parseValueExpression(r)}class OperationNodeVisitor{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=freeze({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}}const LIT_WRAP_REGEX=/'/g;class DefaultQueryCompiler extends OperationNodeVisitor{#e="";#t=[];get numParameters(){return this.#t.length}compileQuery(e,M){return this.#e="",this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),freeze({query:e,queryId:M,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){const M=this.parentNode!==void 0&&!ParensNode.is(this.parentNode)&&!InsertQueryNode.is(this.parentNode)&&!CreateTableNode.is(this.parentNode)&&!CreateViewNode.is(this.parentNode)&&!SetOperationNode.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),M&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append("select"),e.distinctOn&&(this.append(" "),this.compileDistinctOn(e.distinctOn)),e.frontModifiers?.length&&(this.append(" "),this.compileList(e.frontModifiers," ")),e.top&&(this.append(" "),this.visitNode(e.top)),e.selections&&(this.append(" "),this.compileList(e.selections)),e.from&&(this.append(" "),this.visitNode(e.from)),e.joins&&(this.append(" "),this.compileList(e.joins," ")),e.where&&(this.append(" "),this.visitNode(e.where)),e.groupBy&&(this.append(" "),this.visitNode(e.groupBy)),e.having&&(this.append(" "),this.visitNode(e.having)),e.setOperations&&(this.append(" "),this.compileList(e.setOperations," ")),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),e.limit&&(this.append(" "),this.visitNode(e.limit)),e.offset&&(this.append(" "),this.visitNode(e.offset)),e.fetch&&(this.append(" "),this.visitNode(e.fetch)),e.endModifiers?.length&&(this.append(" "),this.compileList(this.sortSelectModifiers([...e.endModifiers])," ")),M&&this.append(")")}visitFrom(e){this.append("from "),this.compileList(e.froms)}visitSelection(e){this.visitNode(e.selection)}visitColumn(e){this.visitNode(e.column)}compileDistinctOn(e){this.append("distinct on ("),this.compileList(e),this.append(")")}compileList(e,M=", "){const tr=e.length-1;for(let rr=0;rr<=tr;rr++)this.visitNode(e[rr]),rr<tr&&this.append(M)}visitWhere(e){this.append("where "),this.visitNode(e.where)}visitHaving(e){this.append("having "),this.visitNode(e.having)}visitInsertQuery(e){const M=this.parentNode!==void 0&&!ParensNode.is(this.parentNode)&&!RawNode.is(this.parentNode)&&!WhenNode.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),M&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append(e.replace?"replace":"insert"),e.ignore&&(logOnce("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore")),e.orAction&&(this.append(" "),this.visitNode(e.orAction)),e.top&&(this.append(" "),this.visitNode(e.top)),e.into&&(this.append(" into "),this.visitNode(e.into)),e.columns&&(this.append(" ("),this.compileList(e.columns),this.append(")")),e.output&&(this.append(" "),this.visitNode(e.output)),e.values&&(this.append(" "),this.visitNode(e.values)),e.defaultValues&&(this.append(" "),this.append("default values")),e.onConflict&&(this.append(" "),this.visitNode(e.onConflict)),e.onDuplicateKey&&(this.append(" "),this.visitNode(e.onDuplicateKey)),e.returning&&(this.append(" "),this.visitNode(e.returning)),M&&this.append(")"),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitValues(e){this.append("values "),this.compileList(e.values)}visitDeleteQuery(e){const M=this.parentNode!==void 0&&!ParensNode.is(this.parentNode)&&!RawNode.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),M&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append("delete "),e.top&&(this.visitNode(e.top),this.append(" ")),this.visitNode(e.from),e.output&&(this.append(" "),this.visitNode(e.output)),e.using&&(this.append(" "),this.visitNode(e.using)),e.joins&&(this.append(" "),this.compileList(e.joins," ")),e.where&&(this.append(" "),this.visitNode(e.where)),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),e.limit&&(this.append(" "),this.visitNode(e.limit)),e.returning&&(this.append(" "),this.visitNode(e.returning)),M&&this.append(")"),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitReturning(e){this.append("returning "),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(" as "),this.visitNode(e.alias)}visitReference(e){e.table&&(this.visitNode(e.table),this.append(".")),this.visitNode(e.column)}visitSelectAll(e){this.append("*")}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!isString$1(e.name))throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(" and "),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(" or "),this.visitNode(e.right)}visitValue(e){e.immediate?this.appendImmediateValue(e.value):this.appendValue(e.value)}visitValueList(e){this.append("("),this.compileList(e.values),this.append(")")}visitTuple(e){this.append("("),this.compileList(e.values),this.append(")")}visitPrimitiveValueList(e){this.append("(");const{values:M}=e;for(let tr=0;tr<M.length;++tr)this.appendValue(M[tr]),tr!==M.length-1&&this.append(", ");this.append(")")}visitParens(e){this.append("("),this.visitNode(e.node),this.append(")")}visitJoin(e){this.append(JOIN_TYPE_SQL[e.joinType]),this.append(" "),this.visitNode(e.table),e.on&&(this.append(" "),this.visitNode(e.on))}visitOn(e){this.append("on "),this.visitNode(e.on)}visitRaw(e){const{sqlFragments:M,parameters:tr}=e;for(let rr=0;rr<M.length;++rr)this.append(M[rr]),tr.length>rr&&this.visitNode(tr[rr])}visitOperator(e){this.append(e.operator)}visitTable(e){this.visitNode(e.table)}visitSchemableIdentifier(e){e.schema&&(this.visitNode(e.schema),this.append(".")),this.visitNode(e.identifier)}visitCreateTable(e){this.append("create "),e.frontModifiers&&e.frontModifiers.length>0&&(this.compileList(e.frontModifiers," "),this.append(" ")),e.temporary&&this.append("temporary "),this.append("table "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.table),e.selectQuery?(this.append(" as "),this.visitNode(e.selectQuery)):(this.append(" ("),this.compileList([...e.columns,...e.constraints??[]]),this.append(")"),e.onCommit&&(this.append(" on commit "),this.append(e.onCommit)),e.endModifiers&&e.endModifiers.length>0&&(this.append(" "),this.compileList(e.endModifiers," ")))}visitColumnDefinition(e){e.ifNotExists&&this.append("if not exists "),this.visitNode(e.column),this.append(" "),this.visitNode(e.dataType),e.unsigned&&this.append(" unsigned"),e.frontModifiers&&e.frontModifiers.length>0&&(this.append(" "),this.compileList(e.frontModifiers," ")),e.generated&&(this.append(" "),this.visitNode(e.generated)),e.identity&&this.append(" identity"),e.defaultTo&&(this.append(" "),this.visitNode(e.defaultTo)),e.notNull&&this.append(" not null"),e.unique&&this.append(" unique"),e.nullsNotDistinct&&this.append(" nulls not distinct"),e.primaryKey&&this.append(" primary key"),e.autoIncrement&&(this.append(" "),this.append(this.getAutoIncrement())),e.references&&(this.append(" "),this.visitNode(e.references)),e.check&&(this.append(" "),this.visitNode(e.check)),e.endModifiers&&e.endModifiers.length>0&&(this.append(" "),this.compileList(e.endModifiers," "))}getAutoIncrement(){return"auto_increment"}visitReferences(e){this.append("references "),this.visitNode(e.table),this.append(" ("),this.compileList(e.columns),this.append(")"),e.onDelete&&(this.append(" on delete "),this.append(e.onDelete)),e.onUpdate&&(this.append(" on update "),this.append(e.onUpdate))}visitDropTable(e){this.append("drop table "),e.ifExists&&this.append("if exists "),this.visitNode(e.table),e.cascade&&this.append(" cascade")}visitDataType(e){this.append(e.dataType)}visitOrderBy(e){this.append("order by "),this.compileList(e.items)}visitOrderByItem(e){this.visitNode(e.orderBy),e.collation&&(this.append(" "),this.visitNode(e.collation)),e.direction&&(this.append(" "),this.visitNode(e.direction)),e.nulls&&(this.append(" nulls "),this.append(e.nulls))}visitGroupBy(e){this.append("group by "),this.compileList(e.items)}visitGroupByItem(e){this.visitNode(e.groupBy)}visitUpdateQuery(e){const M=this.parentNode!==void 0&&!ParensNode.is(this.parentNode)&&!RawNode.is(this.parentNode)&&!WhenNode.is(this.parentNode);if(this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),M&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append("update "),e.top&&(this.visitNode(e.top),this.append(" ")),e.table&&(this.visitNode(e.table),this.append(" ")),this.append("set "),e.updates&&this.compileList(e.updates),e.output&&(this.append(" "),this.visitNode(e.output)),e.from&&(this.append(" "),this.visitNode(e.from)),e.joins){if(!e.from)throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(e.joins," ")}e.where&&(this.append(" "),this.visitNode(e.where)),e.returning&&(this.append(" "),this.visitNode(e.returning)),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),e.limit&&(this.append(" "),this.visitNode(e.limit)),M&&this.append(")"),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitColumnUpdate(e){this.visitNode(e.column),this.append(" = "),this.visitNode(e.value)}visitLimit(e){this.append("limit "),this.visitNode(e.limit)}visitOffset(e){this.append("offset "),this.visitNode(e.offset)}visitOnConflict(e){this.append("on conflict"),e.columns?(this.append(" ("),this.compileList(e.columns),this.append(")")):e.constraint?(this.append(" on constraint "),this.visitNode(e.constraint)):e.indexExpression&&(this.append(" ("),this.visitNode(e.indexExpression),this.append(")")),e.indexWhere&&(this.append(" "),this.visitNode(e.indexWhere)),e.doNothing===!0?this.append(" do nothing"):e.updates&&(this.append(" do update set "),this.compileList(e.updates),e.updateWhere&&(this.append(" "),this.visitNode(e.updateWhere)))}visitOnDuplicateKey(e){this.append("on duplicate key update "),this.compileList(e.updates)}visitCreateIndex(e){this.append("create "),e.unique&&this.append("unique "),this.append("index "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.name),e.table&&(this.append(" on "),this.visitNode(e.table)),e.using&&(this.append(" using "),this.visitNode(e.using)),e.columns&&(this.append(" ("),this.compileList(e.columns),this.append(")")),e.nullsNotDistinct&&this.append(" nulls not distinct"),e.where&&(this.append(" "),this.visitNode(e.where))}visitDropIndex(e){this.append("drop index "),e.ifExists&&this.append("if exists "),this.visitNode(e.name),e.table&&(this.append(" on "),this.visitNode(e.table)),e.cascade&&this.append(" cascade")}visitCreateSchema(e){this.append("create schema "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.schema)}visitDropSchema(e){this.append("drop schema "),e.ifExists&&this.append("if exists "),this.visitNode(e.schema),e.cascade&&this.append(" cascade")}visitPrimaryKeyConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("primary key ("),this.compileList(e.columns),this.append(")"),this.buildDeferrable(e)}buildDeferrable(e){e.deferrable!==void 0&&(e.deferrable?this.append(" deferrable"):this.append(" not deferrable")),e.initiallyDeferred!==void 0&&(e.initiallyDeferred?this.append(" initially deferred"):this.append(" initially immediate"))}visitUniqueConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("unique"),e.nullsNotDistinct&&this.append(" nulls not distinct"),this.append(" ("),this.compileList(e.columns),this.append(")"),this.buildDeferrable(e)}visitCheckConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("check ("),this.visitNode(e.expression),this.append(")")}visitForeignKeyConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("foreign key ("),this.compileList(e.columns),this.append(") "),this.visitNode(e.references),e.onDelete&&(this.append(" on delete "),this.append(e.onDelete)),e.onUpdate&&(this.append(" on update "),this.append(e.onUpdate)),this.buildDeferrable(e)}visitList(e){this.compileList(e.items)}visitWith(e){this.append("with "),e.recursive&&this.append("recursive "),this.compileList(e.expressions)}visitCommonTableExpression(e){this.visitNode(e.name),this.append(" as "),isBoolean(e.materialized)&&(e.materialized||this.append("not "),this.append("materialized ")),this.visitNode(e.expression)}visitCommonTableExpressionName(e){this.visitNode(e.table),e.columns&&(this.append("("),this.compileList(e.columns),this.append(")"))}visitAlterTable(e){this.append("alter table "),this.visitNode(e.table),this.append(" "),e.renameTo&&(this.append("rename to "),this.visitNode(e.renameTo)),e.setSchema&&(this.append("set schema "),this.visitNode(e.setSchema)),e.addConstraint&&this.visitNode(e.addConstraint),e.dropConstraint&&this.visitNode(e.dropConstraint),e.renameConstraint&&this.visitNode(e.renameConstraint),e.columnAlterations&&this.compileColumnAlterations(e.columnAlterations),e.addIndex&&this.visitNode(e.addIndex),e.dropIndex&&this.visitNode(e.dropIndex)}visitAddColumn(e){this.append("add column "),this.visitNode(e.column)}visitRenameColumn(e){this.append("rename column "),this.visitNode(e.column),this.append(" to "),this.visitNode(e.renameTo)}visitDropColumn(e){this.append("drop column "),this.visitNode(e.column)}visitAlterColumn(e){this.append("alter column "),this.visitNode(e.column),this.append(" "),e.dataType&&(this.announcesNewColumnDataType()&&this.append("type "),this.visitNode(e.dataType),e.dataTypeExpression&&(this.append("using "),this.visitNode(e.dataTypeExpression))),e.setDefault&&(this.append("set default "),this.visitNode(e.setDefault)),e.dropDefault&&this.append("drop default"),e.setNotNull&&this.append("set not null"),e.dropNotNull&&this.append("drop not null")}visitModifyColumn(e){this.append("modify column "),this.visitNode(e.column)}visitAddConstraint(e){this.append("add "),this.visitNode(e.constraint)}visitDropConstraint(e){this.append("drop constraint "),e.ifExists&&this.append("if exists "),this.visitNode(e.constraintName),e.modifier==="cascade"?this.append(" cascade"):e.modifier==="restrict"&&this.append(" restrict")}visitRenameConstraint(e){this.append("rename constraint "),this.visitNode(e.oldName),this.append(" to "),this.visitNode(e.newName)}visitSetOperation(e){this.append(e.operator),this.append(" "),e.all&&this.append("all "),this.visitNode(e.expression)}visitCreateView(e){this.append("create "),e.orReplace&&this.append("or replace "),e.materialized&&this.append("materialized "),e.temporary&&this.append("temporary "),this.append("view "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.name),this.append(" "),e.columns&&(this.append("("),this.compileList(e.columns),this.append(") ")),e.as&&(this.append("as "),this.visitNode(e.as))}visitRefreshMaterializedView(e){this.append("refresh materialized view "),e.concurrently&&this.append("concurrently "),this.visitNode(e.name),e.withNoData?this.append(" with no data"):this.append(" with data")}visitDropView(e){this.append("drop "),e.materialized&&this.append("materialized "),this.append("view "),e.ifExists&&this.append("if exists "),this.visitNode(e.name),e.cascade&&this.append(" cascade")}visitGenerated(e){this.append("generated "),e.always&&this.append("always "),e.byDefault&&this.append("by default "),this.append("as "),e.identity&&this.append("identity"),e.expression&&(this.append("("),this.visitNode(e.expression),this.append(")")),e.stored&&this.append(" stored")}visitDefaultValue(e){this.append("default "),this.visitNode(e.defaultValue)}visitSelectModifier(e){e.rawModifier?this.visitNode(e.rawModifier):this.append(SELECT_MODIFIER_SQL[e.modifier]),e.of&&(this.append(" of "),this.compileList(e.of,", "))}visitCreateType(e){this.append("create type "),this.visitNode(e.name),e.enum&&(this.append(" as enum "),this.visitNode(e.enum))}visitDropType(e){this.append("drop type "),e.ifExists&&this.append("if exists "),this.visitNode(e.name)}visitExplain(e){this.append("explain"),(e.options||e.format)&&(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),e.options&&(this.visitNode(e.options),e.format&&this.append(this.getExplainOptionsDelimiter())),e.format&&(this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(e.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(e){this.append("default")}visitAggregateFunction(e){this.append(e.func),this.append("("),e.distinct&&this.append("distinct "),this.compileList(e.aggregated),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),this.append(")"),e.withinGroup&&(this.append(" within group ("),this.visitNode(e.withinGroup),this.append(")")),e.filter&&(this.append(" filter("),this.visitNode(e.filter),this.append(")")),e.over&&(this.append(" "),this.visitNode(e.over))}visitOver(e){this.append("over("),e.partitionBy&&(this.visitNode(e.partitionBy),e.orderBy&&this.append(" ")),e.orderBy&&this.visitNode(e.orderBy),this.append(")")}visitPartitionBy(e){this.append("partition by "),this.compileList(e.items)}visitPartitionByItem(e){this.visitNode(e.partitionBy)}visitBinaryOperation(e){this.visitNode(e.leftOperand),this.append(" "),this.visitNode(e.operator),this.append(" "),this.visitNode(e.rightOperand)}visitUnaryOperation(e){this.visitNode(e.operator),this.isMinusOperator(e.operator)||this.append(" "),this.visitNode(e.operand)}isMinusOperator(e){return OperatorNode.is(e)&&e.operator==="-"}visitUsing(e){this.append("using "),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append("("),this.compileList(e.arguments),this.append(")")}visitCase(e){this.append("case"),e.value&&(this.append(" "),this.visitNode(e.value)),e.when&&(this.append(" "),this.compileList(e.when," ")),e.else&&(this.append(" else "),this.visitNode(e.else)),this.append(" end"),e.isStatement&&this.append(" case")}visitWhen(e){this.append("when "),this.visitNode(e.condition),e.result&&(this.append(" then "),this.visitNode(e.result))}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){e.inOperator&&this.visitNode(e.inOperator),this.append("'$");for(const M of e.pathLegs)this.visitNode(M);this.append("'")}visitJSONPathLeg(e){const M=e.type==="ArrayLocation";this.append(M?"[":"."),this.append(String(e.value)),M&&this.append("]")}visitJSONOperatorChain(e){for(let M=0,tr=e.values.length;M<tr;M++)M===tr-1?this.visitNode(e.operator):this.append("->"),this.visitNode(e.values[M])}visitMergeQuery(e){e.with&&(this.visitNode(e.with),this.append(" ")),this.append("merge "),e.top&&(this.visitNode(e.top),this.append(" ")),this.append("into "),this.visitNode(e.into),e.using&&(this.append(" "),this.visitNode(e.using)),e.whens&&(this.append(" "),this.compileList(e.whens," ")),e.returning&&(this.append(" "),this.visitNode(e.returning)),e.output&&(this.append(" "),this.visitNode(e.output)),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitMatched(e){e.not&&this.append("not "),this.append("matched"),e.bySource&&this.append(" by source")}visitAddIndex(e){this.append("add "),e.unique&&this.append("unique "),this.append("index "),this.visitNode(e.name),e.columns&&(this.append(" ("),this.compileList(e.columns),this.append(")")),e.using&&(this.append(" using "),this.visitNode(e.using))}visitCast(e){this.append("cast("),this.visitNode(e.expression),this.append(" as "),this.visitNode(e.dataType),this.append(")")}visitFetch(e){this.append("fetch next "),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append("output "),this.compileList(e.selections)}visitTop(e){this.append(`top(${e.expression})`),e.modifiers&&this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append("collate "),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(e){const M=this.getLeftIdentifierWrapper(),tr=this.getRightIdentifierWrapper();let rr="";for(const ir of e)rr+=ir,ir===M?rr+=M:ir===tr&&(rr+=tr);return rr}sanitizeStringLiteral(e){return e.replace(LIT_WRAP_REGEX,"''")}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(isString$1(e))this.appendStringLiteral(e);else if(isNumber$1(e)||isBoolean(e)||isBigInt(e))this.append(e.toString());else if(isNull(e))this.append("null");else if(isDate$1(e))this.appendImmediateValue(e.toISOString());else throw new Error(`invalid immediate value ${e}`)}appendStringLiteral(e){this.append("'"),this.append(this.sanitizeStringLiteral(e)),this.append("'")}sortSelectModifiers(e){return e.sort((M,tr)=>M.modifier&&tr.modifier?SELECT_MODIFIER_PRIORITY[M.modifier]-SELECT_MODIFIER_PRIORITY[tr.modifier]:1),freeze(e)}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}}const SELECT_MODIFIER_SQL=freeze({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),SELECT_MODIFIER_PRIORITY=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),JOIN_TYPE_SQL=freeze({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"}),CompiledQuery=freeze({raw(r,e=[]){return freeze({sql:r,query:RawNode.createWithSql(r),parameters:freeze(e),queryId:createQueryId()})}});class DialectAdapterBase{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class NoopPlugin{transformQuery(e){return e.node}async transformResult(e){return e.result}}const DEFAULT_MIGRATION_TABLE="kysely_migration",DEFAULT_MIGRATION_LOCK_TABLE="kysely_migration_lock",DEFAULT_ALLOW_UNORDERED_MIGRATIONS=!1,MIGRATION_LOCK_ID="migration_lock";freeze({__noMigrations__:!0});class Migrator{#e;constructor(e){this.#e=freeze(e)}async getMigrations(){const M=await this.#u(this.#s)?await this.#e.db.withPlugin(this.#o).selectFrom(this.#s).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#_()).map(({name:rr,...ir})=>{const lr=M.find(dr=>dr.name===rr);return{name:rr,migration:ir,executedAt:lr?new Date(lr.timestamp):void 0}})}async migrateToLatest(){return this.#t(()=>({direction:"Up",step:1/0}))}async migrateTo(e){return this.#t(({migrations:M,executedMigrations:tr,pendingMigrations:rr})=>{if(isObject(e)&&e.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!M.find(dr=>dr.name===e))throw new Error(`migration "${e}" doesn't exist`);const ir=tr.indexOf(e),lr=rr.findIndex(dr=>dr.name===e);if(ir!==-1)return{direction:"Down",step:tr.length-ir-1};if(lr!==-1)return{direction:"Up",step:lr+1};throw new Error(`migration "${e}" isn't executed or pending`)})}async migrateUp(){return this.#t(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#t(()=>({direction:"Down",step:1}))}async#t(e){try{return await this.#i(),await this.#l(),await this.#c(),await this.#d(),await this.#m(e)}catch(M){return M instanceof MigrationResultSetError?M.resultSet:{error:M}}}get#r(){return this.#e.migrationTableSchema}get#s(){return this.#e.migrationTableName??DEFAULT_MIGRATION_TABLE}get#n(){return this.#e.migrationLockTableName??DEFAULT_MIGRATION_LOCK_TABLE}get#a(){return this.#e.allowUnorderedMigrations??DEFAULT_ALLOW_UNORDERED_MIGRATIONS}get#o(){return this.#r?new WithSchemaPlugin(this.#r):new NoopPlugin}async#i(){if(!(!this.#r||await this.#p()))try{await this.#g(this.#e.db.schema.createSchema(this.#r))}catch(M){if(!await this.#p())throw M}}async#l(){if(!await this.#u(this.#s))try{await this.#g(this.#e.db.schema.withPlugin(this.#o).createTable(this.#s).addColumn("name","varchar(255)",M=>M.notNull().primaryKey()).addColumn("timestamp","varchar(255)",M=>M.notNull()))}catch(M){if(!await this.#u(this.#s))throw M}}async#c(){if(!await this.#u(this.#n))try{await this.#g(this.#e.db.schema.withPlugin(this.#o).createTable(this.#n).addColumn("id","varchar(255)",M=>M.notNull().primaryKey()).addColumn("is_locked","integer",M=>M.notNull().defaultTo(0)))}catch(M){if(!await this.#u(this.#n))throw M}}async#d(){if(!await this.#h())try{await this.#e.db.withPlugin(this.#o).insertInto(this.#n).values({id:MIGRATION_LOCK_ID,is_locked:0}).execute()}catch(M){if(!await this.#h())throw M}}async#p(){return(await this.#e.db.introspection.getSchemas()).some(M=>M.name===this.#r)}async#u(e){const M=this.#r;return(await this.#e.db.introspection.getTables({withInternalKyselyTables:!0})).some(rr=>rr.name===e&&(!M||rr.schema===M))}async#h(){return!!await this.#e.db.withPlugin(this.#o).selectFrom(this.#n).where("id","=",MIGRATION_LOCK_ID).select("id").executeTakeFirst()}async#m(e){const M=this.#e.db.getExecutor().adapter,tr=freeze({lockTable:this.#e.migrationLockTableName??DEFAULT_MIGRATION_LOCK_TABLE,lockRowId:MIGRATION_LOCK_ID,lockTableSchema:this.#e.migrationTableSchema}),rr=async ir=>{try{await M.acquireMigrationLock(ir,tr);const lr=await this.#f(ir);if(lr.migrations.length===0)return{results:[]};const{direction:dr,step:hr}=e(lr);return hr<=0?{results:[]}:dr==="Down"?await this.#x(ir,lr,hr):dr==="Up"?await this.#S(ir,lr,hr):{results:[]}}finally{await M.releaseMigrationLock(ir,tr)}};return M.supportsTransactionalDdl&&!this.#e.disableTransactions?this.#e.db.transaction().execute(rr):this.#e.db.connection().execute(rr)}async#f(e){const M=await this.#_(),tr=await this.#w(e);this.#b(M,tr),this.#a||this.#E(M,tr);const rr=this.#y(M,tr);return freeze({migrations:M,executedMigrations:tr,lastMigration:getLast(tr),pendingMigrations:rr})}#y(e,M){return e.filter(tr=>!M.includes(tr.name))}async#_(){const e=await this.#e.provider.getMigrations();return Object.keys(e).sort().map(M=>({...e[M],name:M}))}async#w(e){const M=await e.withPlugin(this.#o).selectFrom(this.#s).select(["name","timestamp"]).$narrowType().execute(),tr=this.#e.nameComparator||((rr,ir)=>rr.localeCompare(ir));return M.sort((rr,ir)=>rr.timestamp===ir.timestamp?tr(rr.name,ir.name):new Date(rr.timestamp).getTime()-new Date(ir.timestamp).getTime()).map(rr=>rr.name)}#b(e,M){for(const tr of M)if(!e.some(rr=>rr.name===tr))throw new Error(`corrupted migrations: previously executed migration ${tr} is missing`)}#E(e,M){for(let tr=0;tr<M.length;++tr)if(e[tr].name!==M[tr])throw new Error(`corrupted migrations: expected previously executed migration ${M[tr]} to be at index ${tr} but ${e[tr].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#x(e,M,tr){const rr=M.executedMigrations.slice().reverse().slice(0,tr).map(lr=>M.migrations.find(dr=>dr.name===lr)),ir=rr.map(lr=>({migrationName:lr.name,direction:"Down",status:"NotExecuted"}));for(let lr=0;lr<ir.length;++lr){const dr=rr[lr];try{dr.down&&(await dr.down(e),await e.withPlugin(this.#o).deleteFrom(this.#s).where("name","=",dr.name).execute(),ir[lr]={migrationName:dr.name,direction:"Down",status:"Success"})}catch(hr){throw ir[lr]={migrationName:dr.name,direction:"Down",status:"Error"},new MigrationResultSetError({error:hr,results:ir})}}return{results:ir}}async#S(e,M,tr){const ir=M.pendingMigrations.slice(0,tr).map(lr=>({migrationName:lr.name,direction:"Up",status:"NotExecuted"}));for(let lr=0;lr<ir.length;lr++){const dr=M.pendingMigrations[lr];try{await dr.up(e),await e.withPlugin(this.#o).insertInto(this.#s).values({name:dr.name,timestamp:new Date().toISOString()}).execute(),ir[lr]={migrationName:dr.name,direction:"Up",status:"Success"}}catch(hr){throw ir[lr]={migrationName:dr.name,direction:"Up",status:"Error"},new MigrationResultSetError({error:hr,results:ir})}}return{results:ir}}async#g(e){this.#e.db.getExecutor().adapter.supportsCreateIfNotExists&&(e=e.ifNotExists()),await e.execute()}}class MigrationResultSetError extends Error{#e;constructor(e){super(),this.#e=e}get resultSet(){return this.#e}}const ID_WRAP_REGEX=/"/g;class PostgresQueryCompiler extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(ID_WRAP_REGEX,'""')}}class PostgresIntrospector{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(M=>({name:M.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let M=this.#e.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",sql`col_description(a.attrelid, a.attnum)`.as("column_description"),sql`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(sql`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();e.withInternalKyselyTables||(M=M.where("c.relname","!=",DEFAULT_MIGRATION_TABLE).where("c.relname","!=",DEFAULT_MIGRATION_LOCK_TABLE));const tr=await M.execute();return this.#t(tr)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){return e.reduce((M,tr)=>{let rr=M.find(ir=>ir.name===tr.table&&ir.schema===tr.schema);return rr||(rr=freeze({name:tr.table,isView:tr.table_type==="v",schema:tr.schema,columns:[]}),M.push(rr)),rr.columns.push(freeze({name:tr.column,dataType:tr.type,dataTypeSchema:tr.type_schema,isNullable:!tr.not_null,isAutoIncrementing:tr.auto_incrementing!==null,hasDefaultValue:tr.has_default,comment:tr.column_description??void 0})),M},[])}}const LOCK_ID=BigInt("3853314791062309107");class PostgresAdapter extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,M){await sql`select pg_advisory_xact_lock(${sql.lit(LOCK_ID)})`.execute(e)}async releaseMigrationLock(e,M){}}var PGliteConnection=class{client;constructor(r){this.client=r}async executeQuery(r){const e=await this.client.query(r.sql,[...r.parameters]);return e.affectedRows?{numAffectedRows:BigInt(e.affectedRows),rows:e.rows}:{rows:e.rows}}async*streamQuery(r,e){if(!Number.isInteger(e)||e<=0)throw new Error("chunkSize must be a positive integer");const M=await this.client.query(r.sql,[...r.parameters]);for(let tr=0;tr<M.rows.length;tr=tr+e)yield{rows:M.rows.slice(tr,tr+e)}}},PGliteDialect=class{constructor(r){this.pgLite=r}createAdapter(){return new PostgresAdapter}createDriver(){return new PGliteDriver(this.pgLite)}createQueryCompiler(){return new PostgresQueryCompiler}createIntrospector(r){return new PostgresIntrospector(r)}},PGliteDriver=class{client;connection;queue=[];constructor(r){this.client=r}async init(){}async acquireConnection(){if(this.client===void 0)throw new Error("PGLite not initialized");return this.connection!==void 0?new Promise(r=>{this.queue.push(r)}):(this.connection=new PGliteConnection(this.client),this.connection)}async releaseConnection(r){if(r!==this.connection)throw new Error("Invalid connection");const M=this.queue.splice(0,1)[0];if(M===void 0){this.connection=void 0;return}M(this.connection)}async beginTransaction(r,e){e.isolationLevel?await r.executeQuery(CompiledQuery.raw(`start transaction isolation level ${e.isolationLevel}`)):await r.executeQuery(CompiledQuery.raw("begin"))}async commitTransaction(r){await r.executeQuery(CompiledQuery.raw("commit"))}async rollbackTransaction(r){await r.executeQuery(CompiledQuery.raw("rollback"))}async destroy(){this.client=void 0}};class CollectionMembershipCache{operationIndex;cache=new Map;constructor(e){this.operationIndex=e}async getCollectionsForDocuments(e){const M={},tr=[];for(const rr of e){const ir=this.cache.get(rr);ir!==void 0?M[rr]=ir:tr.push(rr)}if(tr.length>0){const rr=await this.operationIndex.getCollectionsForDocuments(tr);for(const ir of tr){const lr=rr[ir]??[];M[ir]=lr,this.cache.set(ir,lr)}}return M}invalidate(e){this.cache.delete(e)}}class DocumentDeletedError extends Error{documentId;deletedAtUtcIso;constructor(e,M=null){const tr=M?`Document ${e} was deleted at ${M}`:`Document ${e} has been deleted`;super(tr),this.name="DocumentDeletedError",this.documentId=e,this.deletedAtUtcIso=M,Error.captureStackTrace(this,DocumentDeletedError)}}let InvalidSignatureError$1=class ds extends Error{documentId;reason;constructor(e,M){super(`Invalid signature in document ${e}: ${M}`),this.name="InvalidSignatureError",this.documentId=e,this.reason=M,Error.captureStackTrace(this,ds)}},DowngradeNotSupportedError$1=class hs extends Error{documentType;fromVersion;toVersion;constructor(e,M,tr){super(`Downgrade not supported for ${e}: cannot upgrade from version ${M} to ${tr}`),this.name="DowngradeNotSupportedError",this.documentType=e,this.fromVersion=M,this.toVersion=tr,Error.captureStackTrace(this,hs)}};function createDocumentFromAction(r){const e=r.input,M=createPresignedHeader();M.id=e.documentId,M.documentType=e.model,e.signing&&(M.createdAtUtcIso=e.signing.createdAtUtcIso,M.lastModifiedAtUtcIso=e.signing.createdAtUtcIso,M.sig={publicKey:e.signing.publicKey,nonce:e.signing.nonce}),e.slug!==void 0&&(M.slug=e.slug),M.slug||(M.slug=e.documentId),e.name!==void 0&&(M.name=e.name),e.branch!==void 0&&(M.branch=e.branch),e.meta!==void 0&&(M.meta=e.meta),e.protocolVersions!==void 0&&(M.protocolVersions=e.protocolVersions);const tr=defaultBaseState();return{header:M,operations:{},state:tr,initialState:tr,clipboard:[]}}function applyUpgradeDocumentAction(r,e,M){const tr=e.input.fromVersion,rr=e.input.toVersion;if(tr===rr&&tr>0)return r;if(tr>rr)throw new DowngradeNotSupportedError$1(r.header.documentType,tr,rr);if(M)for(const ir of M)r=ir.upgradeReducer(r,e);return applyInitialState(r,e),r.state.document={...r.state.document,version:rr},r}function applyInitialState(r,e){const M=e.input,tr=M.initialState||M.state;tr&&(r.state={...r.state,...tr},r.initialState=r.state)}function applyDeleteDocumentAction(r,e){const M=e.timestampUtcMs||new Date().toISOString();return r.state={...r.state,document:{...r.state.document,isDeleted:!0,deletedAtUtcIso:M}},r}const getNextIndexForScope=(r,e)=>r.header.revision[e]||0;function createEmptyConsistencyToken(){return{version:1,createdAtUtcIso:new Date().toISOString(),coordinates:[]}}function createConsistencyToken(r){if(r.length===0)return createEmptyConsistencyToken();const e=[];for(let M=0;M<r.length;M++){const tr=r[M];e.push({documentId:tr.context.documentId,scope:tr.context.scope,branch:tr.context.branch,operationIndex:tr.operation.index})}return{version:1,createdAtUtcIso:new Date().toISOString(),coordinates:e}}function createOperation(r,e,M,tr){return{id:deriveOperationId(tr.documentId,tr.scope,tr.branch,r.id),index:e,timestampUtcMs:r.timestampUtcMs||new Date().toISOString(),hash:"",skip:M,action:r}}function updateDocumentRevision(r,e,M){r.header.revision={...r.header.revision,[e]:M+1}}function buildSuccessResult(r,e,M,tr,rr,ir){return{job:r,success:!0,operations:[e],operationsWithContext:[{operation:e,context:{documentId:M,scope:r.scope,branch:r.branch,documentType:tr,resultingState:rr,ordinal:0}}],duration:Date.now()-ir}}function buildErrorResult(r,e,M){return{job:r,success:!1,error:e,duration:Date.now()-M}}class LRUNode{key;prev;next;constructor(e){this.key=e,this.prev=void 0,this.next=void 0}}class LRUTracker{map;head;tail;constructor(){this.map=new Map,this.head=void 0,this.tail=void 0}get size(){return this.map.size}touch(e){const M=this.map.get(e);M?this.moveToFront(M):this.addToFront(e)}evict(){if(!this.tail)return;const e=this.tail.key;return this.remove(e),e}remove(e){const M=this.map.get(e);M&&(this.removeNode(M),this.map.delete(e))}clear(){this.map.clear(),this.head=void 0,this.tail=void 0}addToFront(e){const M=new LRUNode(e);this.map.set(e,M),this.head?(M.next=this.head,this.head.prev=M,this.head=M):(this.head=M,this.tail=M)}moveToFront(e){e!==this.head&&(this.removeNode(e),e.prev=void 0,e.next=this.head,this.head&&(this.head.prev=e),this.head=e,this.tail||(this.tail=e))}removeNode(e){e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev}}class DocumentMetaCache{cache;lruTracker;operationStore;config;constructor(e,M){this.operationStore=e,this.config={maxDocuments:M.maxDocuments},this.cache=new Map,this.lruTracker=new LRUTracker}async startup(){return Promise.resolve()}async shutdown(){return Promise.resolve()}async getDocumentMeta(e,M,tr){if(tr?.aborted)throw new Error("Operation aborted");const rr=this.makeKey(e,M),ir=this.cache.get(rr);if(ir)return this.lruTracker.touch(rr),ir;const lr=await this.rebuildLatest(e,M,tr);return this.putDocumentMeta(e,M,lr),lr}async rebuildAtRevision(e,M,tr,rr){if(rr?.aborted)throw new Error("Operation aborted");return this.rebuildFromOperations(e,M,tr,rr)}putDocumentMeta(e,M,tr){const rr=this.makeKey(e,M);if(!this.cache.has(rr)&&this.cache.size>=this.config.maxDocuments){const ir=this.lruTracker.evict();ir&&this.cache.delete(ir)}this.cache.set(rr,structuredClone(tr)),this.lruTracker.touch(rr)}invalidate(e,M){let tr=0;if(M===void 0)for(const rr of this.cache.keys())rr.startsWith(`${e}:`)&&(this.cache.delete(rr),this.lruTracker.remove(rr),tr++);else{const rr=this.makeKey(e,M);this.cache.has(rr)&&(this.cache.delete(rr),this.lruTracker.remove(rr),tr=1)}return tr}clear(){this.cache.clear(),this.lruTracker.clear()}makeKey(e,M){return`${e}:${M}`}async rebuildLatest(e,M,tr){return this.rebuildFromOperations(e,M,void 0,tr)}async rebuildFromOperations(e,M,tr,rr){const ir=await this.operationStore.getSince(e,"document",M,-1,void 0,void 0,rr);if(ir.results.length===0)throw new Error(`Document ${e} not found`);const lr=ir.results[0];if(lr.action.type!=="CREATE_DOCUMENT")throw new Error(`Invalid document: first operation must be CREATE_DOCUMENT, found ${lr.action.type}`);const dr=lr.action,hr=dr.input.model;let fr=createDocumentFromAction(dr),mr=0;for(const _r of ir.results){if(tr!==void 0&&_r.index>tr)break;if(mr=_r.index,_r.action.type==="UPGRADE_DOCUMENT"){const gr=_r.action;fr=applyUpgradeDocumentAction(fr,gr)}else _r.action.type==="DELETE_DOCUMENT"&&(fr=applyDeleteDocumentAction(fr,_r.action))}return{state:fr.state.document,documentType:hr,documentScopeRevision:mr+1}}}class KyselyOperationIndexTxn{collections=[];collectionMemberships=[];collectionRemovals=[];operations=[];createCollection(e){this.collections.push(e)}addToCollection(e,M){const tr=this.operations.length-1;if(tr<0)throw new Error("addToCollection must be called after write() - no operations in transaction");this.collectionMemberships.push({collectionId:e,documentId:M,operationIndex:tr})}removeFromCollection(e,M){const tr=this.operations.length-1;if(tr<0)throw new Error("removeFromCollection must be called after write() - no operations in transaction");this.collectionRemovals.push({collectionId:e,documentId:M,operationIndex:tr})}write(e){this.operations.push(...e)}getCollections(){return this.collections}getCollectionMembershipRecords(){return this.collectionMemberships}getCollectionRemovals(){return this.collectionRemovals}getOperations(){return this.operations}}class KyselyOperationIndex{db;constructor(e){this.db=e}start(){return new KyselyOperationIndexTxn}async commit(e,M){if(M?.aborted)throw new Error("Operation aborted");const tr=e,rr=tr.getCollections(),ir=tr.getCollectionMembershipRecords(),lr=tr.getCollectionRemovals(),dr=tr.getOperations();let hr=[];return await this.db.transaction().execute(async fr=>{if(rr.length>0){const _r=rr.map(gr=>({documentId:gr,collectionId:gr,joinedOrdinal:BigInt(0),leftOrdinal:null}));await fr.insertInto("document_collections").values(_r).onConflict(gr=>gr.doNothing()).execute()}let mr=[];if(dr.length>0){const _r=dr.map(wr=>({opId:wr.id||"",documentId:wr.documentId,documentType:wr.documentType,scope:wr.scope,branch:wr.branch,timestampUtcMs:wr.timestampUtcMs,index:wr.index,skip:wr.skip,hash:wr.hash,action:wr.action,sourceRemote:wr.sourceRemote}));mr=(await fr.insertInto("operation_index_operations").values(_r).returning("ordinal").execute()).map(wr=>wr.ordinal),hr=mr}if(ir.length>0)for(const _r of ir){const gr=mr[_r.operationIndex];await fr.insertInto("document_collections").values({documentId:_r.documentId,collectionId:_r.collectionId,joinedOrdinal:BigInt(gr),leftOrdinal:null}).onConflict(wr=>wr.columns(["documentId","collectionId"]).doUpdateSet({joinedOrdinal:BigInt(gr),leftOrdinal:null})).execute()}if(lr.length>0)for(const _r of lr){const gr=mr[_r.operationIndex];await fr.updateTable("document_collections").set({leftOrdinal:BigInt(gr)}).where("collectionId","=",_r.collectionId).where("documentId","=",_r.documentId).where("leftOrdinal","is",null).execute()}}),hr}async find(e,M,tr,rr,ir){if(ir?.aborted)throw new Error("Operation aborted");let lr=this.db.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","=",e).where(sql`(dc."leftOrdinal" IS NULL OR oi.ordinal < dc."leftOrdinal")`).orderBy("oi.ordinal","asc");if(M!==void 0&&(lr=lr.where("oi.ordinal",">",M)),tr?.branch&&(lr=lr.where("oi.branch","=",tr.branch)),tr?.scopes&&tr.scopes.length>0&&(lr=lr.where("oi.scope","in",tr.scopes)),tr?.excludeSourceRemote&&(lr=lr.where("oi.sourceRemote","!=",tr.excludeSourceRemote)),rr?.cursor){const yr=Number.parseInt(rr.cursor,10);lr=lr.where("oi.ordinal",">",yr)}rr?.limit&&(lr=lr.limit(rr.limit+1));const dr=await lr.execute();let hr=!1,fr=dr;rr?.limit&&dr.length>rr.limit&&(hr=!0,fr=dr.slice(0,rr.limit));const mr=hr&&fr.length>0?fr[fr.length-1].ordinal.toString():void 0,_r=rr?.cursor||"0",gr=rr?.limit||100;return{results:fr.map(yr=>this.rowToOperationIndexEntry(yr)),options:{cursor:_r,limit:gr},nextCursor:mr,next:hr?()=>this.find(e,M,tr,{cursor:mr,limit:gr},ir):void 0}}async get(e,M,tr,rr){if(rr?.aborted)throw new Error("Operation aborted");let ir=this.db.selectFrom("operation_index_operations").selectAll().where("documentId","=",e).orderBy("ordinal","asc");if(M?.branch&&(ir=ir.where("branch","=",M.branch)),M?.scopes&&M.scopes.length>0&&(ir=ir.where("scope","in",M.scopes)),tr?.cursor){const wr=Number.parseInt(tr.cursor,10);ir=ir.where("ordinal",">",wr)}tr?.limit&&(ir=ir.limit(tr.limit+1));const lr=await ir.execute();let dr=!1,hr=lr;tr?.limit&&lr.length>tr.limit&&(dr=!0,hr=lr.slice(0,tr.limit));const fr=dr&&hr.length>0?hr[hr.length-1].ordinal.toString():void 0,mr=tr?.cursor||"0",_r=tr?.limit||100;return{results:hr.map(wr=>this.rowToOperationIndexEntry(wr)),options:{cursor:mr,limit:_r},nextCursor:fr,next:dr?()=>this.get(e,M,{cursor:fr,limit:_r},rr):void 0}}async getSinceOrdinal(e,M,tr){if(tr?.aborted)throw new Error("Operation aborted");let rr=this.db.selectFrom("operation_index_operations").selectAll().where("ordinal",">",e).orderBy("ordinal","asc");if(M?.cursor){const gr=Number.parseInt(M.cursor,10);rr=rr.where("ordinal",">",gr)}M?.limit&&(rr=rr.limit(M.limit+1));const ir=await rr.execute();let lr=!1,dr=ir;M?.limit&&ir.length>M.limit&&(lr=!0,dr=ir.slice(0,M.limit));const hr=lr&&dr.length>0?dr[dr.length-1].ordinal.toString():void 0,fr=M?.cursor||"0",mr=M?.limit||100;return{results:dr.map(gr=>this.rowToOperationWithContext(gr)),options:{cursor:fr,limit:mr},nextCursor:hr,next:lr?()=>this.getSinceOrdinal(e,{cursor:hr,limit:mr},tr):void 0}}rowToOperationWithContext(e){return{operation:{index:e.index,timestampUtcMs:e.timestampUtcMs,hash:e.hash,skip:e.skip,action:e.action,id:e.opId},context:{documentId:e.documentId,documentType:e.documentType,scope:e.scope,branch:e.branch,ordinal:e.ordinal}}}rowToOperationIndexEntry(e){return{ordinal:e.ordinal,documentId:e.documentId,documentType:e.documentType,branch:e.branch,scope:e.scope,index:e.index,timestampUtcMs:e.timestampUtcMs,hash:e.hash,skip:e.skip,action:e.action,id:e.opId,sourceRemote:e.sourceRemote}}async getLatestTimestampForCollection(e,M){if(M?.aborted)throw new Error("Operation aborted");return(await this.db.selectFrom("operation_index_operations as oi").innerJoin("document_collections as dc","oi.documentId","dc.documentId").select("oi.timestampUtcMs").where("dc.collectionId","=",e).where(sql`(dc."leftOrdinal" IS NULL OR oi.ordinal < dc."leftOrdinal")`).orderBy("oi.ordinal","desc").limit(1).executeTakeFirst())?.timestampUtcMs??null}async getCollectionsForDocuments(e){if(e.length===0)return{};const M=await this.db.selectFrom("document_collections").select(["documentId","collectionId"]).where("documentId","in",e).where("leftOrdinal","is",null).execute(),tr={};for(const rr of M)rr.documentId in tr||(tr[rr.documentId]=[]),tr[rr.documentId].push(rr.collectionId);return tr}}class RingBuffer{buffer;head=0;size=0;capacity;constructor(e){if(e<=0)throw new Error("Ring buffer capacity must be greater than 0");this.capacity=e,this.buffer=new Array(e)}push(e){const M=(this.head+this.size)%this.capacity;this.size<this.capacity?(this.buffer[M]=e,this.size++):(this.buffer[this.head]=e,this.head=(this.head+1)%this.capacity)}getAll(){if(this.size===0)return[];const e=[];for(let M=0;M<this.size;M++){const tr=(this.head+M)%this.capacity;e.push(this.buffer[tr])}return e}clear(){this.buffer=new Array(this.capacity),this.head=0,this.size=0}get length(){return this.size}}class KyselyWriteCache{streams;lruTracker;keyframeStore;operationStore;registry;config;constructor(e,M,tr,rr){this.keyframeStore=e,this.operationStore=M,this.registry=tr,this.config={maxDocuments:rr.maxDocuments,ringBufferSize:rr.ringBufferSize,keyframeInterval:rr.keyframeInterval},this.streams=new Map,this.lruTracker=new LRUTracker}async startup(){return Promise.resolve()}async shutdown(){return Promise.resolve()}async getState(e,M,tr,rr,ir){if(ir?.aborted)throw new Error("Operation aborted");const lr=this.makeStreamKey(e,M,tr),dr=this.streams.get(lr);if(dr){const mr=dr.ringBuffer.getAll();if(rr===void 0){if(mr.length>0){const _r=mr[mr.length-1];return this.lruTracker.touch(lr),_r.document}}else{const _r=mr.find(wr=>wr.revision===rr);if(_r)return this.lruTracker.touch(lr),_r.document;const gr=this.findNearestOlderSnapshot(mr,rr);if(gr){const wr=await this.warmMissRebuild(gr.document,gr.revision,e,M,tr,rr,ir);return this.putState(e,M,tr,rr,wr),this.lruTracker.touch(lr),wr}}}const hr=await this.coldMissRebuild(e,M,tr,rr,ir);let fr=rr;return fr===void 0&&(fr=hr.header.revision[M]||0),this.putState(e,M,tr,fr,hr),hr}putState(e,M,tr,rr,ir){const lr=this.makeStreamKey(e,M,tr),dr=this.getOrCreateStream(lr),hr={revision:rr,document:ir};dr.ringBuffer.push(hr),this.isKeyframeRevision(rr)&&this.keyframeStore.putKeyframe(e,M,tr,rr,{...ir,operations:{},clipboard:[]}).catch(fr=>{console.error(`Failed to persist keyframe ${e}@${rr}:`,fr)})}invalidate(e,M,tr){let rr=0;if(M===void 0&&tr===void 0)for(const[ir]of this.streams.entries())ir.startsWith(`${e}:`)&&(this.streams.delete(ir),this.lruTracker.remove(ir),rr++);else if(M!==void 0&&tr===void 0)for(const[ir]of this.streams.entries())ir.startsWith(`${e}:${M}:`)&&(this.streams.delete(ir),this.lruTracker.remove(ir),rr++);else if(M!==void 0&&tr!==void 0){const ir=this.makeStreamKey(e,M,tr);this.streams.has(ir)&&(this.streams.delete(ir),this.lruTracker.remove(ir),rr=1)}return rr}clear(){this.streams.clear(),this.lruTracker.clear()}getStream(e,M,tr){const rr=this.makeStreamKey(e,M,tr);return this.streams.get(rr)}async findNearestKeyframe(e,M,tr,rr,ir){if(!(rr===Number.MAX_SAFE_INTEGER||rr<=0))return this.keyframeStore.findNearestKeyframe(e,M,tr,rr,ir)}async coldMissRebuild(e,M,tr,rr,ir){const lr=rr||Number.MAX_SAFE_INTEGER,dr=await this.findNearestKeyframe(e,M,tr,lr,ir);let hr,fr,mr;if(dr)hr=dr.document,fr=dr.revision,mr=dr.document.header.documentType;else{hr=void 0,fr=-1;const Mr=await this.operationStore.getSince(e,"document",tr,-1,void 0,{cursor:"0",limit:1},ir);if(Mr.results.length===0)throw new Error(`Failed to rebuild document ${e}: no CREATE_DOCUMENT operation found in document scope`);const vr=Mr.results[0];if(vr.action.type!=="CREATE_DOCUMENT")throw new Error(`Failed to rebuild document ${e}: first operation in document scope must be CREATE_DOCUMENT, found ${vr.action.type}`);const Sr=vr.action;if(mr=Sr.input.model,!mr)throw new Error(`Failed to rebuild document ${e}: CREATE_DOCUMENT action missing model in input`);hr=createDocumentFromAction(Sr);const xr=this.registry.getModule(mr),Ar=await this.operationStore.getSince(e,"document",tr,0,void 0,void 0,ir);for(const Dr of Ar.results)if(Dr.index!==0)if(Dr.action.type==="UPGRADE_DOCUMENT"){const Ir=Dr.action;hr=applyUpgradeDocumentAction(hr,Ir)}else if(Dr.action.type==="DELETE_DOCUMENT")applyDeleteDocumentAction(hr,Dr.action);else{const Ir=hr.header.protocolVersions?.["base-reducer"]??1;hr=xr.reducer(hr,Dr.action,void 0,{skip:Dr.skip,protocolVersion:Ir})}}const _r=this.registry.getModule(mr);let gr;const wr=100;let yr;do{if(ir?.aborted)throw new Error("Operation aborted");const Mr={cursor:gr||"0",limit:wr};try{const vr=await this.operationStore.getSince(e,M,tr,fr,void 0,Mr,ir);for(const xr of vr.results){if(rr!==void 0&&xr.index>rr)break;const Ar=hr.header.protocolVersions?.["base-reducer"]??1;hr=_r.reducer(hr,xr.action,void 0,{skip:xr.skip,protocolVersion:Ar})}const Sr=rr!==void 0&&vr.results.some(xr=>xr.index>=rr);yr=!!vr.nextCursor&&!Sr,yr&&(gr=vr.nextCursor)}catch(vr){throw new Error(`Failed to rebuild document ${e}: ${vr instanceof Error?vr.message:String(vr)}`)}}while(yr);const br=await this.operationStore.getRevisions(e,tr,ir);return hr.header.revision=br.revision,hr.header.lastModifiedAtUtcIso=br.latestTimestamp,hr}async warmMissRebuild(e,M,tr,rr,ir,lr,dr){const hr=e.header.documentType,fr=this.registry.getModule(hr);let mr=e;try{const gr=await this.operationStore.getSince(tr,rr,ir,M,void 0,void 0,dr);for(const wr of gr.results){if(dr?.aborted)throw new Error("Operation aborted");if(lr!==void 0&&wr.index>lr)break;const yr=mr.header.protocolVersions?.["base-reducer"]??1;if(mr=fr.reducer(mr,wr.action,void 0,{skip:wr.skip,protocolVersion:yr}),lr!==void 0&&wr.index===lr)break}}catch(gr){throw new Error(`Failed to rebuild document ${tr}: ${gr instanceof Error?gr.message:String(gr)}`)}const _r=await this.operationStore.getRevisions(tr,ir,dr);return mr.header.revision=_r.revision,mr.header.lastModifiedAtUtcIso=_r.latestTimestamp,mr}findNearestOlderSnapshot(e,M){let tr;for(const rr of e)rr.revision<M&&(!tr||rr.revision>tr.revision)&&(tr=rr);return tr}makeStreamKey(e,M,tr){return`${e}:${M}:${tr}`}getOrCreateStream(e){let M=this.streams.get(e);if(!M){if(this.streams.size>=this.config.maxDocuments){const tr=this.lruTracker.evict();tr&&this.streams.delete(tr)}M={key:e,ringBuffer:new RingBuffer(this.config.ringBufferSize)},this.streams.set(e,M)}return this.lruTracker.touch(e),M}isKeyframeRevision(e){return e>0&&e%this.config.keyframeInterval===0}}class EventBus{eventTypeToSubscribers=new Map;subscribe(e,M){let tr=this.eventTypeToSubscribers.get(e);tr||(tr=[],this.eventTypeToSubscribers.set(e,tr)),tr.push(M);let rr=!1;return()=>{if(rr)return;rr=!0;const ir=this.eventTypeToSubscribers.get(e);if(!ir)return;const lr=ir.indexOf(M);lr!==-1&&ir.splice(lr,1),ir.length===0&&this.eventTypeToSubscribers.delete(e)}}async emit(e,M){const tr=this.eventTypeToSubscribers.get(e);if(!tr||tr.length===0)return;const rr=tr.slice(),ir=[];for(const lr of rr)try{await Promise.resolve(lr(e,M))}catch(dr){ir.push(dr)}if(ir.length>0)throw new EventBusAggregateError(ir)}}var JobQueueState;(function(r){r[r.UNKNOWN=-1]="UNKNOWN",r[r.PREPROCESSING=0]="PREPROCESSING",r[r.PENDING=1]="PENDING",r[r.READY=2]="READY",r[r.RUNNING=3]="RUNNING",r[r.RESOLVED=4]="RESOLVED"})(JobQueueState||(JobQueueState={}));const QueueEventTypes={JOB_AVAILABLE:1e4};class SimpleJobExecutorManager{executorFactory;eventBus;queue;jobTracker;logger;executors=[];isRunning=!1;activeJobs=0;totalJobsProcessed=0;unsubscribe;constructor(e,M,tr,rr,ir){this.executorFactory=e,this.eventBus=M,this.queue=tr,this.jobTracker=rr,this.logger=ir}async start(e){if(this.isRunning)throw new Error("JobExecutorManager is already running");if(e<1)throw new Error("Number of executors must be at least 1");this.executors=[];for(let M=0;M<e;M++)this.executors.push(this.executorFactory());this.unsubscribe=this.eventBus.subscribe(QueueEventTypes.JOB_AVAILABLE,async()=>{this.activeJobs<this.executors.length&&await this.processNextJob()}),this.isRunning=!0,await this.processExistingJobs()}async stop(e=!0){if(this.isRunning){if(this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0),e)for(;this.activeJobs>0;)await new Promise(M=>setTimeout(M,100));this.executors=[],this.isRunning=!1}}getExecutors(){return[...this.executors]}getStatus(){return{isRunning:this.isRunning,numExecutors:this.executors.length,activeJobs:this.activeJobs,totalJobsProcessed:this.totalJobsProcessed}}async processNextJob(){let e;try{e=await this.queue.dequeueNext()}catch(lr){this.logger.error("Error dequeueing next job: @Error",lr);return}if(!e)return;e.start(),this.activeJobs++,this.jobTracker.markRunning(e.job.id);const M={jobId:e.job.id,jobMeta:e.job.meta};this.eventBus.emit(ReactorEventTypes.JOB_RUNNING,M).catch(()=>{});const tr=this.totalJobsProcessed%this.executors.length,rr=this.executors[tr];let ir;try{ir=await rr.executeJob(e.job)}catch(lr){const dr=this.toErrorInfo(lr instanceof Error?lr:String(lr));e.fail(dr),this.activeJobs--,this.jobTracker.markFailed(e.job.id,dr,e.job),this.eventBus.emit(ReactorEventTypes.JOB_FAILED,{jobId:e.job.id,error:new Error(dr.message),job:e.job}).catch(()=>{}),await this.checkForMoreJobs();return}if(ir.success)e.complete(),this.totalJobsProcessed++;else{const lr=e.job.retryCount||0,dr=e.job.maxRetries||0;if(lr<dr){const hr=ir.error?this.toErrorInfo(ir.error):this.toErrorInfo("Unknown error");try{await this.queue.retryJob(e.job.id,hr)}catch(fr){const mr=this.toErrorInfo(fr instanceof Error?fr:"Failed to retry job");this.jobTracker.markFailed(e.job.id,mr,e.job),this.eventBus.emit(ReactorEventTypes.JOB_FAILED,{jobId:e.job.id,error:new Error(mr.message),job:e.job}).catch(()=>{}),e.fail(mr)}}else{const hr=ir.error?this.toErrorInfo(ir.error):this.toErrorInfo("Unknown error"),fr=this.formatErrorHistory(e.job.errorHistory,hr,lr+1);this.jobTracker.markFailed(e.job.id,fr,e.job),this.eventBus.emit(ReactorEventTypes.JOB_FAILED,{jobId:e.job.id,error:new Error(fr.message),job:e.job}).catch(()=>{}),e.fail(fr)}}this.activeJobs--,await this.checkForMoreJobs()}async checkForMoreJobs(){if(!this.isRunning)return;let e;try{e=await this.queue.hasJobs()}catch(M){this.logger.error("Error checking for more jobs: @Error",M);return}e&&await this.processNextJob()}async processExistingJobs(){let e;try{e=await this.queue.hasJobs()}catch(M){this.logger.error("Error checking for existing jobs: @Error",M);return}if(e){const M=[];for(let tr=0;tr<Math.min(this.executors.length,5);tr++)M.push(this.processNextJob());try{await Promise.all(M)}catch(tr){this.logger.error("Error processing existing jobs: @Error",tr)}}}toErrorInfo(e){return e instanceof Error?{message:e.message,stack:e.stack||new Error().stack||""}:{message:e,stack:new Error().stack||""}}formatErrorHistory(e,M,tr){const rr=[...e,M];if(rr.length===1)return M;const ir=[`Job failed after ${tr} attempts:`],lr=[];return rr.forEach((dr,hr)=>{ir.push(`[Attempt ${hr+1}] ${dr.message}`),lr.push(`[Attempt ${hr+1}] Stack trace:
12
+ ${dr.stack}`)}),{message:ir.join(`
13
+ `),stack:lr.join(`
14
+
15
+ `)}}}function reshuffleByTimestamp(r,e,M){return[...e,...M].sort((tr,rr)=>{const ir=new Date(tr.timestampUtcMs).getTime()-new Date(rr.timestampUtcMs).getTime();if(ir!==0)return ir;const lr=tr.index-rr.index;return lr!==0?lr:tr.id.localeCompare(rr.id)}).map((tr,rr)=>({...tr,index:r.index+rr,skip:rr===0?r.skip:0}))}function driveCollectionId(r,e){return`drive.${r}.${e}`}class DocumentActionHandler{writeCache;operationStore;documentMetaCache;collectionMembershipCache;registry;logger;constructor(e,M,tr,rr,ir,lr){this.writeCache=e,this.operationStore=M,this.documentMetaCache=tr,this.collectionMembershipCache=rr,this.registry=ir,this.logger=lr}async execute(e,M,tr,rr,ir=0,lr=""){switch(M.type){case"CREATE_DOCUMENT":return this.executeCreate(e,M,tr,rr,ir,lr);case"DELETE_DOCUMENT":return this.executeDelete(e,M,tr,rr,lr);case"UPGRADE_DOCUMENT":return this.executeUpgrade(e,M,tr,rr,ir,lr);case"ADD_RELATIONSHIP":return this.executeAddRelationship(e,M,tr,rr,lr);case"REMOVE_RELATIONSHIP":return this.executeRemoveRelationship(e,M,tr,rr,lr);default:return buildErrorResult(e,new Error(`Unknown document action type: ${M.type}`),tr)}}async executeCreate(e,M,tr,rr,ir=0,lr=""){if(e.scope!=="document")return{job:e,success:!1,error:new Error(`CREATE_DOCUMENT must be in "document" scope, got "${e.scope}"`),duration:Date.now()-tr};const dr=createDocumentFromAction(M),hr=createOperation(M,0,ir,{documentId:dr.header.id,scope:e.scope,branch:e.branch}),fr={header:dr.header,...dr.state},mr=JSON.stringify(fr),_r=await this.writeOperationToStore(dr.header.id,dr.header.documentType,e.scope,e.branch,hr,e,tr);if(_r!==null)return _r;if(updateDocumentRevision(dr,e.scope,hr.index),this.writeCache.putState(dr.header.id,e.scope,e.branch,hr.index,dr),rr.write([{...hr,documentId:dr.header.id,documentType:dr.header.documentType,branch:e.branch,scope:e.scope,sourceRemote:lr}]),dr.header.documentType==="powerhouse/document-drive"){const gr=driveCollectionId(e.branch,dr.header.id);rr.createCollection(gr),rr.addToCollection(gr,dr.header.id)}return this.documentMetaCache.putDocumentMeta(dr.header.id,e.branch,{state:dr.state.document,documentType:dr.header.documentType,documentScopeRevision:1}),buildSuccessResult(e,hr,dr.header.id,dr.header.documentType,mr,tr)}async executeDelete(e,M,tr,rr,ir=""){const lr=M.input;if(!lr.documentId)return buildErrorResult(e,new Error("DELETE_DOCUMENT action requires a documentId in input"),tr);const dr=lr.documentId;let hr;try{hr=await this.writeCache.getState(dr,e.scope,e.branch)}catch(br){return buildErrorResult(e,new Error(`Failed to fetch document before deletion: ${br instanceof Error?br.message:String(br)}`),tr)}const fr=hr.state.document;if(fr.isDeleted)return buildErrorResult(e,new DocumentDeletedError(dr,fr.deletedAtUtcIso),tr);const mr=getNextIndexForScope(hr,e.scope),_r=createOperation(M,mr,0,{documentId:dr,scope:e.scope,branch:e.branch});applyDeleteDocumentAction(hr,M);const gr={header:hr.header,document:hr.state.document},wr=JSON.stringify(gr),yr=await this.writeOperationToStore(dr,hr.header.documentType,e.scope,e.branch,_r,e,tr);return yr!==null?yr:(rr.write([{..._r,documentId:dr,documentType:hr.header.documentType,branch:e.branch,scope:e.scope,sourceRemote:ir}]),this.documentMetaCache.putDocumentMeta(dr,e.branch,{state:hr.state.document,documentType:hr.header.documentType,documentScopeRevision:_r.index+1}),buildSuccessResult(e,_r,dr,hr.header.documentType,wr,tr))}async executeUpgrade(e,M,tr,rr,ir=0,lr=""){const dr=M.input;if(!dr.documentId)return buildErrorResult(e,new Error("UPGRADE_DOCUMENT action requires a documentId in input"),tr);const hr=dr.documentId,fr=dr.fromVersion,mr=dr.toVersion;let _r;try{_r=await this.writeCache.getState(hr,e.scope,e.branch)}catch(xr){return buildErrorResult(e,new Error(`Failed to fetch document for upgrade: ${xr instanceof Error?xr.message:String(xr)}`),tr)}const gr=_r.state.document;if(gr.isDeleted)return buildErrorResult(e,new DocumentDeletedError(hr,gr.deletedAtUtcIso),tr);const wr=getNextIndexForScope(_r,e.scope);let yr;if(fr>0&&fr<mr)try{yr=this.registry.computeUpgradePath(_r.header.documentType,fr,mr)}catch(xr){return buildErrorResult(e,xr instanceof Error?xr:new Error(String(xr)),tr)}if(fr===mr&&fr>0)return{job:e,success:!0,operations:[],operationsWithContext:[],duration:Date.now()-tr};try{_r=applyUpgradeDocumentAction(_r,M,yr)}catch(xr){return buildErrorResult(e,xr instanceof Error?xr:new Error(String(xr)),tr)}const br=createOperation(M,wr,ir,{documentId:hr,scope:e.scope,branch:e.branch}),Mr={header:_r.header,..._r.state},vr=JSON.stringify(Mr),Sr=await this.writeOperationToStore(hr,_r.header.documentType,e.scope,e.branch,br,e,tr);return Sr!==null?Sr:(updateDocumentRevision(_r,e.scope,br.index),this.writeCache.putState(hr,e.scope,e.branch,br.index,_r),rr.write([{...br,documentId:hr,documentType:_r.header.documentType,branch:e.branch,scope:e.scope,sourceRemote:lr}]),this.documentMetaCache.putDocumentMeta(hr,e.branch,{state:_r.state.document,documentType:_r.header.documentType,documentScopeRevision:br.index+1}),buildSuccessResult(e,br,hr,_r.header.documentType,vr,tr))}async executeAddRelationship(e,M,tr,rr,ir=""){if(e.scope!=="document")return buildErrorResult(e,new Error(`ADD_RELATIONSHIP must be in "document" scope, got "${e.scope}"`),tr);const lr=M.input;if(!lr.sourceId||!lr.targetId||!lr.relationshipType)return buildErrorResult(e,new Error("ADD_RELATIONSHIP action requires sourceId, targetId, and relationshipType in input"),tr);if(lr.sourceId===lr.targetId)return buildErrorResult(e,new Error("ADD_RELATIONSHIP: sourceId and targetId cannot be the same (self-relationships not allowed)"),tr);let dr;try{dr=await this.writeCache.getState(lr.sourceId,"document",e.branch)}catch(yr){return buildErrorResult(e,new Error(`ADD_RELATIONSHIP: source document ${lr.sourceId} not found: ${yr instanceof Error?yr.message:String(yr)}`),tr)}const hr=getNextIndexForScope(dr,e.scope),fr=createOperation(M,hr,0,{documentId:lr.sourceId,scope:e.scope,branch:e.branch}),mr=await this.writeOperationToStore(lr.sourceId,dr.header.documentType,e.scope,e.branch,fr,e,tr);if(mr!==null)return mr;dr.header.lastModifiedAtUtcIso=fr.timestampUtcMs||new Date().toISOString(),updateDocumentRevision(dr,e.scope,fr.index),dr.operations={...dr.operations,[e.scope]:[...dr.operations[e.scope]??[],fr]};const _r=dr.state[e.scope],gr={header:structuredClone(dr.header),[e.scope]:_r===void 0?{}:structuredClone(_r)},wr=JSON.stringify(gr);if(this.writeCache.putState(lr.sourceId,e.scope,e.branch,fr.index,dr),rr.write([{...fr,documentId:lr.sourceId,documentType:dr.header.documentType,branch:e.branch,scope:e.scope,sourceRemote:ir}]),dr.header.documentType==="powerhouse/document-drive"){const yr=driveCollectionId(e.branch,lr.sourceId);rr.addToCollection(yr,lr.targetId),this.collectionMembershipCache.invalidate(lr.targetId)}return this.documentMetaCache.putDocumentMeta(lr.sourceId,e.branch,{state:dr.state.document,documentType:dr.header.documentType,documentScopeRevision:fr.index+1}),buildSuccessResult(e,fr,lr.sourceId,dr.header.documentType,wr,tr)}async executeRemoveRelationship(e,M,tr,rr,ir=""){if(e.scope!=="document")return buildErrorResult(e,new Error(`REMOVE_RELATIONSHIP must be in "document" scope, got "${e.scope}"`),tr);const lr=M.input;if(!lr.sourceId||!lr.targetId||!lr.relationshipType)return buildErrorResult(e,new Error("REMOVE_RELATIONSHIP action requires sourceId, targetId, and relationshipType in input"),tr);let dr;try{dr=await this.writeCache.getState(lr.sourceId,"document",e.branch)}catch(yr){return buildErrorResult(e,new Error(`REMOVE_RELATIONSHIP: source document ${lr.sourceId} not found: ${yr instanceof Error?yr.message:String(yr)}`),tr)}const hr=getNextIndexForScope(dr,e.scope),fr=createOperation(M,hr,0,{documentId:lr.sourceId,scope:e.scope,branch:e.branch}),mr=await this.writeOperationToStore(lr.sourceId,dr.header.documentType,e.scope,e.branch,fr,e,tr);if(mr!==null)return mr;dr.header.lastModifiedAtUtcIso=fr.timestampUtcMs||new Date().toISOString(),updateDocumentRevision(dr,e.scope,fr.index),dr.operations={...dr.operations,[e.scope]:[...dr.operations[e.scope]??[],fr]};const _r=dr.state[e.scope],gr={header:structuredClone(dr.header),[e.scope]:_r===void 0?{}:structuredClone(_r)},wr=JSON.stringify(gr);if(this.writeCache.putState(lr.sourceId,e.scope,e.branch,fr.index,dr),rr.write([{...fr,documentId:lr.sourceId,documentType:dr.header.documentType,branch:e.branch,scope:e.scope,sourceRemote:ir}]),dr.header.documentType==="powerhouse/document-drive"){const yr=driveCollectionId(e.branch,lr.sourceId);rr.removeFromCollection(yr,lr.targetId),this.collectionMembershipCache.invalidate(lr.targetId)}return this.documentMetaCache.putDocumentMeta(lr.sourceId,e.branch,{state:dr.state.document,documentType:dr.header.documentType,documentScopeRevision:fr.index+1}),buildSuccessResult(e,fr,lr.sourceId,dr.header.documentType,wr,tr)}async writeOperationToStore(e,M,tr,rr,ir,lr,dr){try{return await this.operationStore.apply(e,M,tr,rr,ir.index,hr=>{hr.addOperations(ir)}),null}catch(hr){return this.logger.error("Error writing @Operation to IOperationStore: @Error",ir,hr),this.writeCache.invalidate(e,tr,rr),{job:lr,success:!1,error:new Error(`Failed to write operation to IOperationStore: ${hr instanceof Error?hr.message:String(hr)}`),duration:Date.now()-dr}}}}class SignatureVerifier{verifier;constructor(e){this.verifier=e}async verifyActions(e,M,tr){if(this.verifier)for(const rr of tr){const ir=rr.context?.signer;if(!ir)continue;if(ir.signatures.length===0)throw new InvalidSignatureError$1(e,`Action ${rr.id} has signer but no signatures`);const lr=ir.app.key;let dr=!1;try{const hr={id:deriveOperationId(e,rr.scope,M,rr.id),index:0,timestampUtcMs:rr.timestampUtcMs||new Date().toISOString(),hash:"",skip:0,action:rr};dr=await this.verifier(hr,lr)}catch(hr){const fr=hr instanceof Error?hr.message:String(hr);throw new InvalidSignatureError$1(e,`Action ${rr.id} verification failed: ${fr}`)}if(!dr)throw new InvalidSignatureError$1(e,`Action ${rr.id} signature verification returned false`)}}async verifyOperations(e,M){if(this.verifier)for(let tr=0;tr<M.length;tr++){const rr=M[tr],ir=rr.action.context?.signer;if(!ir)continue;if(ir.signatures.length===0)throw new InvalidSignatureError$1(e,`Operation ${rr.id} at index ${rr.index} has signer but no signatures`);const lr=ir.app.key;let dr=!1;try{dr=await this.verifier(rr,lr)}catch(hr){const fr=hr instanceof Error?hr.message:String(hr);throw new InvalidSignatureError$1(e,`Operation ${rr.id} at index ${rr.index} verification failed: ${fr}`)}if(!dr)throw new InvalidSignatureError$1(e,`Operation ${rr.id} at index ${rr.index} signature verification returned false`)}}}const MAX_SKIP_THRESHOLD=1e3,documentScopeActions=["CREATE_DOCUMENT","DELETE_DOCUMENT","UPGRADE_DOCUMENT","ADD_RELATIONSHIP","REMOVE_RELATIONSHIP"];class SimpleJobExecutor{logger;registry;operationStore;eventBus;writeCache;operationIndex;documentMetaCache;collectionMembershipCache;config;signatureVerifierModule;documentActionHandler;constructor(e,M,tr,rr,ir,lr,dr,hr,fr,mr){this.logger=e,this.registry=M,this.operationStore=tr,this.eventBus=rr,this.writeCache=ir,this.operationIndex=lr,this.documentMetaCache=dr,this.collectionMembershipCache=hr,this.config={maxSkipThreshold:fr.maxSkipThreshold??MAX_SKIP_THRESHOLD,maxConcurrency:fr.maxConcurrency??1,jobTimeoutMs:fr.jobTimeoutMs??3e4,retryBaseDelayMs:fr.retryBaseDelayMs??100,retryMaxDelayMs:fr.retryMaxDelayMs??5e3},this.signatureVerifierModule=new SignatureVerifier(mr),this.documentActionHandler=new DocumentActionHandler(ir,tr,dr,hr,M,e)}async executeJob(e){const M=Date.now(),tr=this.operationIndex.start();if(e.kind==="load"){const lr=await this.executeLoadJob(e,M,tr);if(lr.success&&lr.operationsWithContext){const dr=await this.operationIndex.commit(tr);for(let mr=0;mr<lr.operationsWithContext.length;mr++)lr.operationsWithContext[mr].context.ordinal=dr[mr];const hr=lr.operationsWithContext.length>0?await this.getCollectionMembershipsForOperations(lr.operationsWithContext):{},fr={jobId:e.id,operations:lr.operationsWithContext,jobMeta:e.meta,collectionMemberships:hr};this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY,fr).catch(mr=>{this.logger.error("Failed to emit JOB_WRITE_READY event: @Event : @Error",fr,mr)})}return lr}const rr=await this.processActions(e,e.actions,M,tr);if(!rr.success)return{job:e,success:!1,error:rr.error,duration:Date.now()-M};const ir=await this.operationIndex.commit(tr);if(rr.operationsWithContext.length>0){for(let hr=0;hr<rr.operationsWithContext.length;hr++)rr.operationsWithContext[hr].context.ordinal=ir[hr];const lr=await this.getCollectionMembershipsForOperations(rr.operationsWithContext),dr={jobId:e.id,operations:rr.operationsWithContext,jobMeta:e.meta,collectionMemberships:lr};this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY,dr).catch(hr=>{this.logger.error("Failed to emit JOB_WRITE_READY event: @Event : @Error",dr,hr)})}return{job:e,success:!0,operations:rr.generatedOperations,operationsWithContext:rr.operationsWithContext,duration:Date.now()-M}}async getCollectionMembershipsForOperations(e){const M=[...new Set(e.map(tr=>tr.context.documentId))];return this.collectionMembershipCache.getCollectionsForDocuments(M)}async processActions(e,M,tr,rr,ir,lr,dr=""){const hr=[],fr=[];try{await this.signatureVerifierModule.verifyActions(e.documentId,e.branch,M)}catch(mr){return{success:!1,generatedOperations:hr,operationsWithContext:fr,error:mr instanceof Error?mr:new Error(String(mr))}}for(let mr=0;mr<M.length;mr++){const _r=M[mr],gr=ir?.[mr]??0,wr=lr?.[mr],br=documentScopeActions.includes(_r.type)?await this.documentActionHandler.execute(e,_r,tr,rr,gr,dr):await this.executeRegularAction(e,_r,tr,rr,gr,wr,dr),Mr=this.accumulateResultOrReturnError(br,hr,fr);if(Mr!==null)return{success:!1,generatedOperations:hr,operationsWithContext:fr,error:Mr.error}}return{success:!0,generatedOperations:hr,operationsWithContext:fr}}async executeRegularAction(e,M,tr,rr,ir=0,lr,dr=""){let hr;try{hr=await this.documentMetaCache.getDocumentMeta(e.documentId,e.branch)}catch(Mr){return buildErrorResult(e,Mr instanceof Error?Mr:new Error(String(Mr)),tr)}if(hr.state.isDeleted)return buildErrorResult(e,new DocumentDeletedError(e.documentId,hr.state.deletedAtUtcIso),tr);let fr;try{fr=await this.writeCache.getState(e.documentId,e.scope,e.branch)}catch(Mr){return buildErrorResult(e,Mr instanceof Error?Mr:new Error(String(Mr)),tr)}let mr;try{const Mr=hr.state.version===0?void 0:hr.state.version;mr=this.registry.getModule(fr.header.documentType,Mr)}catch(Mr){return buildErrorResult(e,Mr instanceof Error?Mr:new Error(String(Mr)),tr)}let _r;try{const Mr=fr.header.protocolVersions?.["base-reducer"]??1,vr=lr?{skip:ir,branch:e.branch,replayOptions:{operation:lr},protocolVersion:Mr}:{skip:ir,branch:e.branch,protocolVersion:Mr};_r=mr.reducer(fr,M,void 0,vr)}catch(Mr){const vr=`Failed to apply action to document:
16
+ Action type: ${M.type}
17
+ Document ID: ${e.documentId}
18
+ Document type: ${fr.header.documentType}
19
+ Scope: ${e.scope}
20
+ Original error: ${Mr instanceof Error?Mr.message:String(Mr)}`,Sr=new Error(vr);return Mr instanceof Error&&Mr.stack&&(Sr.stack=`${vr}
21
+
22
+ Original stack trace:
23
+ ${Mr.stack}`),buildErrorResult(e,Sr,tr)}const gr=e.scope,wr=_r.operations[gr];if(wr.length===0)return buildErrorResult(e,new Error("No operation generated from action"),tr);const yr=wr[wr.length-1];isUndoRedo(M)||(yr.skip=ir);const br=JSON.stringify({..._r.state,header:_r.header});try{await this.operationStore.apply(e.documentId,fr.header.documentType,gr,e.branch,yr.index,Mr=>{Mr.addOperations(yr)})}catch(Mr){return this.logger.error("Error writing @Operation to IOperationStore: @Error",yr,Mr),this.writeCache.invalidate(e.documentId,gr,e.branch),{job:e,success:!1,error:new Error(`Failed to write operation to IOperationStore: ${Mr instanceof Error?Mr.message:String(Mr)}`),duration:Date.now()-tr}}return _r.header.revision={..._r.header.revision,[gr]:yr.index+1},this.writeCache.putState(e.documentId,gr,e.branch,yr.index,_r),rr.write([{...yr,documentId:e.documentId,documentType:fr.header.documentType,branch:e.branch,scope:gr,sourceRemote:dr}]),{job:e,success:!0,operations:[yr],operationsWithContext:[{operation:yr,context:{documentId:e.documentId,scope:gr,branch:e.branch,documentType:fr.header.documentType,resultingState:br,ordinal:0}}],duration:Date.now()-tr}}async executeLoadJob(e,M,tr){if(e.operations.length===0)return buildErrorResult(e,new Error("Load job must include at least one operation"),M);const rr=e.scope;let ir=0;try{ir=(await this.operationStore.getRevisions(e.documentId,e.branch)).revision[rr]??0}catch{ir=0}let lr=Number.POSITIVE_INFINITY,dr=e.operations[0]?.timestampUtcMs||"";for(const Dr of e.operations){lr=Math.min(lr,Dr.index);const Ir=Dr.timestampUtcMs||"";Ir<dr&&(dr=Ir)}let hr=[];try{const Dr=await this.operationStore.getConflicting(e.documentId,rr,e.branch,dr,{cursor:"0",limit:this.config.maxSkipThreshold+1});if(Dr.nextCursor!==void 0)return{job:e,success:!1,error:new Error(`Excessive reshuffle detected: more than ${this.config.maxSkipThreshold} conflicting operations found. This indicates a significant divergence between local and incoming operations.`),duration:Date.now()-M};hr=Dr.results}catch{hr=[]}let fr=hr;if(hr.length>0){const Dr=Math.min(...hr.map(Ir=>Ir.index));try{fr=(await this.operationStore.getSince(e.documentId,rr,e.branch,Dr-1,void 0,{cursor:"0",limit:this.config.maxSkipThreshold*2})).results}catch{fr=hr}}const mr=hr.filter(Dr=>{for(const Ir of fr)if(Ir.index>Dr.index&&Ir.skip>0&&Ir.index-Ir.skip<=Dr.index)return!1;return!0}),_r=mr,gr=_r.length;if(gr>this.config.maxSkipThreshold)return{job:e,success:!1,error:new Error(`Excessive reshuffle detected: skip count of ${gr} exceeds threshold of ${this.config.maxSkipThreshold}. This indicates a significant divergence between local and incoming operations.`),duration:Date.now()-M};const wr=new Set(mr.map(Dr=>Dr.action.id)),yr=new Set,br=e.operations.filter(Dr=>wr.has(Dr.action.id)||yr.has(Dr.action.id)?!1:(yr.add(Dr.action.id),!0));if(br.length===0)return{job:e,success:!0,operations:[],operationsWithContext:[],duration:Date.now()-M};const Mr=reshuffleByTimestamp({index:ir,skip:gr},_r,br.map(Dr=>({...Dr,id:Dr.id})));for(const Dr of Mr)Dr.action.type==="NOOP"&&(Dr.skip=1);const vr=Mr.map(Dr=>Dr.action),Sr=Mr.map(Dr=>Dr.skip),xr=gr>0?"":e.meta.sourceRemote||"",Ar=await this.processActions(e,vr,M,tr,Sr,Mr,xr);return Ar.success?(this.writeCache.invalidate(e.documentId,rr,e.branch),rr==="document"&&this.documentMetaCache.invalidate(e.documentId,e.branch),{job:e,success:!0,operations:Ar.generatedOperations,operationsWithContext:Ar.operationsWithContext,duration:Date.now()-M}):{job:e,success:!1,error:Ar.error,duration:Date.now()-M}}accumulateResultOrReturnError(e,M,tr){return e.success?(e.operations&&e.operations.length>0&&M.push(...e.operations),e.operationsWithContext&&tr.push(...e.operationsWithContext),null):e}}class InMemoryJobTracker{eventBus;jobs=new Map;unsubscribers=[];constructor(e){this.eventBus=e,this.subscribeToEvents()}subscribeToEvents(){this.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY,(e,M)=>{this.handleWriteReady(M)})),this.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_READ_READY,(e,M)=>{this.handleReadReady(M)})),this.unsubscribers.push(this.eventBus.subscribe(ReactorEventTypes.JOB_FAILED,(e,M)=>{this.handleJobFailed(M)}))}handleWriteReady(e){const M=e.jobId,tr=this.jobs.get(M);if(tr&&tr.status===JobStatus.RUNNING){const rr=createConsistencyToken(e.operations);this.jobs.set(M,{...tr,status:JobStatus.WRITE_READY,consistencyToken:rr})}}handleReadReady(e){const M=e.jobId,tr=this.jobs.get(M);tr&&tr.status===JobStatus.WRITE_READY&&this.jobs.set(M,{...tr,status:JobStatus.READ_READY})}handleJobFailed(e){this.markFailed(e.jobId,{message:e.error.message,stack:e.error.stack||""},e.job)}shutdown(){for(const e of this.unsubscribers)e();this.unsubscribers=[]}registerJob(e){this.jobs.set(e.id,{...e})}markRunning(e){const M=this.jobs.get(e);if(!M){this.jobs.set(e,{id:e,status:JobStatus.RUNNING,createdAtUtcIso:new Date().toISOString(),consistencyToken:createEmptyConsistencyToken(),meta:{batchId:e,batchJobIds:[e]}});return}this.jobs.set(e,{...M,status:JobStatus.RUNNING})}markFailed(e,M,tr){const rr=this.jobs.get(e);if(!rr){this.jobs.set(e,{id:e,status:JobStatus.FAILED,createdAtUtcIso:new Date().toISOString(),completedAtUtcIso:new Date().toISOString(),error:M,job:tr,consistencyToken:createEmptyConsistencyToken(),meta:{batchId:e,batchJobIds:[e]}});return}this.jobs.set(e,{...rr,status:JobStatus.FAILED,completedAtUtcIso:new Date().toISOString(),error:M,job:tr,consistencyToken:createEmptyConsistencyToken()})}getJobStatus(e){const M=this.jobs.get(e);return M?{...M}:null}}class BaseReadModel{db;operationIndex;writeCache;consistencyTracker;readModelId;lastOrdinal=0;constructor(e,M,tr,rr,ir){this.db=e,this.operationIndex=M,this.writeCache=tr,this.consistencyTracker=rr,this.readModelId=ir}async init(){const e=await this.loadState();if(e!==void 0){this.lastOrdinal=e;const M=await this.operationIndex.getSinceOrdinal(this.lastOrdinal);if(M.results.length>0){const tr=await this.rebuildStateForOperations(M.results);await this.indexOperations(tr)}}else{await this.initializeState();const M=await this.operationIndex.getSinceOrdinal(0);if(M.results.length>0){const tr=await this.rebuildStateForOperations(M.results);await this.indexOperations(tr)}}}async indexOperations(e){e.length!==0&&(await this.db.transaction().execute(async M=>{await this.saveState(M,e)}),this.updateConsistencyTracker(e))}async waitForConsistency(e,M,tr){e.coordinates.length!==0&&await this.consistencyTracker.waitFor(e.coordinates,M,tr)}async rebuildStateForOperations(e){const M=[];for(const tr of e){const{documentId:rr,scope:ir,branch:lr}=tr.context,dr=tr.operation.index,hr=await this.writeCache.getState(rr,ir,lr,dr);M.push({operation:tr.operation,context:{...tr.context,resultingState:JSON.stringify(hr)}})}return M}async loadState(){return(await this.db.selectFrom("ViewState").select("lastOrdinal").where("readModelId","=",this.readModelId).executeTakeFirst())?.lastOrdinal}async initializeState(){await this.db.insertInto("ViewState").values({readModelId:this.readModelId,lastOrdinal:0}).execute()}async saveState(e,M){const tr=Math.max(...M.map(rr=>rr.context.ordinal));this.lastOrdinal=tr,await e.updateTable("ViewState").set({lastOrdinal:tr,lastOperationTimestamp:new Date}).where("readModelId","=",this.readModelId).execute()}updateConsistencyTracker(e){const M=[];for(let tr=0;tr<e.length;tr++){const rr=e[tr];M.push({documentId:rr.context.documentId,scope:rr.context.scope,branch:rr.context.branch,operationIndex:rr.operation.index})}this.consistencyTracker.update(M)}}const DRIVE_DOCUMENT_TYPE="powerhouse/document-drive";function isDriveCreation(r){return r.operation.action.type==="CREATE_DOCUMENT"&&r.context.documentType===DRIVE_DOCUMENT_TYPE}function isDriveDeletion(r){return r.operation.action.type==="DELETE_DOCUMENT"}function extractDriveHeader(r){return r.context.resultingState?JSON.parse(r.context.resultingState).header:void 0}function extractDeletedDocumentId(r){return r.operation.action.input.documentId??r.context.documentId}function createMinimalDriveHeader(r){return{id:r,documentType:DRIVE_DOCUMENT_TYPE,sig:{publicKey:{},nonce:""},slug:"",name:"",branch:"main",revision:{},createdAtUtcIso:new Date().toISOString(),lastModifiedAtUtcIso:new Date().toISOString()}}function matchesFilter(r,e){return!(e.documentType&&e.documentType.length>0&&!e.documentType.includes(r.context.documentType)||e.scope&&e.scope.length>0&&!e.scope.includes(r.context.scope)||e.branch&&e.branch.length>0&&!e.branch.includes(r.context.branch)||e.documentId&&e.documentId.length>0&&!e.documentId.includes("*")&&!e.documentId.includes(r.context.documentId))}class ProcessorManager extends BaseReadModel{factoryRegistry=new Map;processorsByDrive=new Map;factoryToProcessors=new Map;knownDriveIds=new Set;constructor(e,M,tr,rr){super(e,M,tr,rr,"processor-manager")}async indexOperations(e){e.length!==0&&(await this.detectAndRegisterNewDrives(e),await this.detectAndCleanupDeletedDrives(e),await this.routeOperationsToProcessors(e),await this.db.transaction().execute(async M=>{await this.saveState(M,e)}),this.updateConsistencyTracker(e))}async registerFactory(e,M){this.factoryRegistry.has(e)&&await this.unregisterFactory(e),this.factoryRegistry.set(e,M),this.factoryToProcessors.set(e,new Map);for(const tr of this.knownDriveIds){const rr=createMinimalDriveHeader(tr);await this.createProcessorsForDrive(tr,e,M,rr)}}async unregisterFactory(e){const M=this.factoryToProcessors.get(e);if(M){for(const[tr,rr]of M){for(const lr of rr)await this.safeDisconnect(lr.processor);const ir=this.processorsByDrive.get(tr);if(ir){const lr=ir.filter(dr=>!rr.includes(dr));lr.length>0?this.processorsByDrive.set(tr,lr):this.processorsByDrive.delete(tr)}}this.factoryToProcessors.delete(e),this.factoryRegistry.delete(e)}}getFactoryIdentifiers(){return Array.from(this.factoryRegistry.keys())}getProcessorsForDrive(e){return this.processorsByDrive.get(e)??[]}async detectAndRegisterNewDrives(e){for(const M of e){if(!isDriveCreation(M))continue;const tr=M.context.documentId;if(this.knownDriveIds.has(tr))continue;this.knownDriveIds.add(tr);const rr=extractDriveHeader(M);if(rr)for(const[ir,lr]of this.factoryRegistry)await this.createProcessorsForDrive(tr,ir,lr,rr)}}async detectAndCleanupDeletedDrives(e){for(const M of e){if(!isDriveDeletion(M))continue;const tr=extractDeletedDocumentId(M);!tr||!this.knownDriveIds.has(tr)||this.isDeletedDocumentADrive(tr)&&(await this.cleanupDriveProcessors(tr),this.knownDriveIds.delete(tr))}}isDeletedDocumentADrive(e){return this.knownDriveIds.has(e)}async createProcessorsForDrive(e,M,tr,rr){let ir=[];try{ir=await tr(rr)}catch(hr){console.error(`ProcessorManager: Factory '${M}' failed for drive '${e}':`,hr);return}if(ir.length===0)return;const lr=this.factoryToProcessors.get(M);lr&&lr.set(e,ir);const dr=this.processorsByDrive.get(e)??[];this.processorsByDrive.set(e,[...dr,...ir])}async cleanupDriveProcessors(e){const M=this.processorsByDrive.get(e);if(M){for(const tr of M)await this.safeDisconnect(tr.processor);this.processorsByDrive.delete(e);for(const tr of this.factoryToProcessors.values())tr.delete(e)}}async safeDisconnect(e){try{await e.onDisconnect()}catch(M){console.error("ProcessorManager: Error disconnecting processor:",M)}}async routeOperationsToProcessors(e){const M=new Map;for(const[,tr]of this.processorsByDrive)for(const{processor:rr,filter:ir}of tr){const lr=e.filter(hr=>matchesFilter(hr,ir));if(lr.length===0)continue;const dr=M.get(rr)??[];M.set(rr,[...dr,...lr])}await Promise.all(Array.from(M.entries()).map(async([tr,rr])=>{try{await tr.onOperations(rr)}catch(ir){console.error("ProcessorManager: Error in processor.onOperations:",ir)}}))}}class ModuleNotFoundError extends Error{constructor(e,M){const tr=M!==void 0?` version ${M}`:"";super(`Document model module not found for type: ${e}${tr}`),this.name="ModuleNotFoundError"}static isError(e){return Error.isError(e)&&e.name==="ModuleNotFoundError"}}class DuplicateModuleError extends Error{constructor(e,M){const tr=M!==void 0?` (version ${M})`:"";super(`Document model module already registered for type: ${e}${tr}`),this.name="DuplicateModuleError"}static isError(e){return Error.isError(e)&&e.name==="DuplicateModuleError"}}class DuplicateManifestError extends Error{constructor(e){super(`Upgrade manifest already registered for type: ${e}`),this.name="DuplicateManifestError"}}class ManifestNotFoundError extends Error{constructor(e){super(`Upgrade manifest not found for type: ${e}`),this.name="ManifestNotFoundError"}}class DowngradeNotSupportedError extends Error{constructor(e,M,tr){super(`Downgrade not supported for ${e}: cannot go from version ${M} to ${tr}`),this.name="DowngradeNotSupportedError"}}class MissingUpgradeTransitionError extends Error{constructor(e,M,tr){super(`Missing upgrade transition for ${e}: v${M} to v${tr}`),this.name="MissingUpgradeTransitionError"}}class InvalidUpgradeStepError extends Error{constructor(e,M,tr){super(`Invalid upgrade step for ${e}: must be single version increment, got v${M} to v${tr}`),this.name="InvalidUpgradeStepError"}}class DocumentModelRegistry{modules=[];manifests=[];registerModules(...e){for(const M of e){const tr=M.documentModel.global.id,rr=M.version??1;for(let ir=0;ir<this.modules.length;ir++){const lr=this.modules[ir],dr=lr.documentModel.global.id,hr=lr.version??1;if(dr===tr&&hr===rr)throw new DuplicateModuleError(tr,rr)}this.modules.push(M)}}unregisterModules(...e){let M=!0;for(const tr of e)this.modules.some(ir=>ir.documentModel.global.id===tr)||(M=!1),this.modules=this.modules.filter(ir=>ir.documentModel.global.id!==tr);return M}getModule(e,M){let tr,rr=-1;for(let ir=0;ir<this.modules.length;ir++){const lr=this.modules[ir],dr=lr.documentModel.global.id,hr=lr.version??1;if(dr===e){if(M!==void 0&&hr===M)return lr;hr>rr&&(tr=lr,rr=hr)}}if(M===void 0&&tr!==void 0)return tr;throw new ModuleNotFoundError(e,M)}getAllModules(){return[...this.modules]}clear(){this.modules=[],this.manifests=[]}getSupportedVersions(e){const M=[];for(const tr of this.modules)tr.documentModel.global.id===e&&M.push(tr.version??1);if(M.length===0)throw new ModuleNotFoundError(e);return M.sort((tr,rr)=>tr-rr)}getLatestVersion(e){let M=-1,tr=!1;for(const rr of this.modules)if(rr.documentModel.global.id===e){tr=!0;const ir=rr.version??1;ir>M&&(M=ir)}if(!tr)throw new ModuleNotFoundError(e);return M}registerUpgradeManifests(...e){for(const M of e){for(let tr=0;tr<this.manifests.length;tr++)if(this.manifests[tr].documentType===M.documentType)throw new DuplicateManifestError(M.documentType);this.manifests.push(M)}}getUpgradeManifest(e){for(let M=0;M<this.manifests.length;M++)if(this.manifests[M].documentType===e)return this.manifests[M];throw new ManifestNotFoundError(e)}computeUpgradePath(e,M,tr){if(M===tr)return[];if(tr<M)throw new DowngradeNotSupportedError(e,M,tr);const rr=this.getUpgradeManifest(e),ir=[];for(let lr=M+1;lr<=tr;lr++){const dr=`v${lr}`;if(!(dr in rr.upgrades))throw new MissingUpgradeTransitionError(e,lr-1,lr);const hr=rr.upgrades[dr];ir.push(hr)}return ir}getUpgradeReducer(e,M,tr){if(tr!==M+1)throw new InvalidUpgradeStepError(e,M,tr);const rr=this.getUpgradeManifest(e),ir=`v${tr}`;if(!(ir in rr.upgrades))throw new MissingUpgradeTransitionError(e,M,tr);return rr.upgrades[ir].upgradeReducer}}class JobExecutionHandle{_state;_job;onStart;onComplete;onFail;getStateName(e){switch(e){case JobQueueState.PREPROCESSING:return"PREPROCESSING";case JobQueueState.PENDING:return"PENDING";case JobQueueState.READY:return"READY";case JobQueueState.RUNNING:return"RUNNING";case JobQueueState.RESOLVED:return"RESOLVED";default:return"UNKNOWN"}}constructor(e,M,tr){this._job=e,this._state=M,this.onStart=tr?.onStart,this.onComplete=tr?.onComplete,this.onFail=tr?.onFail}get job(){return this._job}get state(){return this._state}start(){if(this._state!==JobQueueState.READY)throw new Error(`Cannot start job in state ${this.getStateName(this._state)}`);this._state=JobQueueState.RUNNING,this.onStart?.()}complete(){if(this._state!==JobQueueState.RUNNING)throw new Error(`Cannot complete job in state ${this.getStateName(this._state)}`);this._state=JobQueueState.RESOLVED,this.onComplete?.()}fail(e){if(this._state!==JobQueueState.RUNNING)throw new Error(`Cannot fail job in state ${this.getStateName(this._state)}`);this._state=JobQueueState.RESOLVED,this.onFail?.(e)}}class InMemoryQueue{eventBus;registry;loader;queues=new Map;jobIdToQueueKey=new Map;docIdToJobId=new Map;jobIdToDocId=new Map;completedJobs=new Set;jobIndex=new Map;isBlocked=!1;onDrainedCallback;isPausedFlag=!1;loadingModels=new Map;failedModelTypes=new Set;constructor(e,M,tr){this.eventBus=e,this.registry=M,this.loader=tr}toErrorInfo(e){return e instanceof Error?{message:e.message,stack:e.stack||new Error().stack||""}:{message:e,stack:new Error().stack||""}}createQueueKey(e,M,tr){return`${e}:${M}:${tr}`}getQueue(e){let M=this.queues.get(e);return M||(M=[],this.queues.set(e,M)),M}isDocumentExecuting(e){const M=this.docIdToJobId.get(e);return M?M.size>0:!1}markJobExecuting(e){let M=this.docIdToJobId.get(e.documentId);M||(M=new Set,this.docIdToJobId.set(e.documentId,M)),M.add(e.id),this.jobIdToDocId.set(e.id,e.documentId)}markJobComplete(e,M){const tr=this.docIdToJobId.get(M);tr&&(tr.delete(e),tr.size===0&&this.docIdToJobId.delete(M)),this.jobIdToDocId.delete(e)}areDependenciesMet(e){return e.queueHint.length===0?!0:e.queueHint.every(M=>this.completedJobs.has(M))}getNextJobWithMetDependencies(e){for(const M of e)if(this.areDependenciesMet(M))return M;return null}getCreateDocumentType(e){for(const M of e.actions)if(M.type==="CREATE_DOCUMENT")return M.input.model;for(const M of e.operations)if(M.action.type==="CREATE_DOCUMENT")return M.action.input.model}async ensureModelLoaded(e){if(!this.registry)return;try{this.registry.getModule(e);return}catch(rr){if(!ModuleNotFoundError.isError(rr))throw rr}if(!this.loader)throw new Error(`No document model loader configured for type: ${e}`);if(this.failedModelTypes.has(e))throw new Error(`Document model type previously failed to load: ${e}`);const M=this.loadingModels.get(e);if(M)return M;const tr=(async()=>{try{const rr=await this.loader.load(e);try{this.registry.registerModules(rr)}catch{}}catch(rr){throw this.failedModelTypes.add(e),rr}finally{this.loadingModels.delete(e)}})();return this.loadingModels.set(e,tr),tr}async enqueue(e){if(this.isBlocked)throw new Error("Queue is blocked");const M=this.createQueueKey(e.documentId,e.scope,e.branch);this.getQueue(M).push(e),this.jobIdToQueueKey.set(e.id,M),this.jobIndex.set(e.id,e);const rr=this.getCreateDocumentType(e);if(rr)try{await this.ensureModelLoaded(rr)}catch{await this.failJob(e.id,{message:`Failed to load document model for type: ${rr}`,stack:new Error().stack||""});return}const ir={documentId:e.documentId,scope:e.scope,branch:e.branch,jobId:e.id};await this.eventBus.emit(QueueEventTypes.JOB_AVAILABLE,ir)}dequeue(e,M,tr,rr){const ir=this.createQueueKey(e,M,tr),lr=this.queues.get(ir);if(rr?.aborted)return Promise.reject(new Error("Operation aborted"));if(!lr||lr.length===0)return Promise.resolve(null);const dr=this.getNextJobWithMetDependencies(lr);if(!dr)return Promise.resolve(null);const hr=lr.indexOf(dr);lr.splice(hr,1),this.jobIdToQueueKey.delete(dr.id),this.markJobExecuting(dr),lr.length===0&&this.queues.delete(ir);const fr=new JobExecutionHandle(dr,JobQueueState.READY,{onStart:()=>{},onComplete:()=>{this.completeJob(dr.id)},onFail:mr=>{this.failJob(dr.id,mr)}});return Promise.resolve(fr)}dequeueNext(e){if(e?.aborted)return Promise.reject(new Error("Operation aborted"));if(this.isPausedFlag)return Promise.resolve(null);for(const[M,tr]of this.queues.entries())if(tr.length>0){const rr=this.getNextJobWithMetDependencies(tr);if(!rr)continue;if(!this.isDocumentExecuting(rr.documentId)){const ir=tr.indexOf(rr);tr.splice(ir,1),this.jobIdToQueueKey.delete(rr.id),this.markJobExecuting(rr),tr.length===0&&this.queues.delete(M);const lr=new JobExecutionHandle(rr,JobQueueState.READY,{onStart:()=>{},onComplete:()=>{this.completeJob(rr.id)},onFail:dr=>{this.failJob(rr.id,dr)}});return Promise.resolve(lr)}}return Promise.resolve(null)}size(e,M,tr){const rr=this.createQueueKey(e,M,tr),ir=this.queues.get(rr);return Promise.resolve(ir?ir.length:0)}totalSize(){let e=0;for(const M of this.queues.values())e+=M.length;return Promise.resolve(e)}remove(e){const M=this.jobIdToQueueKey.get(e);if(!M)return Promise.resolve(!1);const tr=this.queues.get(M);if(!tr)return this.jobIdToQueueKey.delete(e),this.jobIndex.delete(e),Promise.resolve(!1);const rr=tr.findIndex(ir=>ir.id===e);return rr===-1?(this.jobIdToQueueKey.delete(e),this.jobIndex.delete(e),Promise.resolve(!1)):(tr.splice(rr,1),this.jobIdToQueueKey.delete(e),this.jobIndex.delete(e),tr.length===0&&this.queues.delete(M),Promise.resolve(!0))}clear(e,M,tr){const rr=this.createQueueKey(e,M,tr),ir=this.queues.get(rr);if(ir){for(const lr of ir)this.jobIdToQueueKey.delete(lr.id),this.jobIndex.delete(lr.id);this.queues.delete(rr)}return Promise.resolve()}clearAll(){return this.jobIdToQueueKey.clear(),this.jobIndex.clear(),this.completedJobs.clear(),this.queues.clear(),Promise.resolve()}hasJobs(){return Promise.resolve(this.queues.size>0&&Array.from(this.queues.values()).some(e=>e.length>0))}async completeJob(e){const M=this.jobIdToDocId.get(e);M&&this.markJobComplete(e,M),this.completedJobs.add(e),this.jobIndex.delete(e),await this.remove(e),this.checkDrained()}async failJob(e,M){const tr=this.jobIdToDocId.get(e);tr&&this.markJobComplete(e,tr);const rr=this.jobIndex.get(e);rr&&(rr.lastError=M,M&&rr.errorHistory.push(M)),this.jobIndex.delete(e),await this.remove(e),this.checkDrained()}async retryJob(e,M){const tr=this.jobIndex.get(e);if(!tr)return;tr.lastError=M;const rr=this.jobIdToDocId.get(e);rr&&this.markJobComplete(e,rr),this.jobIndex.delete(e),this.jobIdToQueueKey.delete(e),M&&tr.errorHistory.push(M);const ir={...tr,retryCount:(tr.retryCount||0)+1,lastError:M};await this.enqueue(ir)}checkDrained(){if(this.isDrained&&this.onDrainedCallback){const e=this.onDrainedCallback;this.onDrainedCallback=void 0,e()}}get isDrained(){const e=this.queues.size>0&&Array.from(this.queues.values()).some(tr=>tr.length>0),M=this.docIdToJobId.size>0&&Array.from(this.docIdToJobId.values()).some(tr=>tr.size>0);return!e&&!M}block(e){this.isBlocked=!0,this.onDrainedCallback=e,this.checkDrained()}unblock(){this.isBlocked=!1,this.onDrainedCallback=void 0}pause(){this.isPausedFlag=!0}async resume(){this.isPausedFlag=!1;for(const[,e]of this.queues.entries())if(e.length>0){const M=e[0];await this.eventBus.emit(QueueEventTypes.JOB_AVAILABLE,{documentId:M.documentId,scope:M.scope,branch:M.branch,jobId:M.id})}}get paused(){return this.isPausedFlag}getPendingJobs(){const e=[];for(const M of this.queues.values())e.push(...M);return e}getExecutingJobIds(){return new Map(Array.from(this.docIdToJobId.entries()).map(([e,M])=>[e,new Set(M)]))}getJob(e){return this.jobIndex.get(e)}}class ReadModelCoordinator{eventBus;preReady;postReady;unsubscribe;isRunning=!1;constructor(e,M,tr){this.eventBus=e,this.preReady=M,this.postReady=tr}start(){this.isRunning||(this.unsubscribe=this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY,async(e,M)=>{await this.handleWriteReady(M)}),this.isRunning=!0)}stop(){this.isRunning&&(this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0),this.isRunning=!1)}async handleWriteReady(e){await Promise.all(this.preReady.map(tr=>tr.indexOperations(e.operations)));const M={jobId:e.jobId,operations:e.operations};await this.eventBus.emit(ReactorEventTypes.JOB_READ_READY,M),await Promise.all(this.postReady.map(tr=>tr.indexOperations(e.operations)))}}class KyselyDocumentView extends BaseReadModel{operationStore;_db;constructor(e,M,tr,rr,ir){super(e,tr,rr,ir,"document-view"),this.operationStore=M,this._db=e}async indexOperations(e){e.length!==0&&(await this._db.transaction().execute(async M=>{for(const tr of e){const{operation:rr,context:ir}=tr,{documentId:lr,scope:dr,branch:hr,documentType:fr,resultingState:mr}=ir,{index:_r,hash:gr}=rr;if(!mr)throw new Error(`Missing resultingState in context for operation ${rr.id||"unknown"}. IDocumentView requires resultingState from upstream - it does not rebuild documents.`);let wr={};try{wr=JSON.parse(mr)}catch(Mr){throw new Error(`Failed to parse resultingState for operation ${rr.id||"unknown"}: ${Mr instanceof Error?Mr.message:String(Mr)}`)}const yr=rr.action.type;let br;if(yr==="CREATE_DOCUMENT")br=Object.entries(wr).filter(([Mr])=>Mr==="header"||Mr==="document"||Mr==="auth");else if(yr==="UPGRADE_DOCUMENT"){const Mr=[];for(const[vr,Sr]of Object.entries(wr)){if(vr==="header"){Mr.push([vr,Sr]);continue}if(vr===dr){Mr.push([vr,Sr]);continue}await M.selectFrom("DocumentSnapshot").select("scope").where("documentId","=",lr).where("scope","=",vr).where("branch","=",hr).executeTakeFirst()||Mr.push([vr,Sr])}br=Mr}else br=[],wr.header!==void 0&&br.push(["header",wr.header]),wr[dr]!==void 0?br.push([dr,wr[dr]]):br.push([dr,{}]);for(const[Mr,vr]of br){const Sr=await M.selectFrom("DocumentSnapshot").selectAll().where("documentId","=",lr).where("scope","=",Mr).where("branch","=",hr).executeTakeFirst(),xr=typeof vr=="object"&&vr!==null?vr:{};let Ar=Sr?.slug??null,Dr=Sr?.name??null;if(Mr==="header"){const Ir=xr.slug,kr=xr.name;typeof Ir=="string"&&(Ar=Ir),typeof kr=="string"&&(Dr=kr),Ar&&Ar!==lr&&await M.insertInto("SlugMapping").values({slug:Ar,documentId:lr,scope:Mr,branch:hr}).onConflict(Or=>Or.column("slug").doUpdateSet({documentId:lr,scope:Mr,branch:hr})).execute()}if(Sr)await M.updateTable("DocumentSnapshot").set({lastOperationIndex:_r,lastOperationHash:gr,lastUpdatedAt:new Date,snapshotVersion:Sr.snapshotVersion+1,content:xr,slug:Ar,name:Dr}).where("documentId","=",lr).where("scope","=",Mr).where("branch","=",hr).execute();else{const Ir={id:v4(),documentId:lr,slug:Ar,name:Dr,scope:Mr,branch:hr,content:xr,documentType:fr,lastOperationIndex:_r,lastOperationHash:gr,identifiers:null,metadata:null,deletedAt:null};await M.insertInto("DocumentSnapshot").values(Ir).execute()}}}await this.saveState(M,e)}),this.updateConsistencyTracker(e))}async exists(e,M,tr){if(M&&await this.waitForConsistency(M,void 0,tr),tr?.aborted)throw new Error("Operation aborted");if(e.length===0)return[];const rr=await this._db.selectFrom("DocumentSnapshot").select(["documentId"]).where("documentId","in",e).where("isDeleted","=",!1).distinct().execute(),ir=new Set(rr.map(lr=>lr.documentId));return e.map(lr=>ir.has(lr))}async get(e,M,tr,rr){if(tr&&await this.waitForConsistency(tr,void 0,rr),rr?.aborted)throw new Error("Operation aborted");const ir=M?.branch||"main";let lr;M?.scopes&&M.scopes.length>0?lr=[...new Set(["header","document",...M.scopes])]:lr=[];let dr=this._db.selectFrom("DocumentSnapshot").selectAll().where("documentId","=",e).where("branch","=",ir).where("isDeleted","=",!1);lr.length>0&&(dr=dr.where("scope","in",lr));const hr=await dr.execute();if(hr.length===0)throw new Error(`Document not found: ${e}`);if(rr?.aborted)throw new Error("Operation aborted");const fr=hr.find(yr=>yr.scope==="header");if(!fr)throw new Error(`Document header not found: ${e}`);const mr=fr.content,_r=await this.operationStore.getRevisions(e,ir,rr);mr.revision=_r.revision,mr.lastModifiedAtUtcIso=_r.latestTimestamp;const gr={};for(const yr of hr)yr.scope!=="header"&&(gr[yr.scope]=yr.content);return{header:mr,state:gr,operations:{},initialState:gr,clipboard:[]}}async getMany(e,M,tr,rr){if(e.length===0)return[];if(tr&&await this.waitForConsistency(tr,void 0,rr),rr?.aborted)throw new Error("Operation aborted");const ir=M?.branch||"main";let lr;M?.scopes&&M.scopes.length>0?lr=[...new Set(["header","document",...M.scopes])]:lr=[];let dr=this._db.selectFrom("DocumentSnapshot").selectAll().where("documentId","in",e).where("branch","=",ir).where("isDeleted","=",!1);lr.length>0&&(dr=dr.where("scope","in",lr));const hr=await dr.execute();if(rr?.aborted)throw new Error("Operation aborted");const fr=new Map;for(const yr of hr){const br=fr.get(yr.documentId)||[];br.push(yr),fr.set(yr.documentId,br)}const mr=[...fr.keys()],_r=await Promise.all(mr.map(yr=>this.operationStore.getRevisions(yr,ir,rr))),gr=new Map;for(let yr=0;yr<mr.length;yr++)gr.set(mr[yr],_r[yr]);if(rr?.aborted)throw new Error("Operation aborted");const wr=[];for(const yr of e){const br=fr.get(yr);if(!br||br.length===0)continue;const Mr=br.find(Dr=>Dr.scope==="header");if(!Mr)continue;const vr=Mr.content,Sr=gr.get(yr);Sr&&(vr.revision=Sr.revision,vr.lastModifiedAtUtcIso=Sr.latestTimestamp);const xr={};for(const Dr of br)Dr.scope!=="header"&&(xr[Dr.scope]=Dr.content);const Ar={header:vr,state:xr,operations:{},initialState:xr,clipboard:[]};wr.push(Ar)}return wr}async getByIdOrSlug(e,M,tr,rr){const ir=await this.resolveIdOrSlug(e,M,tr,rr);return this.get(ir,M,void 0,rr)}async findByType(e,M,tr,rr,ir){if(rr&&await this.waitForConsistency(rr,void 0,ir),ir?.aborted)throw new Error("Operation aborted");const lr=M?.branch||"main",dr=tr?.cursor?parseInt(tr.cursor):0,hr=tr?.limit||100,fr=[],mr=new Set,_r=[],gr=await this._db.selectFrom("DocumentSnapshot").selectAll().where("documentType","=",e).where("branch","=",lr).where("isDeleted","=",!1).orderBy("lastUpdatedAt","desc").execute();if(ir?.aborted)throw new Error("Operation aborted");for(const Mr of gr)mr.has(Mr.documentId)||(mr.add(Mr.documentId),_r.push(Mr.documentId));const wr=_r.slice(dr,dr+hr);for(const Mr of wr){if(ir?.aborted)throw new Error("Operation aborted");try{const vr=await this.get(Mr,M,void 0,ir);fr.push(vr)}catch{continue}}const yr=_r.length>dr+hr,br=yr?String(dr+hr):void 0;return{results:fr,options:tr||{cursor:"0",limit:100},nextCursor:br,totalCount:_r.length,next:yr?()=>this.findByType(e,M,{cursor:br,limit:hr},rr,ir):void 0}}async resolveSlug(e,M,tr,rr){if(tr&&await this.waitForConsistency(tr,void 0,rr),rr?.aborted)throw new Error("Operation aborted");const ir=M?.branch||"main",lr=await this._db.selectFrom("SlugMapping").select("documentId").where("slug","=",e).where("branch","=",ir).executeTakeFirst();if(lr){if(rr?.aborted)throw new Error("Operation aborted");if(!(M?.scopes&&M.scopes.length>0&&!await this._db.selectFrom("DocumentSnapshot").select("scope").where("documentId","=",lr.documentId).where("branch","=",ir).where("scope","in",M.scopes).where("isDeleted","=",!1).executeTakeFirst()))return lr.documentId}}async resolveSlugs(e,M,tr,rr){return(await Promise.all(e.map(lr=>this.resolveSlug(lr,M,tr,rr)))).filter(lr=>lr!==void 0)}async resolveIdOrSlug(e,M,tr,rr){if(tr&&await this.waitForConsistency(tr,void 0,rr),rr?.aborted)throw new Error("Operation aborted");const ir=M?.branch||"main",lr=this._db.selectFrom("DocumentSnapshot").select("documentId").where("documentId","=",e).where("branch","=",ir).where("isDeleted","=",!1).executeTakeFirst(),dr=this._db.selectFrom("SlugMapping").select("documentId").where("slug","=",e).where("branch","=",ir).executeTakeFirst(),[hr,fr]=await Promise.all([lr,dr]);if(rr?.aborted)throw new Error("Operation aborted");const mr=hr?.documentId,_r=fr?.documentId;if(mr&&_r&&mr!==_r)throw new Error(`Ambiguous identifier "${e}": matches both document ID "${mr}" and slug for document ID "${_r}". Please use get() for ID or resolveSlug() + get() for slug to be explicit.`);const gr=mr||_r;if(!gr)throw new Error(`Document not found: ${e}`);return gr}}function makeConsistencyKey(r,e,M){return`${r}:${e}:${M}`}class ConsistencyTracker{state=new Map;waiters=[];update(e){const M=this.deduplicateCoordinates(e);for(let tr=0;tr<M.length;tr++){const rr=M[tr],ir=makeConsistencyKey(rr.documentId,rr.scope,rr.branch),lr=this.state.get(ir);(lr===void 0||rr.operationIndex>lr)&&this.state.set(ir,rr.operationIndex)}this.checkWaiters()}getLatest(e){return this.state.get(e)}waitFor(e,M,tr){return tr?.aborted?Promise.reject(new Error("Operation aborted")):this.areCoordinatesSatisfied(e)?Promise.resolve():new Promise((rr,ir)=>{const lr={coordinates:e,resolve:rr,reject:ir,signal:tr};if(M!==void 0&&(lr.timeoutId=setTimeout(()=>{this.removeWaiter(lr),ir(new Error(`Consistency wait timed out after ${M}ms`))},M)),tr){const dr=()=>{this.removeWaiter(lr),ir(new Error("Operation aborted"))};tr.addEventListener("abort",dr,{once:!0})}this.waiters.push(lr)})}serialize(){return Array.from(this.state.entries())}hydrate(e){this.state.clear();for(const[M,tr]of e)this.state.set(M,tr)}deduplicateCoordinates(e){const M=new Map;for(let tr=0;tr<e.length;tr++){const rr=e[tr],ir=makeConsistencyKey(rr.documentId,rr.scope,rr.branch),lr=M.get(ir);(!lr||rr.operationIndex>lr.operationIndex)&&M.set(ir,rr)}return Array.from(M.values())}areCoordinatesSatisfied(e){for(let M=0;M<e.length;M++){const tr=e[M],rr=makeConsistencyKey(tr.documentId,tr.scope,tr.branch),ir=this.state.get(rr);if(ir===void 0||ir<tr.operationIndex)return!1}return!0}checkWaiters(){const e=[],M=[];for(const tr of this.waiters)tr.signal?.aborted||(this.areCoordinatesSatisfied(tr.coordinates)?e.push(tr):M.push(tr));this.waiters=M;for(const tr of e)tr.timeoutId!==void 0&&clearTimeout(tr.timeoutId),tr.resolve()}removeWaiter(e){const M=this.waiters.indexOf(e);M!==-1&&this.waiters.splice(M,1),e.timeoutId!==void 0&&clearTimeout(e.timeoutId)}}var ChannelScheme;(function(r){r.CONNECT="connect",r.SWITCHBOARD="switchboard"})(ChannelScheme||(ChannelScheme={}));var SyncOperationStatus;(function(r){r[r.Unknown=-1]="Unknown",r[r.TransportPending=0]="TransportPending",r[r.ExecutionPending=1]="ExecutionPending",r[r.Applied=2]="Applied",r[r.Error=3]="Error"})(SyncOperationStatus||(SyncOperationStatus={}));var ChannelErrorSource;(function(r){r.None="none",r.Channel="channel",r.Inbox="inbox",r.Outbox="outbox"})(ChannelErrorSource||(ChannelErrorSource={}));const SyncEventTypes={SYNC_SUCCEEDED:20002,SYNC_FAILED:20003};class MailboxAggregateError extends Error{errors;constructor(e){const M=e.map(tr=>tr.message).join("; ");super(`Mailbox callback failed with ${e.length} error(s): ${M}`),this.name="MailboxAggregateError",this.errors=e}}class Mailbox{itemsMap=new Map;addedCallbacks=[];removedCallbacks=[];paused=!1;addedBuffer=[];removedBuffer=[];_ack=0;_latestOrdinal=0;init(e){this._ack=this._latestOrdinal=e}get items(){return Array.from(this.itemsMap.values())}get ackOrdinal(){return this._ack}get latestOrdinal(){return this._latestOrdinal}get(e){return this.itemsMap.get(e)}add(...e){for(const rr of e){this.itemsMap.set(rr.id,rr);for(const ir of rr.operations)this._latestOrdinal=Math.max(this._latestOrdinal,ir.context.ordinal);rr.on((ir,lr,dr)=>{if(dr===SyncOperationStatus.Applied)for(const hr of ir.operations)this._ack=Math.max(this._ack,hr.context.ordinal)})}if(this.paused){this.addedBuffer.push(...e);return}const M=[...this.addedCallbacks],tr=[];for(const rr of M)try{rr(e)}catch(ir){tr.push(ir instanceof Error?ir:new Error(String(ir)))}if(tr.length>0)throw new MailboxAggregateError(tr)}remove(...e){for(const rr of e)this.itemsMap.delete(rr.id);if(this.paused){this.removedBuffer.push(...e);return}const M=[...this.removedCallbacks],tr=[];for(const rr of M)try{rr(e)}catch(ir){tr.push(ir instanceof Error?ir:new Error(String(ir)))}if(tr.length>0)throw new MailboxAggregateError(tr)}onAdded(e){this.addedCallbacks.push(e)}onRemoved(e){this.removedCallbacks.push(e)}pause(){this.paused=!0}resume(){this.paused=!1,this.flush()}flush(){if(this.addedBuffer.length>0){const e=this.addedBuffer.splice(0),M=[...this.addedCallbacks],tr=[];for(const rr of M)try{rr(e)}catch(ir){tr.push(ir instanceof Error?ir:new Error(String(ir)))}if(tr.length>0)throw new MailboxAggregateError(tr)}if(this.removedBuffer.length>0){const e=this.removedBuffer.splice(0),M=[...this.removedCallbacks],tr=[];for(const rr of M)try{rr(e)}catch(ir){tr.push(ir instanceof Error?ir:new Error(String(ir)))}if(tr.length>0)throw new MailboxAggregateError(tr)}}isPaused(){return this.paused}}class BufferedMailbox{itemsMap=new Map;addedCallbacks=[];removedCallbacks=[];addedBuffer=[];removedBuffer=[];addedTimer=null;removedTimer=null;milliseconds;maxQueued;paused=!1;_ack=0;_latestOrdinal=0;constructor(e,M){this.milliseconds=e,this.maxQueued=M}init(e){this._ack=this._latestOrdinal=e}get items(){return Array.from(this.itemsMap.values())}get ackOrdinal(){return this._ack}get latestOrdinal(){return this._latestOrdinal}get(e){return this.itemsMap.get(e)}add(...e){for(const M of e){this.itemsMap.set(M.id,M);for(const tr of M.operations)this._latestOrdinal=Math.max(this._latestOrdinal,tr.context.ordinal);M.on((tr,rr,ir)=>{if(ir===SyncOperationStatus.Applied)for(const lr of tr.operations)this._ack=Math.max(this._ack,lr.context.ordinal)})}this.addedBuffer.push(...e),!this.paused&&(this.addedBuffer.length>=this.maxQueued?this.flushAdded():this.scheduleAddedFlush())}remove(...e){for(const M of e)this.itemsMap.delete(M.id);this.removedBuffer.push(...e),!this.paused&&(this.removedBuffer.length>=this.maxQueued?this.flushRemoved():this.scheduleRemovedFlush())}onAdded(e){this.addedCallbacks.push(e)}onRemoved(e){this.removedCallbacks.push(e)}pause(){this.paused=!0,this.addedTimer!==null&&(clearTimeout(this.addedTimer),this.addedTimer=null),this.removedTimer!==null&&(clearTimeout(this.removedTimer),this.removedTimer=null)}resume(){this.paused=!1,this.addedBuffer.length>0&&this.scheduleAddedFlush(),this.removedBuffer.length>0&&this.scheduleRemovedFlush()}isPaused(){return this.paused}flush(){this.flushAdded(),this.flushRemoved()}scheduleAddedFlush(){this.addedTimer!==null&&clearTimeout(this.addedTimer),this.addedTimer=setTimeout(()=>{this.flushAdded()},this.milliseconds)}scheduleRemovedFlush(){this.removedTimer!==null&&clearTimeout(this.removedTimer),this.removedTimer=setTimeout(()=>{this.flushRemoved()},this.milliseconds)}flushAdded(){this.addedTimer!==null&&(clearTimeout(this.addedTimer),this.addedTimer=null);const e=this.addedBuffer;this.addedBuffer=[],e.length>0&&this.invokeCallbacks(this.addedCallbacks,e)}flushRemoved(){this.removedTimer!==null&&(clearTimeout(this.removedTimer),this.removedTimer=null);const e=this.removedBuffer;this.removedBuffer=[],e.length>0&&this.invokeCallbacks(this.removedCallbacks,e)}invokeCallbacks(e,M){const tr=[...e],rr=[];for(const ir of tr)try{ir(M)}catch(lr){rr.push(lr instanceof Error?lr:new Error(String(lr)))}if(rr.length>0)throw new MailboxAggregateError(rr)}}class ChannelError extends Error{source;error;constructor(e,M){super(`ChannelError[${e}]: ${M.message}`),this.name="ChannelError",this.source=e,this.error=M}}function trimMailboxFromBatch(r,e){const M=[];for(const tr of e.entries)for(const rr of r.items)if(tr.event.jobId===rr.jobId){M.push(rr);break}if(M.length>0){for(const tr of M)tr.executed();r.remove(...M)}}function trimMailboxFromAckOrdinal(r,e){const M=[];for(const tr of r.items){let rr=0;for(const ir of tr.operations)rr=Math.max(rr,ir.context.ordinal);rr<=e&&M.push(tr)}if(M.length>0){for(const tr of M)tr.executed();r.remove(...M)}}function filterOperations(r,e){return r.filter(M=>!(e.branch&&M.context.branch!==e.branch||e.documentId.length>0&&!e.documentId.includes(M.context.documentId)||e.scope.length>0&&!e.scope.includes(M.context.scope)))}function createIdleHealth(){return{state:"idle",failureCount:0}}function sortEnvelopesByFirstOperationTimestamp(r){return r.slice().sort((e,M)=>{const tr=e.operations?.[0]?.operation.timestampUtcMs,rr=M.operations?.[0]?.operation.timestampUtcMs;return!tr&&!rr?0:tr?rr?new Date(tr).getTime()-new Date(rr).getTime():-1:1})}function batchOperationsByDocument(r){const e=[];let M=null,tr=null,rr=[];const ir=()=>{rr.length===0||M===null||tr===null||(e.push({documentId:M,branch:rr[0].context.branch,scope:tr,operations:rr}),rr=[])};for(const lr of r){const dr=lr.context.documentId,hr=lr.context.scope;(dr!==M||hr!==tr)&&(ir(),M=dr,tr=hr),rr.push(lr)}return ir(),e}function toOperationWithContext(r){return{operation:{id:r.id,index:r.index,skip:r.skip,hash:r.hash,timestampUtcMs:r.timestampUtcMs,action:r.action},context:{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,ordinal:r.ordinal??0}}}function mergeCollectionMemberships(r){const e={};for(const M of r){if(M.collectionMemberships)for(const[tr,rr]of Object.entries(M.collectionMemberships)){tr in e||(e[tr]=[]);for(const ir of rr)e[tr].includes(ir)||e[tr].push(ir)}for(const tr of M.operations){const rr=tr.operation.action;if(rr.type!=="ADD_RELATIONSHIP")continue;const ir=rr.input;if(!ir?.sourceId||!ir.targetId)continue;const lr=driveCollectionId(tr.context.branch,ir.sourceId);ir.targetId in e||(e[ir.targetId]=[]),e[ir.targetId].includes(lr)||e[ir.targetId].push(lr)}}return e}const DEFAULT_CONFIG={intervalMs:2e3,maxQueueDepth:100,backpressureCheckIntervalMs:500,retryBaseDelayMs:1e3,retryMaxDelayMs:3e5};function calculateBackoffDelay(r,e,M,tr){const rr=Math.min(M,e*Math.pow(2,r-1));return rr/2+tr*(rr/2)}class IntervalPollTimer{delegate;timer;running;paused;consecutiveFailures;queue;config;constructor(e,M={}){this.queue=e,this.config={...DEFAULT_CONFIG,...M},this.running=!1,this.paused=!1,this.consecutiveFailures=0}setDelegate(e){this.delegate=e}start(){this.running=!0,this.consecutiveFailures=0,this.tick()}stop(){this.running=!1,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}tick(){if(!this.delegate||!this.running)return;const e=this.delegate;this.queue.totalSize().then(M=>{this.running&&(M>this.config.maxQueueDepth?this.scheduleBackpressureRecheck():e().then(()=>{this.consecutiveFailures=0,this.scheduleNext()}).catch(()=>{this.consecutiveFailures++,this.scheduleRetry()}))}).catch(()=>{this.scheduleNext()})}scheduleNext(){!this.running||this.paused||(this.timer=setTimeout(()=>this.tick(),this.config.intervalMs))}scheduleRetry(){if(!this.running||this.paused)return;const e=calculateBackoffDelay(this.consecutiveFailures,this.config.retryBaseDelayMs,this.config.retryMaxDelayMs,Math.random());this.timer=setTimeout(()=>this.tick(),e)}scheduleBackpressureRecheck(){!this.running||this.paused||(this.timer=setTimeout(()=>this.tick(),this.config.backpressureCheckIntervalMs))}pause(){this.paused=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}resume(){this.paused=!1,this.running&&this.scheduleNext()}triggerNow(){this.running&&this.delegate&&this.tick()}isPaused(){return this.paused}isRunning(){return this.running}}class SyncOperationAggregateError extends Error{errors;constructor(e){const M=e.map(tr=>tr.message).join("; ");super(`SyncOperation callback failed with ${e.length} error(s): ${M}`),this.name="SyncOperationAggregateError",this.errors=e}}class SyncOperation{id;jobId;jobDependencies;remoteName;documentId;scopes;branch;operations;status;error;callbacks=[];constructor(e,M,tr,rr,ir,lr,dr,hr){this.id=e,this.jobId=M,this.jobDependencies=tr,this.remoteName=rr,this.documentId=ir,this.scopes=lr,this.branch=dr,this.operations=hr,this.status=SyncOperationStatus.Unknown}on(e){this.callbacks.push(e)}started(){this.transition(SyncOperationStatus.TransportPending)}transported(){this.transition(SyncOperationStatus.ExecutionPending)}executed(){this.transition(SyncOperationStatus.Applied)}failed(e){this.error=e,this.transition(SyncOperationStatus.Error)}transition(e){const M=this.status;if(e<=M)return;this.status=e;const tr=[];for(const rr of this.callbacks)try{rr(this,M,e)}catch(ir){tr.push(ir instanceof Error?ir:new Error(String(ir)))}if(tr.length>0)throw new SyncOperationAggregateError(tr)}}let syncOpCounter=0;function serializeAction(r){const e=r.context?.signer;return e?.signatures?{...r,context:{...r.context,signer:{...e,signatures:e.signatures.map(M=>Array.isArray(M)?M.join(", "):M)}}}:r}function serializeEnvelope(r){return{type:r.type.toUpperCase(),channelMeta:r.channelMeta,operations:r.operations?.map(e=>({operation:{index:e.operation.index,timestampUtcMs:e.operation.timestampUtcMs,hash:e.operation.hash,skip:e.operation.skip,error:e.operation.error,id:e.operation.id,action:serializeAction(e.operation.action)},context:{documentId:e.context.documentId,documentType:e.context.documentType,scope:e.context.scope,branch:e.context.branch}})),cursor:r.cursor,key:r.key,dependsOn:r.dependsOn}}function deserializeSignature(r){return Array.isArray(r)?r:r.split(", ")}function deserializeOperationSignatures(r){const e=r.operation.action.context?.signer;if(!e?.signatures||e.signatures.length===0)return r;const M=e.signatures.map(deserializeSignature),tr={...r.operation,action:{...r.operation.action,context:{...r.operation.action.context,signer:{...e,signatures:M}}}};return{...r,operation:tr}}function envelopesToSyncOperations(r,e){if(!r.operations||r.operations.length===0)return[];const M=r.operations.map(deserializeOperationSignatures);return batchOperationsByDocument(M).map(rr=>{const ir=`syncop-${r.channelMeta.id}-${Date.now()}-${syncOpCounter++}`;return new SyncOperation(ir,r.key??"",(r.dependsOn??[]).filter(Boolean),e,rr.documentId,[rr.scope],rr.branch,rr.operations)})}const getLatestAppliedOrdinal=r=>{let e=0;for(const M of r)if(M.status===SyncOperationStatus.Applied)for(const tr of M.operations)e=Math.max(e,tr.context.ordinal);return e};class GqlRequestChannel{logger;inbox;outbox;deadLetter;config;bufferedOutbox;channelId;remoteName;cursorStorage;operationIndex;pollTimer;isShutdown;failureCount;lastSuccessUtcMs;lastFailureUtcMs;lastPersistedInboxOrdinal=0;lastPersistedOutboxOrdinal=0;pushFailureCount=0;pushRetryTimer=null;pushBlocked=!1;constructor(e,M,tr,rr,ir,lr,dr){this.logger=e,this.channelId=M,this.remoteName=tr,this.cursorStorage=rr,this.operationIndex=lr,this.pollTimer=dr,this.config={url:ir.url,jwtHandler:ir.jwtHandler,fetchFn:ir.fetchFn,collectionId:ir.collectionId,filter:ir.filter,retryBaseDelayMs:ir.retryBaseDelayMs,retryMaxDelayMs:ir.retryMaxDelayMs},this.isShutdown=!1,this.failureCount=0,this.inbox=new Mailbox,this.bufferedOutbox=new BufferedMailbox(500,25),this.outbox=this.bufferedOutbox,this.deadLetter=new Mailbox,this.outbox.onAdded(hr=>{this.isShutdown||this.pushBlocked||this.attemptPush(hr)}),this.outbox.onRemoved(hr=>{const fr=getLatestAppliedOrdinal(hr);fr>this.lastPersistedOutboxOrdinal&&(this.lastPersistedOutboxOrdinal=fr,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:"outbox",cursorOrdinal:fr,lastSyncedAtUtcMs:Date.now()}).catch(mr=>{this.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,mr)}))}),this.inbox.onRemoved(hr=>{const fr=getLatestAppliedOrdinal(hr);fr>this.lastPersistedInboxOrdinal&&(this.lastPersistedInboxOrdinal=fr,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:"inbox",cursorOrdinal:fr,lastSyncedAtUtcMs:Date.now()}).catch(mr=>{this.logger.error("Failed to update inbox cursor for @ChannelId! This is unlikely to cause a problem, but not-optimal: @Error",this.channelId,mr)}))})}shutdown(){return this.bufferedOutbox.flush(),this.isShutdown=!0,this.pollTimer.stop(),this.pushRetryTimer&&(clearTimeout(this.pushRetryTimer),this.pushRetryTimer=null),Promise.resolve()}async init(){await this.touchRemoteChannel();const e=await this.cursorStorage.list(this.remoteName),M=e.find(rr=>rr.cursorType==="inbox")?.cursorOrdinal??0,tr=e.find(rr=>rr.cursorType==="outbox")?.cursorOrdinal??0;this.inbox.init(M),this.outbox.init(tr),this.lastPersistedInboxOrdinal=M,this.lastPersistedOutboxOrdinal=tr,this.pollTimer.setDelegate(()=>this.poll()),this.pollTimer.start()}async poll(){if(this.isShutdown)return;let e;try{e=await this.pollSyncEnvelopes(this.inbox.ackOrdinal,this.inbox.latestOrdinal)}catch(lr){if(!this.handlePollError(lr))throw lr;return}const{envelopes:M,ackOrdinal:tr}=e;tr>0&&trimMailboxFromAckOrdinal(this.outbox,tr);const rr=sortEnvelopesByFirstOperationTimestamp(M),ir=[];for(const lr of rr)if(lr.type.toLowerCase()==="operations"&&lr.operations){const dr=envelopesToSyncOperations(lr,this.remoteName);for(const hr of dr)hr.transported();ir.push(...dr)}ir.length>0&&this.inbox.add(...ir),this.lastSuccessUtcMs=Date.now(),this.failureCount=0}handlePollError(e){const M=e instanceof Error?e:new Error(String(e));if(M.message.includes("Channel not found"))return this.recoverFromChannelNotFound(),!0;this.failureCount++,this.lastFailureUtcMs=Date.now();const tr=new ChannelError(ChannelErrorSource.Inbox,M);return this.logger.error("GqlChannel poll error (@FailureCount): @Error",this.failureCount,tr),!1}recoverFromChannelNotFound(){this.logger.info("GqlChannel @ChannelId not found on remote, re-registering...",this.channelId),this.pollTimer.stop(),this.touchRemoteChannel().then(()=>{this.logger.info("GqlChannel @ChannelId re-registered successfully",this.channelId),this.failureCount=0,this.pollTimer.start()}).catch(e=>{this.logger.error("GqlChannel @ChannelId failed to re-register: @Error",this.channelId,e),this.failureCount++,this.lastFailureUtcMs=Date.now(),this.pollTimer.start()})}async pollSyncEnvelopes(e,M){const tr=`
24
+ query PollSyncEnvelopes($channelId: String!, $outboxAck: Int!, $outboxLatest: Int!) {
25
+ pollSyncEnvelopes(channelId: $channelId, outboxAck: $outboxAck, outboxLatest: $outboxLatest) {
26
+ envelopes {
27
+ type
28
+ channelMeta {
29
+ id
30
+ }
31
+ operations {
32
+ operation {
33
+ index
34
+ timestampUtcMs
35
+ hash
36
+ skip
37
+ error
38
+ id
39
+ action {
40
+ id
41
+ type
42
+ timestampUtcMs
43
+ input
44
+ scope
45
+ attachments {
46
+ data
47
+ mimeType
48
+ hash
49
+ extension
50
+ fileName
51
+ }
52
+ context {
53
+ signer {
54
+ user {
55
+ address
56
+ networkId
57
+ chainId
58
+ }
59
+ app {
60
+ name
61
+ key
62
+ }
63
+ signatures
64
+ }
65
+ }
66
+ }
67
+ }
68
+ context {
69
+ documentId
70
+ documentType
71
+ scope
72
+ branch
73
+ ordinal
74
+ }
75
+ }
76
+ cursor {
77
+ remoteName
78
+ cursorOrdinal
79
+ lastSyncedAtUtcMs
80
+ }
81
+ key
82
+ dependsOn
83
+ }
84
+ ackOrdinal
85
+ }
86
+ }
87
+ `,rr={channelId:this.channelId,outboxAck:e,outboxLatest:M},ir=await this.executeGraphQL(tr,rr);return{envelopes:ir.pollSyncEnvelopes.envelopes,ackOrdinal:ir.pollSyncEnvelopes.ackOrdinal}}async touchRemoteChannel(){let e="0";try{const rr=await this.operationIndex.getLatestTimestampForCollection(this.config.collectionId);rr&&(e=rr)}catch{}const M=`
88
+ mutation TouchChannel($input: TouchChannelInput!) {
89
+ touchChannel(input: $input)
90
+ }
91
+ `,tr={input:{id:this.channelId,name:this.channelId,collectionId:this.config.collectionId,filter:{documentId:this.config.filter.documentId,scope:this.config.filter.scope,branch:this.config.filter.branch},sinceTimestampUtcMs:e}};await this.executeGraphQL(M,tr)}attemptPush(e){this.pushSyncOperations(e).then(()=>{this.pushBlocked=!1,this.pushFailureCount=0}).catch(M=>{const tr=M instanceof Error?M:new Error(String(M));if(this.isRecoverablePushError(tr))this.pushFailureCount++,this.pushBlocked=!0,this.logger.error("GqlChannel push failed (attempt @FailureCount), will retry: @Error",this.pushFailureCount,tr),this.schedulePushRetry();else{const rr=new ChannelError(ChannelErrorSource.Outbox,tr);for(const ir of e)ir.failed(rr);this.deadLetter.add(...e),this.outbox.remove(...e)}})}schedulePushRetry(){if(this.pushRetryTimer)return;const e=calculateBackoffDelay(this.pushFailureCount,this.config.retryBaseDelayMs,this.config.retryMaxDelayMs,Math.random());this.pushRetryTimer=setTimeout(()=>{if(this.pushRetryTimer=null,this.isShutdown)return;const M=this.outbox.items;if(M.length===0){this.pushBlocked=!1,this.pushFailureCount=0;return}this.attemptPush([...M])},e)}isRecoverablePushError(e){return!(e.message.startsWith("GraphQL errors:")||e.message==="GraphQL response missing data field")}async pushSyncOperations(e){for(const lr of e)lr.started();const M=new Map,tr=[];for(let lr=0;lr<e.length;lr++){const dr=e[lr],hr=String(lr);dr.jobId&&(M.has(dr.jobId)||M.set(dr.jobId,[]),M.get(dr.jobId).push(hr));const fr=[];for(const mr of dr.jobDependencies){const _r=M.get(mr);_r&&fr.push(..._r)}this.logger.debug("[PUSH]: @Operations",dr.operations.map(mr=>`(${mr.context.documentId}, ${mr.context.branch}, ${mr.context.scope}, ${mr.operation.index})`)),tr.push({type:"operations",channelMeta:{id:this.channelId},operations:dr.operations,key:hr,dependsOn:fr})}const rr=`
92
+ mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
93
+ pushSyncEnvelopes(envelopes: $envelopes)
94
+ }
95
+ `,ir={envelopes:tr.map(lr=>serializeEnvelope(lr))};await this.executeGraphQL(rr,ir)}async getAuthorizationHeader(){if(this.config.jwtHandler)try{const e=await this.config.jwtHandler(this.config.url);if(e)return`Bearer ${e}`}catch(e){this.logger.error("JWT handler failed: @Error",e)}}async executeGraphQL(e,M){const tr={"Content-Type":"application/json"},rr=await this.getAuthorizationHeader();rr&&(tr.Authorization=rr);const ir=this.config.fetchFn??fetch;let lr;try{lr=await ir(this.config.url,{method:"POST",headers:tr,body:JSON.stringify({query:e,variables:M})})}catch(hr){throw new Error(`GraphQL request failed: ${hr instanceof Error?hr.message:String(hr)}`)}if(!lr.ok)throw new Error(`GraphQL request failed: ${lr.status} ${lr.statusText}`);let dr;try{dr=await lr.json()}catch(hr){throw new Error(`Failed to parse GraphQL response: ${hr instanceof Error?hr.message:String(hr)}`)}if(dr.errors)throw new Error(`GraphQL errors: ${JSON.stringify(dr.errors,null,2)}`);if(!dr.data)throw new Error("GraphQL response missing data field");return dr.data}getHealth(){return{state:this.failureCount>0?"error":"idle",lastSuccessUtcMs:this.lastSuccessUtcMs,lastFailureUtcMs:this.lastFailureUtcMs,failureCount:this.failureCount}}get poller(){return this.pollTimer}}class GqlRequestChannelFactory{logger;jwtHandler;queue;constructor(e,M,tr){this.logger=e,this.jwtHandler=M,this.queue=tr}instance(e,M,tr,rr,ir,lr,dr){const hr=tr.parameters.url;if(typeof hr!="string"||!hr)throw new Error('GqlRequestChannelFactory requires "url" parameter in config.parameters');const fr={url:hr,collectionId:ir,filter:lr,jwtHandler:this.jwtHandler,retryBaseDelayMs:1e3,retryMaxDelayMs:3e5};let mr=2e3;if(tr.parameters.pollIntervalMs!==void 0){if(typeof tr.parameters.pollIntervalMs!="number")throw new Error('"pollIntervalMs" parameter must be a number');mr=tr.parameters.pollIntervalMs}let _r;if(tr.parameters.retryBaseDelayMs!==void 0){if(typeof tr.parameters.retryBaseDelayMs!="number")throw new Error('"retryBaseDelayMs" parameter must be a number');_r=tr.parameters.retryBaseDelayMs}let gr;if(tr.parameters.retryMaxDelayMs!==void 0){if(typeof tr.parameters.retryMaxDelayMs!="number")throw new Error('"retryMaxDelayMs" parameter must be a number');gr=tr.parameters.retryMaxDelayMs}if(tr.parameters.fetchFn!==void 0){if(typeof tr.parameters.fetchFn!="function")throw new Error('"fetchFn" parameter must be a function');fr.fetchFn=tr.parameters.fetchFn}_r!==void 0&&(fr.retryBaseDelayMs=_r),gr!==void 0&&(fr.retryMaxDelayMs=gr);let wr;if(tr.parameters.maxQueueDepth!==void 0){if(typeof tr.parameters.maxQueueDepth!="number")throw new Error('"maxQueueDepth" parameter must be a number');wr=tr.parameters.maxQueueDepth}let yr;if(tr.parameters.backpressureCheckIntervalMs!==void 0){if(typeof tr.parameters.backpressureCheckIntervalMs!="number")throw new Error('"backpressureCheckIntervalMs" parameter must be a number');yr=tr.parameters.backpressureCheckIntervalMs}const br=new IntervalPollTimer(this.queue,{intervalMs:mr,..._r!==void 0&&{retryBaseDelayMs:_r},...gr!==void 0&&{retryMaxDelayMs:gr},...wr!==void 0&&{maxQueueDepth:wr},...yr!==void 0&&{backpressureCheckIntervalMs:yr}});return new GqlRequestChannel(this.logger,e,M,rr,fr,dr,br)}}class GqlResponseChannel{logger;inbox;outbox;deadLetter;channelId;remoteName;cursorStorage;isShutdown;lastPersistedInboxOrdinal=0;lastPersistedOutboxOrdinal=0;constructor(e,M,tr,rr){this.logger=e,this.channelId=M,this.remoteName=tr,this.cursorStorage=rr,this.isShutdown=!1,this.inbox=new Mailbox,this.outbox=new Mailbox,this.deadLetter=new Mailbox,this.outbox.onRemoved(ir=>{const lr=getLatestAppliedOrdinal(ir);lr>this.lastPersistedOutboxOrdinal&&(this.lastPersistedOutboxOrdinal=lr,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:"outbox",cursorOrdinal:lr,lastSyncedAtUtcMs:Date.now()}).catch(dr=>{this.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,dr)}))}),this.inbox.onRemoved(ir=>{const lr=getLatestAppliedOrdinal(ir);lr>this.lastPersistedInboxOrdinal&&(this.lastPersistedInboxOrdinal=lr,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:"inbox",cursorOrdinal:lr,lastSyncedAtUtcMs:Date.now()}).catch(dr=>{this.logger.error("Failed to update inbox cursor for @ChannelId! This is unlikely to cause a problem, but not-optimal: @Error",this.channelId,dr)}))})}shutdown(){return this.isShutdown=!0,Promise.resolve()}async init(){const e=await this.cursorStorage.list(this.remoteName),M=e.find(rr=>rr.cursorType==="inbox")?.cursorOrdinal??0,tr=e.find(rr=>rr.cursorType==="outbox")?.cursorOrdinal??0;this.inbox.init(M),this.outbox.init(tr),this.lastPersistedInboxOrdinal=M,this.lastPersistedOutboxOrdinal=tr}}class GqlResponseChannelFactory{logger;constructor(e){this.logger=e}instance(e,M,tr,rr){return new GqlResponseChannel(this.logger,e,M,rr)}}async function collectAllPages(r,e){const M=[...r.results];let tr=r;for(;tr.next;){if(e?.aborted)throw new Error("Operation aborted");tr=await tr.next(),M.push(...tr.results)}return M}class KyselyDocumentIndexer{db;operationStore;consistencyTracker;lastOperationId=0;constructor(e,M,tr){this.db=e,this.operationStore=M,this.consistencyTracker=tr}async init(){const e=await this.db.selectFrom("IndexerState").selectAll().executeTakeFirst();if(e){this.lastOperationId=e.lastOperationId;const M=await this.operationStore.getSinceId(this.lastOperationId);M.results.length>0&&await this.indexOperations(M.results)}else{await this.db.insertInto("IndexerState").values({lastOperationId:0}).execute();const M=await this.operationStore.getSinceId(0);M.results.length>0&&await this.indexOperations(M.results)}}async indexOperations(e){if(e.length===0)return;await this.db.transaction().execute(async tr=>{for(const ir of e){const{operation:lr}=ir,dr=lr.action.type;dr==="ADD_RELATIONSHIP"?await this.handleAddRelationship(tr,lr):dr==="REMOVE_RELATIONSHIP"&&await this.handleRemoveRelationship(tr,lr)}const rr=e[e.length-1].operation.id;rr&&typeof rr=="number"&&(this.lastOperationId=rr,await tr.updateTable("IndexerState").set({lastOperationId:rr,lastOperationTimestamp:new Date}).execute())});const M=[];for(let tr=0;tr<e.length;tr++){const rr=e[tr];M.push({documentId:rr.context.documentId,scope:rr.context.scope,branch:rr.context.branch,operationIndex:rr.operation.index})}this.consistencyTracker.update(M)}async waitForConsistency(e,M,tr){e.coordinates.length!==0&&await this.consistencyTracker.waitFor(e.coordinates,M,tr)}async getOutgoing(e,M,tr,rr,ir){if(rr&&await this.waitForConsistency(rr,void 0,ir),ir?.aborted)throw new Error("Operation aborted");const lr=tr?.cursor?parseInt(tr.cursor):0,dr=tr?.limit||100;let hr=this.db.selectFrom("DocumentRelationship").selectAll().where("sourceId","=",e);M&&M.length>0&&(hr=hr.where("relationshipType","in",M));const fr=await hr.orderBy("createdAt","asc").orderBy("id","asc").offset(lr).limit(dr+1).execute(),mr=fr.length>dr,_r=mr?fr.slice(0,dr):fr,gr=mr?String(lr+dr):void 0;return{results:_r.map(wr=>({sourceId:wr.sourceId,targetId:wr.targetId,relationshipType:wr.relationshipType,metadata:wr.metadata?wr.metadata:void 0,createdAt:wr.createdAt,updatedAt:wr.updatedAt})),options:tr||{cursor:"0",limit:100},nextCursor:gr,next:mr?()=>this.getOutgoing(e,M,{cursor:gr,limit:dr},rr,ir):void 0}}async getIncoming(e,M,tr,rr,ir){if(rr&&await this.waitForConsistency(rr,void 0,ir),ir?.aborted)throw new Error("Operation aborted");const lr=tr?.cursor?parseInt(tr.cursor):0,dr=tr?.limit||100;let hr=this.db.selectFrom("DocumentRelationship").selectAll().where("targetId","=",e);M&&M.length>0&&(hr=hr.where("relationshipType","in",M));const fr=await hr.orderBy("createdAt","asc").orderBy("id","asc").offset(lr).limit(dr+1).execute(),mr=fr.length>dr,_r=mr?fr.slice(0,dr):fr,gr=mr?String(lr+dr):void 0;return{results:_r.map(wr=>({sourceId:wr.sourceId,targetId:wr.targetId,relationshipType:wr.relationshipType,metadata:wr.metadata?wr.metadata:void 0,createdAt:wr.createdAt,updatedAt:wr.updatedAt})),options:tr||{cursor:"0",limit:100},nextCursor:gr,next:mr?()=>this.getIncoming(e,M,{cursor:gr,limit:dr},rr,ir):void 0}}async hasRelationship(e,M,tr,rr,ir){if(rr&&await this.waitForConsistency(rr,void 0,ir),ir?.aborted)throw new Error("Operation aborted");let lr=this.db.selectFrom("DocumentRelationship").select("id").where("sourceId","=",e).where("targetId","=",M);return tr&&tr.length>0&&(lr=lr.where("relationshipType","in",tr)),await lr.executeTakeFirst()!==void 0}async getUndirectedRelationships(e,M,tr,rr,ir,lr){if(ir&&await this.waitForConsistency(ir,void 0,lr),lr?.aborted)throw new Error("Operation aborted");const dr=rr?.cursor?parseInt(rr.cursor):0,hr=rr?.limit||100;let fr=this.db.selectFrom("DocumentRelationship").selectAll().where(yr=>yr.or([yr.and([yr("sourceId","=",e),yr("targetId","=",M)]),yr.and([yr("sourceId","=",M),yr("targetId","=",e)])]));tr&&tr.length>0&&(fr=fr.where("relationshipType","in",tr));const mr=await fr.orderBy("createdAt","asc").orderBy("id","asc").offset(dr).limit(hr+1).execute(),_r=mr.length>hr,gr=_r?mr.slice(0,hr):mr,wr=_r?String(dr+hr):void 0;return{results:gr.map(yr=>({sourceId:yr.sourceId,targetId:yr.targetId,relationshipType:yr.relationshipType,metadata:yr.metadata?yr.metadata:void 0,createdAt:yr.createdAt,updatedAt:yr.updatedAt})),options:rr||{cursor:"0",limit:100},nextCursor:wr,next:_r?()=>this.getUndirectedRelationships(e,M,tr,{cursor:wr,limit:hr},ir,lr):void 0}}async getDirectedRelationships(e,M,tr,rr,ir,lr){if(ir&&await this.waitForConsistency(ir,void 0,lr),lr?.aborted)throw new Error("Operation aborted");const dr=rr?.cursor?parseInt(rr.cursor):0,hr=rr?.limit||100;let fr=this.db.selectFrom("DocumentRelationship").selectAll().where("sourceId","=",e).where("targetId","=",M);tr&&tr.length>0&&(fr=fr.where("relationshipType","in",tr));const mr=await fr.orderBy("createdAt","asc").orderBy("id","asc").offset(dr).limit(hr+1).execute(),_r=mr.length>hr,gr=_r?mr.slice(0,hr):mr,wr=_r?String(dr+hr):void 0;return{results:gr.map(yr=>({sourceId:yr.sourceId,targetId:yr.targetId,relationshipType:yr.relationshipType,metadata:yr.metadata?yr.metadata:void 0,createdAt:yr.createdAt,updatedAt:yr.updatedAt})),options:rr||{cursor:"0",limit:100},nextCursor:wr,next:_r?()=>this.getDirectedRelationships(e,M,tr,{cursor:wr,limit:hr},ir,lr):void 0}}async findPath(e,M,tr,rr,ir){if(rr&&await this.waitForConsistency(rr,void 0,ir),ir?.aborted)throw new Error("Operation aborted");if(e===M)return[e];const lr=new Set,dr=[{id:e,path:[e]}];for(;dr.length>0;){const hr=dr.shift();if(hr.id===M)return hr.path;if(lr.has(hr.id))continue;lr.add(hr.id);const fr=await this.getOutgoing(hr.id,tr,void 0,rr,ir),mr=await collectAllPages(fr,ir);for(const _r of mr)lr.has(_r.targetId)||dr.push({id:_r.targetId,path:[...hr.path,_r.targetId]})}return null}async findAncestors(e,M,tr,rr){if(tr&&await this.waitForConsistency(tr,void 0,rr),rr?.aborted)throw new Error("Operation aborted");const ir=new Set([e]),lr=[],dr=[e],hr=new Set;for(;dr.length>0;){const fr=dr.shift();if(hr.has(fr))continue;hr.add(fr);const mr=await this.getIncoming(fr,M,void 0,tr,rr),_r=await collectAllPages(mr,rr);for(const gr of _r)ir.add(gr.sourceId),lr.push({from:gr.sourceId,to:gr.targetId,type:gr.relationshipType}),hr.has(gr.sourceId)||dr.push(gr.sourceId)}return{nodes:Array.from(ir),edges:lr}}async getRelationshipTypes(e,M){if(e&&await this.waitForConsistency(e,void 0,M),M?.aborted)throw new Error("Operation aborted");return(await this.db.selectFrom("DocumentRelationship").select("relationshipType").distinct().execute()).map(rr=>rr.relationshipType)}async handleAddRelationship(e,M){const tr=M.action.input;if(await e.selectFrom("Document").select("id").where("id","=",tr.sourceId).executeTakeFirst()||await e.insertInto("Document").values({id:tr.sourceId}).execute(),await e.selectFrom("Document").select("id").where("id","=",tr.targetId).executeTakeFirst()||await e.insertInto("Document").values({id:tr.targetId}).execute(),!await e.selectFrom("DocumentRelationship").select("id").where("sourceId","=",tr.sourceId).where("targetId","=",tr.targetId).where("relationshipType","=",tr.relationshipType).executeTakeFirst()){const dr={id:v4(),sourceId:tr.sourceId,targetId:tr.targetId,relationshipType:tr.relationshipType,metadata:tr.metadata||null};await e.insertInto("DocumentRelationship").values(dr).execute()}}async handleRemoveRelationship(e,M){const tr=M.action.input;await e.deleteFrom("DocumentRelationship").where("sourceId","=",tr.sourceId).where("targetId","=",tr.targetId).where("relationshipType","=",tr.relationshipType).execute()}}class KyselyKeyframeStore{db;constructor(e){this.db=e}async putKeyframe(e,M,tr,rr,ir,lr){if(lr?.aborted)throw new Error("Operation aborted");await this.db.insertInto("Keyframe").values({documentId:e,documentType:ir.header.documentType,scope:M,branch:tr,revision:rr,document:ir}).onConflict(dr=>dr.columns(["documentId","scope","branch","revision"]).doUpdateSet({document:ir})).execute()}async findNearestKeyframe(e,M,tr,rr,ir){if(ir?.aborted)throw new Error("Operation aborted");const lr=await this.db.selectFrom("Keyframe").selectAll().where("documentId","=",e).where("scope","=",M).where("branch","=",tr).where("revision","<=",rr).orderBy("revision","desc").limit(1).executeTakeFirst();if(lr)return{revision:lr.revision,document:lr.document}}async deleteKeyframes(e,M,tr,rr){if(rr?.aborted)throw new Error("Operation aborted");let ir=this.db.deleteFrom("Keyframe").where("documentId","=",e);M!==void 0&&tr!==void 0?ir=ir.where("scope","=",M).where("branch","=",tr):M!==void 0&&(ir=ir.where("scope","=",M));const lr=await ir.executeTakeFirst();return Number(lr.numDeletedRows||0n)}}class DuplicateOperationError extends Error{constructor(e){super(`Duplicate operation: ${e}`),this.name="DuplicateOperationError"}}class RevisionMismatchError extends Error{constructor(e,M){super(`Revision mismatch: expected ${e}, got ${M}`),this.name="RevisionMismatchError"}}class AtomicTransaction{documentId;documentType;scope;branch;baseRevision;operations=[];constructor(e,M,tr,rr,ir){this.documentId=e,this.documentType=M,this.scope=tr,this.branch=rr,this.baseRevision=ir}addOperations(...e){for(const M of e)this.operations.push({jobId:v4(),opId:M.id,prevOpId:"",documentId:this.documentId,documentType:this.documentType,scope:this.scope,branch:this.branch,timestampUtcMs:new Date(M.timestampUtcMs),index:M.index,action:JSON.stringify(M.action),skip:M.skip,error:M.error||null,hash:M.hash})}getOperations(){return this.operations}}class KyselyOperationStore{db;constructor(e){this.db=e}async apply(e,M,tr,rr,ir,lr,dr){await this.db.transaction().execute(async hr=>{if(dr?.aborted)throw new Error("Operation aborted");const fr=await hr.selectFrom("Operation").selectAll().where("documentId","=",e).where("scope","=",tr).where("branch","=",rr).orderBy("index","desc").limit(1).executeTakeFirst(),mr=fr?fr.index:-1;if(mr!==ir-1)throw new RevisionMismatchError(mr+1,ir);const _r=new AtomicTransaction(e,M,tr,rr,ir);await lr(_r);const gr=_r.getOperations();if(gr.length>0){let wr=fr?.opId||"";for(const yr of gr)yr.prevOpId=wr,wr=yr.opId;try{await hr.insertInto("Operation").values(gr).execute()}catch(yr){if(yr instanceof Error){if(yr.message.includes("unique constraint")){const br=gr[0];throw new DuplicateOperationError(`${br.opId} at index ${br.index} with skip ${br.skip}`)}throw yr}throw yr}}})}async getSince(e,M,tr,rr,ir,lr,dr){if(dr?.aborted)throw new Error("Operation aborted");let hr=this.db.selectFrom("Operation").selectAll().where("documentId","=",e).where("scope","=",M).where("branch","=",tr).where("index",">",rr).orderBy("index","asc");if(ir){if(ir.actionTypes&&ir.actionTypes.length>0){const Mr=ir.actionTypes.map(vr=>`'${vr.replace(/'/g,"''")}'`).join(",");hr=hr.where(sql`action->>'type' = ANY(ARRAY[${sql.raw(Mr)}]::text[])`)}ir.timestampFrom&&(hr=hr.where("timestampUtcMs",">=",new Date(ir.timestampFrom))),ir.timestampTo&&(hr=hr.where("timestampUtcMs","<=",new Date(ir.timestampTo))),ir.sinceRevision!==void 0&&(hr=hr.where("index",">=",ir.sinceRevision))}if(lr){const Mr=Number.parseInt(lr.cursor,10);Mr>0&&(hr=hr.where("index",">",Mr)),lr.limit&&(hr=hr.limit(lr.limit+1))}const fr=await hr.execute();let mr=!1,_r=fr;lr?.limit&&fr.length>lr.limit&&(mr=!0,_r=fr.slice(0,lr.limit));const gr=mr&&_r.length>0?_r[_r.length-1].index.toString():void 0,wr=lr?.cursor||"0",yr=lr?.limit||100;return{results:_r.map(Mr=>this.rowToOperation(Mr)),options:{cursor:wr,limit:yr},nextCursor:gr,next:mr?()=>this.getSince(e,M,tr,rr,ir,{cursor:gr,limit:yr},dr):void 0}}async getSinceId(e,M,tr){if(tr?.aborted)throw new Error("Operation aborted");let rr=this.db.selectFrom("Operation").selectAll().where("id",">",e).orderBy("id","asc");if(M){const gr=Number.parseInt(M.cursor,10);gr>0&&(rr=rr.where("id",">",gr)),M.limit&&(rr=rr.limit(M.limit+1))}const ir=await rr.execute();let lr=!1,dr=ir;M?.limit&&ir.length>M.limit&&(lr=!0,dr=ir.slice(0,M.limit));const hr=lr&&dr.length>0?dr[dr.length-1].id.toString():void 0,fr=M?.cursor||"0",mr=M?.limit||100;return{results:dr.map(gr=>this.rowToOperationWithContext(gr)),options:{cursor:fr,limit:mr},nextCursor:hr,next:lr?()=>this.getSinceId(e,{cursor:hr,limit:mr},tr):void 0}}async getConflicting(e,M,tr,rr,ir,lr){if(lr?.aborted)throw new Error("Operation aborted");let dr=this.db.selectFrom("Operation").selectAll().where("documentId","=",e).where("scope","=",M).where("branch","=",tr).where("timestampUtcMs",">=",new Date(rr)).orderBy("index","asc");if(ir){const br=Number.parseInt(ir.cursor,10);br>0&&(dr=dr.where("index",">",br)),ir.limit&&(dr=dr.limit(ir.limit+1))}const hr=await dr.execute();let fr=!1,mr=hr;ir?.limit&&hr.length>ir.limit&&(fr=!0,mr=hr.slice(0,ir.limit));const _r=fr&&mr.length>0?mr[mr.length-1].index.toString():void 0,gr=ir?.cursor||"0",wr=ir?.limit||100;return{results:mr.map(br=>this.rowToOperation(br)),options:{cursor:gr,limit:wr},nextCursor:_r,next:fr?()=>this.getConflicting(e,M,tr,rr,{cursor:_r,limit:wr},lr):void 0}}async getRevisions(e,M,tr){if(tr?.aborted)throw new Error("Operation aborted");const rr=await this.db.selectFrom("Operation as o1").select(["o1.scope","o1.index","o1.timestampUtcMs"]).where("o1.documentId","=",e).where("o1.branch","=",M).where(dr=>dr("o1.index","=",dr.selectFrom("Operation as o2").select(hr=>hr.fn.max("o2.index").as("maxIndex")).where("o2.documentId","=",dr.ref("o1.documentId")).where("o2.branch","=",dr.ref("o1.branch")).where("o2.scope","=",dr.ref("o1.scope")))).execute(),ir={};let lr=new Date(0).toISOString();for(const dr of rr){ir[dr.scope]=dr.index+1;const hr=dr.timestampUtcMs.toISOString();hr>lr&&(lr=hr)}return{revision:ir,latestTimestamp:lr}}rowToOperation(e){return{index:e.index,timestampUtcMs:e.timestampUtcMs.toISOString(),hash:e.hash,skip:e.skip,error:e.error||void 0,id:e.opId,action:e.action}}rowToOperationWithContext(e){return{operation:this.rowToOperation(e),context:{documentId:e.documentId,documentType:e.documentType,scope:e.scope,branch:e.branch,ordinal:e.id}}}}async function up$b(r){await r.schema.createTable("Operation").addColumn("id","serial",e=>e.primaryKey()).addColumn("jobId","text",e=>e.notNull()).addColumn("opId","text",e=>e.notNull()).addColumn("prevOpId","text",e=>e.notNull()).addColumn("writeTimestampUtcMs","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addColumn("documentId","text",e=>e.notNull()).addColumn("documentType","text",e=>e.notNull()).addColumn("scope","text",e=>e.notNull()).addColumn("branch","text",e=>e.notNull()).addColumn("timestampUtcMs","timestamptz",e=>e.notNull()).addColumn("index","integer",e=>e.notNull()).addColumn("action","jsonb",e=>e.notNull()).addColumn("skip","integer",e=>e.notNull()).addColumn("error","text").addColumn("hash","text",e=>e.notNull()).addUniqueConstraint("unique_revision",["documentId","scope","branch","index"]).addUniqueConstraint("unique_operation_instance",["opId","index","skip"]).execute(),await r.schema.createIndex("streamOperations").on("Operation").columns(["documentId","scope","branch","id"]).execute(),await r.schema.createIndex("branchlessStreamOperations").on("Operation").columns(["documentId","scope","id"]).execute()}const migration001=Object.freeze(Object.defineProperty({__proto__:null,up:up$b},Symbol.toStringTag,{value:"Module"}));async function up$a(r){await r.schema.createTable("Keyframe").addColumn("id","serial",e=>e.primaryKey()).addColumn("documentId","text",e=>e.notNull()).addColumn("documentType","text",e=>e.notNull()).addColumn("scope","text",e=>e.notNull()).addColumn("branch","text",e=>e.notNull()).addColumn("revision","integer",e=>e.notNull()).addColumn("document","jsonb",e=>e.notNull()).addColumn("createdAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint("unique_keyframe",["documentId","scope","branch","revision"]).execute(),await r.schema.createIndex("keyframe_lookup").on("Keyframe").columns(["documentId","scope","branch","revision"]).execute()}const migration002=Object.freeze(Object.defineProperty({__proto__:null,up:up$a},Symbol.toStringTag,{value:"Module"}));async function up$9(r){await r.schema.createTable("Document").addColumn("id","text",e=>e.primaryKey()).addColumn("createdAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addColumn("updatedAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).execute()}const migration003=Object.freeze(Object.defineProperty({__proto__:null,up:up$9},Symbol.toStringTag,{value:"Module"}));async function up$8(r){await r.schema.createTable("DocumentRelationship").addColumn("id","text",e=>e.primaryKey()).addColumn("sourceId","text",e=>e.notNull().references("Document.id").onDelete("cascade")).addColumn("targetId","text",e=>e.notNull().references("Document.id").onDelete("cascade")).addColumn("relationshipType","text",e=>e.notNull()).addColumn("metadata","jsonb").addColumn("createdAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addColumn("updatedAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint("unique_source_target_type",["sourceId","targetId","relationshipType"]).execute(),await r.schema.createIndex("idx_relationship_source").on("DocumentRelationship").column("sourceId").execute(),await r.schema.createIndex("idx_relationship_target").on("DocumentRelationship").column("targetId").execute(),await r.schema.createIndex("idx_relationship_type").on("DocumentRelationship").column("relationshipType").execute()}const migration004=Object.freeze(Object.defineProperty({__proto__:null,up:up$8},Symbol.toStringTag,{value:"Module"}));async function up$7(r){await r.schema.createTable("IndexerState").addColumn("id","integer",e=>e.primaryKey().generatedAlwaysAsIdentity()).addColumn("lastOperationId","integer",e=>e.notNull()).addColumn("lastOperationTimestamp","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).execute()}const migration005=Object.freeze(Object.defineProperty({__proto__:null,up:up$7},Symbol.toStringTag,{value:"Module"}));async function up$6(r){await r.schema.createTable("DocumentSnapshot").addColumn("id","text",e=>e.primaryKey()).addColumn("documentId","text",e=>e.notNull()).addColumn("slug","text").addColumn("name","text").addColumn("scope","text",e=>e.notNull()).addColumn("branch","text",e=>e.notNull()).addColumn("content","jsonb",e=>e.notNull()).addColumn("documentType","text",e=>e.notNull()).addColumn("lastOperationIndex","integer",e=>e.notNull()).addColumn("lastOperationHash","text",e=>e.notNull()).addColumn("lastUpdatedAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addColumn("snapshotVersion","integer",e=>e.notNull().defaultTo(1)).addColumn("identifiers","jsonb").addColumn("metadata","jsonb").addColumn("isDeleted","boolean",e=>e.notNull().defaultTo(!1)).addColumn("deletedAt","timestamptz").addUniqueConstraint("unique_doc_scope_branch",["documentId","scope","branch"]).execute(),await r.schema.createIndex("idx_slug_scope_branch").on("DocumentSnapshot").columns(["slug","scope","branch"]).execute(),await r.schema.createIndex("idx_doctype_scope_branch").on("DocumentSnapshot").columns(["documentType","scope","branch"]).execute(),await r.schema.createIndex("idx_last_updated").on("DocumentSnapshot").column("lastUpdatedAt").execute(),await r.schema.createIndex("idx_is_deleted").on("DocumentSnapshot").column("isDeleted").execute()}const migration006=Object.freeze(Object.defineProperty({__proto__:null,up:up$6},Symbol.toStringTag,{value:"Module"}));async function up$5(r){await r.schema.createTable("SlugMapping").addColumn("slug","text",e=>e.primaryKey()).addColumn("documentId","text",e=>e.notNull()).addColumn("scope","text",e=>e.notNull()).addColumn("branch","text",e=>e.notNull()).addColumn("createdAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addColumn("updatedAt","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint("unique_docid_scope_branch",["documentId","scope","branch"]).execute(),await r.schema.createIndex("idx_slug_documentid").on("SlugMapping").column("documentId").execute()}const migration007=Object.freeze(Object.defineProperty({__proto__:null,up:up$5},Symbol.toStringTag,{value:"Module"}));async function up$4(r){await r.schema.createTable("ViewState").addColumn("readModelId","text",e=>e.primaryKey()).addColumn("lastOrdinal","integer",e=>e.notNull().defaultTo(0)).addColumn("lastOperationTimestamp","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).execute()}const migration008=Object.freeze(Object.defineProperty({__proto__:null,up:up$4},Symbol.toStringTag,{value:"Module"}));async function up$3(r){await r.schema.createTable("document_collections").addColumn("documentId","text",e=>e.notNull()).addColumn("collectionId","text",e=>e.notNull()).addColumn("joinedOrdinal","bigint",e=>e.notNull().defaultTo(0)).addColumn("leftOrdinal","bigint").addPrimaryKeyConstraint("document_collections_pkey",["documentId","collectionId"]).execute(),await r.schema.createIndex("idx_document_collections_collectionId").on("document_collections").column("collectionId").execute(),await r.schema.createIndex("idx_doc_collections_collection_range").on("document_collections").columns(["collectionId","joinedOrdinal"]).execute(),await r.schema.createTable("operation_index_operations").addColumn("ordinal","serial",e=>e.primaryKey()).addColumn("opId","text",e=>e.notNull()).addColumn("documentId","text",e=>e.notNull()).addColumn("documentType","text",e=>e.notNull()).addColumn("scope","text",e=>e.notNull()).addColumn("branch","text",e=>e.notNull()).addColumn("timestampUtcMs","text",e=>e.notNull()).addColumn("writeTimestampUtcMs","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addColumn("index","integer",e=>e.notNull()).addColumn("skip","integer",e=>e.notNull()).addColumn("hash","text",e=>e.notNull()).addColumn("action","jsonb",e=>e.notNull()).execute(),await r.schema.createIndex("idx_operation_index_operations_document").on("operation_index_operations").columns(["documentId","branch","scope"]).execute(),await r.schema.createIndex("idx_operation_index_operations_ordinal").on("operation_index_operations").column("ordinal").execute()}const migration009=Object.freeze(Object.defineProperty({__proto__:null,up:up$3},Symbol.toStringTag,{value:"Module"}));async function up$2(r){await r.schema.createTable("sync_remotes").addColumn("name","text",e=>e.primaryKey()).addColumn("collection_id","text",e=>e.notNull()).addColumn("channel_type","text",e=>e.notNull()).addColumn("channel_id","text",e=>e.notNull().defaultTo("")).addColumn("remote_name","text",e=>e.notNull().defaultTo("")).addColumn("channel_parameters","jsonb",e=>e.notNull().defaultTo(sql`'{}'::jsonb`)).addColumn("filter_document_ids","jsonb").addColumn("filter_scopes","jsonb").addColumn("filter_branch","text",e=>e.notNull().defaultTo("main")).addColumn("push_state","text",e=>e.notNull().defaultTo("idle")).addColumn("push_last_success_utc_ms","text").addColumn("push_last_failure_utc_ms","text").addColumn("push_failure_count","integer",e=>e.notNull().defaultTo(0)).addColumn("pull_state","text",e=>e.notNull().defaultTo("idle")).addColumn("pull_last_success_utc_ms","text").addColumn("pull_last_failure_utc_ms","text").addColumn("pull_failure_count","integer",e=>e.notNull().defaultTo(0)).addColumn("created_at","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addColumn("updated_at","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).execute(),await r.schema.createIndex("idx_sync_remotes_collection").on("sync_remotes").column("collection_id").execute(),await r.schema.createTable("sync_cursors").addColumn("remote_name","text",e=>e.primaryKey().references("sync_remotes.name").onDelete("cascade")).addColumn("cursor_ordinal","bigint",e=>e.notNull().defaultTo(0)).addColumn("last_synced_at_utc_ms","text").addColumn("updated_at","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).execute(),await r.schema.createIndex("idx_sync_cursors_ordinal").on("sync_cursors").column("cursor_ordinal").execute()}const migration010=Object.freeze(Object.defineProperty({__proto__:null,up:up$2},Symbol.toStringTag,{value:"Module"}));async function up$1(r){await r.deleteFrom("sync_cursors").where("remote_name","like","outbox::%").execute(),await r.deleteFrom("sync_remotes").where("name","like","outbox::%").execute(),await r.schema.dropTable("sync_cursors").execute(),await r.schema.createTable("sync_cursors").addColumn("remote_name","text",e=>e.notNull()).addColumn("cursor_type","text",e=>e.notNull().defaultTo("inbox")).addColumn("cursor_ordinal","bigint",e=>e.notNull().defaultTo(0)).addColumn("last_synced_at_utc_ms","text").addColumn("updated_at","timestamptz",e=>e.notNull().defaultTo(sql`NOW()`)).addPrimaryKeyConstraint("sync_cursors_pk",["remote_name","cursor_type"]).execute(),await r.schema.createIndex("idx_sync_cursors_ordinal").on("sync_cursors").column("cursor_ordinal").execute()}const migration011=Object.freeze(Object.defineProperty({__proto__:null,up:up$1},Symbol.toStringTag,{value:"Module"}));async function up(r){await r.schema.alterTable("operation_index_operations").addColumn("sourceRemote","text",e=>e.notNull().defaultTo("")).execute()}const migration012=Object.freeze(Object.defineProperty({__proto__:null,up},Symbol.toStringTag,{value:"Module"})),REACTOR_SCHEMA="reactor",migrations={"001_create_operation_table":migration001,"002_create_keyframe_table":migration002,"003_create_document_table":migration003,"004_create_document_relationship_table":migration004,"005_create_indexer_state_table":migration005,"006_create_document_snapshot_table":migration006,"007_create_slug_mapping_table":migration007,"008_create_view_state_table":migration008,"009_create_operation_index_tables":migration009,"010_create_sync_tables":migration010,"011_add_cursor_type_column":migration011,"012_add_source_remote_column":migration012};class ProgrammaticMigrationProvider{getMigrations(){return Promise.resolve(migrations)}}async function runMigrations(r,e=REACTOR_SCHEMA){try{await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(e)}`.execute(r)}catch(lr){return{success:!1,migrationsExecuted:[],error:lr instanceof Error?lr:new Error("Failed to create schema")}}const M=new Migrator({db:r.withSchema(e),provider:new ProgrammaticMigrationProvider,migrationTableSchema:e});let tr,rr;try{const lr=await M.migrateToLatest();tr=lr.error,rr=lr.results}catch(lr){tr=lr,rr=[]}const ir=rr?.map(lr=>lr.migrationName)??[];return tr?{success:!1,migrationsExecuted:ir,error:tr instanceof Error?tr:new Error("Unknown migration error")}:{success:!0,migrationsExecuted:ir}}class DefaultSubscriptionErrorHandler{handleError(e,M){const tr=`Subscription error in ${M.eventType} (${M.subscriptionId})`;if(e instanceof Error){const rr=new Error(`${tr}: ${e.message}`);throw rr.cause=e,rr.stack=e.stack,rr}else throw new Error(`${tr}: ${String(e)}`)}}class ReactorSubscriptionManager{createdSubscriptions=new Map;deletedSubscriptions=new Map;updatedSubscriptions=new Map;relationshipSubscriptions=new Map;subscriptionCounter=0;errorHandler;constructor(e){this.errorHandler=e}onDocumentCreated(e,M){const tr=`created-${++this.subscriptionCounter}`;return this.createdSubscriptions.set(tr,{id:tr,callback:e,search:M}),()=>{this.createdSubscriptions.delete(tr)}}onDocumentDeleted(e,M){const tr=`deleted-${++this.subscriptionCounter}`;return this.deletedSubscriptions.set(tr,{id:tr,callback:e,search:M}),()=>{this.deletedSubscriptions.delete(tr)}}onDocumentStateUpdated(e,M,tr){const rr=`updated-${++this.subscriptionCounter}`;return this.updatedSubscriptions.set(rr,{id:rr,callback:e,search:M,view:tr}),()=>{this.updatedSubscriptions.delete(rr)}}onRelationshipChanged(e,M){const tr=`relationship-${++this.subscriptionCounter}`;return this.relationshipSubscriptions.set(tr,{id:tr,callback:e,search:M}),()=>{this.relationshipSubscriptions.delete(tr)}}notifyDocumentsCreated(e,M,tr){const rr={results:e,options:{cursor:"",limit:e.length}};for(const ir of this.createdSubscriptions.values()){const lr=this.filterDocumentIds(e,ir.search,M,tr);if(lr.length>0)try{ir.callback({...rr,results:lr})}catch(dr){this.errorHandler.handleError(dr,{eventType:"created",subscriptionId:ir.id,eventData:lr})}}}notifyDocumentsDeleted(e,M,tr){for(const rr of this.deletedSubscriptions.values()){const ir=this.filterDocumentIds(e,rr.search,M,tr);if(ir.length>0)try{rr.callback(ir)}catch(lr){this.errorHandler.handleError(lr,{eventType:"deleted",subscriptionId:rr.id,eventData:ir})}}}notifyDocumentsUpdated(e){const M={results:e,options:{cursor:"",limit:e.length}};for(const tr of this.updatedSubscriptions.values()){const rr=this.filterDocuments(e,tr.search);if(rr.length>0)try{tr.callback({...M,results:rr})}catch(ir){this.errorHandler.handleError(ir,{eventType:"updated",subscriptionId:tr.id,eventData:rr})}}}notifyRelationshipChanged(e,M,tr,rr){for(const ir of this.relationshipSubscriptions.values())if(this.matchesRelationshipFilter(e,M,rr,ir.search))try{ir.callback(e,M,tr)}catch(lr){this.errorHandler.handleError(lr,{eventType:"relationshipChanged",subscriptionId:ir.id,eventData:{parentId:e,childId:M,changeType:tr}})}}clearAll(){this.createdSubscriptions.clear(),this.deletedSubscriptions.clear(),this.updatedSubscriptions.clear(),this.relationshipSubscriptions.clear()}filterDocumentIds(e,M,tr,rr){return M?e.filter(ir=>!(M.ids&&!M.ids.includes(ir)||M.type&&tr&&tr.get(ir)!==M.type||M.parentId&&rr&&rr.get(ir)!==M.parentId)):e}filterDocuments(e,M){return M?e.filter(tr=>!(M.ids&&!M.ids.includes(tr.header.id)||M.type&&tr.header.documentType!==M.type||M.slugs&&!M.slugs.includes(tr.header.slug))):e}matchesRelationshipFilter(e,M,tr,rr){return rr?!(rr.parentId&&e!==rr.parentId||rr.ids&&!rr.ids.includes(M)||rr.type&&tr&&tr!==rr.type):!0}}class SubscriptionNotificationReadModel{subscriptionManager;documentView;constructor(e,M){this.subscriptionManager=e,this.documentView=M}async indexOperations(e){if(e.length===0)return;const M=[],tr=[],rr=new Set,ir=new Map,lr=new Map;for(const dr of e){const{operation:hr,context:fr}=dr,mr=hr.action.type;if(ir.set(fr.documentId,fr.documentType),mr==="CREATE_DOCUMENT")M.push(fr.documentId);else if(mr==="DELETE_DOCUMENT"){const gr=hr.action.input.documentId??fr.documentId;tr.push(gr)}else if(mr==="ADD_RELATIONSHIP"){const _r=hr.action.input;this.subscriptionManager.notifyRelationshipChanged(_r.sourceId,_r.targetId,RelationshipChangeType.Added,_r.childType)}else if(mr==="REMOVE_RELATIONSHIP"){const _r=hr.action.input;this.subscriptionManager.notifyRelationshipChanged(_r.sourceId,_r.targetId,RelationshipChangeType.Removed,_r.childType)}else M.includes(fr.documentId)||rr.add(fr.documentId)}if(M.length>0&&this.subscriptionManager.notifyDocumentsCreated(M,ir,lr),tr.length>0&&this.subscriptionManager.notifyDocumentsDeleted(tr,ir,lr),rr.size>0&&this.documentView){const dr=await Promise.all(Array.from(rr).map(hr=>this.documentView.get(hr)));this.subscriptionManager.notifyDocumentsUpdated(dr)}}}function rowToRemoteCursor(r){return{remoteName:r.remote_name,cursorType:r.cursor_type,cursorOrdinal:Number(r.cursor_ordinal),lastSyncedAtUtcMs:r.last_synced_at_utc_ms?new Date(r.last_synced_at_utc_ms).getTime():void 0}}function remoteCursorToRow(r){return{remote_name:r.remoteName,cursor_type:r.cursorType,cursor_ordinal:BigInt(r.cursorOrdinal),last_synced_at_utc_ms:r.lastSyncedAtUtcMs?new Date(r.lastSyncedAtUtcMs).toISOString():null}}class KyselySyncCursorStorage{db;constructor(e){this.db=e}async list(e,M){if(M?.aborted)throw new Error("Operation aborted");const tr=await this.db.selectFrom("sync_cursors").selectAll().where("remote_name","=",e).execute();if(M?.aborted)throw new Error("Operation aborted");return tr.map(rowToRemoteCursor)}async get(e,M,tr){if(tr?.aborted)throw new Error("Operation aborted");const rr=await this.db.selectFrom("sync_cursors").selectAll().where("remote_name","=",e).where("cursor_type","=",M).executeTakeFirst();if(tr?.aborted)throw new Error("Operation aborted");return rr?rowToRemoteCursor(rr):{remoteName:e,cursorType:M,cursorOrdinal:0}}async upsert(e,M){if(M?.aborted)throw new Error("Operation aborted");if(await this.db.transaction().execute(async tr=>{const rr=remoteCursorToRow(e);await tr.insertInto("sync_cursors").values(rr).onConflict(ir=>ir.columns(["remote_name","cursor_type"]).doUpdateSet({...rr,updated_at:sql`NOW()`})).execute()}),M?.aborted)throw new Error("Operation aborted")}async remove(e,M){if(M?.aborted)throw new Error("Operation aborted");if(await this.db.transaction().execute(async tr=>{await tr.deleteFrom("sync_cursors").where("remote_name","=",e).execute()}),M?.aborted)throw new Error("Operation aborted")}}function rowToRemoteRecord(r){return{id:r.channel_id,name:r.name,collectionId:r.collection_id,channelConfig:{type:r.channel_type,parameters:r.channel_parameters??{}},filter:{documentId:r.filter_document_ids??[],scope:r.filter_scopes??[],branch:r.filter_branch},options:{sinceTimestampUtcMs:"0"},status:{push:{state:r.push_state,lastSuccessUtcMs:r.push_last_success_utc_ms?new Date(r.push_last_success_utc_ms).getTime():void 0,lastFailureUtcMs:r.push_last_failure_utc_ms?new Date(r.push_last_failure_utc_ms).getTime():void 0,failureCount:r.push_failure_count},pull:{state:r.pull_state,lastSuccessUtcMs:r.pull_last_success_utc_ms?new Date(r.pull_last_success_utc_ms).getTime():void 0,lastFailureUtcMs:r.pull_last_failure_utc_ms?new Date(r.pull_last_failure_utc_ms).getTime():void 0,failureCount:r.pull_failure_count}}}}function remoteRecordToRow(r){return{name:r.name,collection_id:r.collectionId,channel_type:r.channelConfig.type,channel_id:r.id,remote_name:r.name,channel_parameters:r.channelConfig.parameters,filter_document_ids:r.filter.documentId.length>0?r.filter.documentId:null,filter_scopes:r.filter.scope.length>0?r.filter.scope:null,filter_branch:r.filter.branch,push_state:r.status.push.state,push_last_success_utc_ms:r.status.push.lastSuccessUtcMs?new Date(r.status.push.lastSuccessUtcMs).toISOString():null,push_last_failure_utc_ms:r.status.push.lastFailureUtcMs?new Date(r.status.push.lastFailureUtcMs).toISOString():null,push_failure_count:r.status.push.failureCount,pull_state:r.status.pull.state,pull_last_success_utc_ms:r.status.pull.lastSuccessUtcMs?new Date(r.status.pull.lastSuccessUtcMs).toISOString():null,pull_last_failure_utc_ms:r.status.pull.lastFailureUtcMs?new Date(r.status.pull.lastFailureUtcMs).toISOString():null,pull_failure_count:r.status.pull.failureCount}}class KyselySyncRemoteStorage{db;constructor(e){this.db=e}async list(e){if(e?.aborted)throw new Error("Operation aborted");const M=await this.db.selectFrom("sync_remotes").selectAll().execute();if(e?.aborted)throw new Error("Operation aborted");return M.map(rowToRemoteRecord)}async get(e,M){if(M?.aborted)throw new Error("Operation aborted");const tr=await this.db.selectFrom("sync_remotes").selectAll().where("name","=",e).executeTakeFirst();if(M?.aborted)throw new Error("Operation aborted");if(!tr)throw new Error(`Remote not found: ${e}`);return rowToRemoteRecord(tr)}async upsert(e,M){if(M?.aborted)throw new Error("Operation aborted");if(await this.db.transaction().execute(async tr=>{const rr=remoteRecordToRow(e);await tr.insertInto("sync_remotes").values(rr).onConflict(ir=>ir.column("name").doUpdateSet({...rr,updated_at:sql`NOW()`})).execute()}),M?.aborted)throw new Error("Operation aborted")}async remove(e,M){if(M?.aborted)throw new Error("Operation aborted");if(await this.db.transaction().execute(async tr=>{await tr.deleteFrom("sync_remotes").where("name","=",e).execute()}),M?.aborted)throw new Error("Operation aborted")}}class BatchAggregator{logger;onBatchReady;queue=[];processing=!1;pendingBatches=new Map;constructor(e,M){this.logger=e,this.onBatchReady=M}async enqueueWriteReady(e){this.queue.push(e),await this.processQueue()}async handleJobFailed(e){const M=e.job?.meta.batchId;if(!M)return;const tr=this.pendingBatches.get(M);tr&&(this.pendingBatches.delete(M),tr.events.length>0&&await this.onBatchReady(this.prepareBatch(tr.events)))}clear(){this.queue=[],this.pendingBatches.clear()}async processQueue(){if(!this.processing){this.processing=!0;try{for(;this.queue.length>0;){const e=this.queue.shift();try{await this.handleWriteReady(e)}catch(M){const tr=M instanceof Error?M:new Error(String(M));this.logger.error("Failed to process write-ready event (@jobId, @error)",e.jobId,tr.message)}}}finally{this.processing=!1}}}async handleWriteReady(e){const{batchId:M,batchJobIds:tr}=e.jobMeta;if(tr.length<=1){await this.onBatchReady(this.prepareBatch([e]));return}let rr=this.pendingBatches.get(M);rr||(rr={expectedJobIds:new Set(tr),arrivedJobIds:new Set,events:[]},this.pendingBatches.set(M,rr)),rr.arrivedJobIds.add(e.jobId),rr.events.push(e),rr.arrivedJobIds.size>=rr.expectedJobIds.size&&(this.pendingBatches.delete(M),await this.onBatchReady(this.prepareBatch(rr.events)))}prepareBatch(e){const M=mergeCollectionMemberships(e),tr=e.length>1,rr=[],ir=[];for(const lr of e)ir.push({event:lr,jobDependencies:tr?[...rr]:[]}),tr&&lr.jobId&&rr.push(lr.jobId);return{collectionMemberships:M,entries:ir}}}class SyncAwaiter{eventBus;completedResults=new Map;pendingWaiters=new Map;unsubscribers=[];isShutdown=!1;constructor(e){this.eventBus=e,this.subscribeToEvents()}waitForSync(e,M){if(M?.aborted)return Promise.reject(new Error("Operation aborted"));if(this.isShutdown)return Promise.reject(new Error("SyncAwaiter is shutdown"));const tr=this.completedResults.get(e);return tr?Promise.resolve(tr):new Promise((rr,ir)=>{const lr={resolve:rr,reject:ir,signal:M},dr=this.pendingWaiters.get(e)||[];if(dr.push(lr),this.pendingWaiters.set(e,dr),M){const hr=()=>{const fr=this.pendingWaiters.get(e);if(fr){const mr=fr.indexOf(lr);mr!==-1&&(fr.splice(mr,1),fr.length===0&&this.pendingWaiters.delete(e),lr.reject(new Error("Operation aborted")))}};M.addEventListener("abort",hr,{once:!0})}})}shutdown(){this.isShutdown=!0;for(const e of this.unsubscribers)e();this.unsubscribers.length=0;for(const[,e]of this.pendingWaiters)for(const M of e)M.reject(new Error("SyncAwaiter shutdown"));this.pendingWaiters.clear()}subscribeToEvents(){this.unsubscribers.push(this.eventBus.subscribe(SyncEventTypes.SYNC_SUCCEEDED,(e,M)=>{this.handleSyncSucceeded(M)})),this.unsubscribers.push(this.eventBus.subscribe(SyncEventTypes.SYNC_FAILED,(e,M)=>{this.handleSyncFailed(M)}))}handleSyncSucceeded(e){const M={jobId:e.jobId,status:"succeeded",syncOperationCount:e.syncOperationCount,successCount:e.syncOperationCount,failureCount:0,errors:[]};this.completedResults.set(e.jobId,M),this.resolveWaiters(e.jobId,M)}handleSyncFailed(e){const M={jobId:e.jobId,status:"failed",syncOperationCount:e.successCount+e.failureCount,successCount:e.successCount,failureCount:e.failureCount,errors:e.errors};this.completedResults.set(e.jobId,M),this.resolveWaiters(e.jobId,M)}resolveWaiters(e,M){const tr=this.pendingWaiters.get(e);if(!(!tr||tr.length===0)){this.pendingWaiters.delete(e);for(const rr of tr)rr.signal?.aborted?rr.reject(new Error("Operation aborted")):rr.resolve(M)}}}var SyncStatus;(function(r){r.Synced="SYNCED",r.Outgoing="OUTGOING",r.Incoming="INCOMING",r.OutgoingAndIncoming="OUTGOING_AND_INCOMING",r.Error="ERROR"})(SyncStatus||(SyncStatus={}));class SyncStatusTracker{remotes=new Map;seen=new Set;callbacks=new Set;getStatus(e){if(!this.seen.has(e))return;let M=0,tr=0,rr=0;for(const ir of this.remotes.values()){const lr=ir.get(e);lr&&(M+=lr.inboxCount,tr+=lr.outboxCount,rr+=lr.errorCount)}return deriveStatus(M,tr,rr)}onChange(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e)}}trackRemote(e,M){this.remotes.set(e,new Map),M.inbox.onAdded(tr=>this.handleAdded(e,"inbox",tr)),M.inbox.onRemoved(tr=>this.handleRemoved(e,"inbox",tr)),M.outbox.onAdded(tr=>this.handleAdded(e,"outbox",tr)),M.outbox.onRemoved(tr=>this.handleRemoved(e,"outbox",tr)),M.deadLetter.onAdded(tr=>this.handleAdded(e,"deadLetter",tr))}untrackRemote(e){const M=this.remotes.get(e);if(!M)return;const tr=[...M.keys()];this.remotes.delete(e);for(const rr of tr)this.notifyChange(rr)}clear(){this.remotes.clear(),this.seen.clear(),this.callbacks.clear()}handleAdded(e,M,tr){const rr=new Set;for(const ir of tr){if(M==="inbox"&&!ir.remoteName)continue;const lr=this.getOrCreateCounts(e,ir.documentId);this.seen.add(ir.documentId),M==="inbox"?lr.inboxCount++:M==="outbox"?lr.outboxCount++:lr.errorCount++,rr.add(ir.documentId)}for(const ir of rr)this.notifyChange(ir)}handleRemoved(e,M,tr){const rr=new Set;for(const ir of tr){const lr=this.getOrCreateCounts(e,ir.documentId);M==="inbox"?lr.inboxCount=Math.max(0,lr.inboxCount-1):M==="outbox"&&(lr.outboxCount=Math.max(0,lr.outboxCount-1)),rr.add(ir.documentId)}for(const ir of rr)this.notifyChange(ir)}getOrCreateCounts(e,M){let tr=this.remotes.get(e);tr||(tr=new Map,this.remotes.set(e,tr));let rr=tr.get(M);return rr||(rr={inboxCount:0,outboxCount:0,errorCount:0},tr.set(M,rr)),rr}notifyChange(e){const M=this.getStatus(e);if(M!==void 0)for(const tr of[...this.callbacks])tr(e,M)}}function deriveStatus(r,e,M){return M>0?SyncStatus.Error:r>0&&e>0?SyncStatus.OutgoingAndIncoming:r>0?SyncStatus.Incoming:e>0?SyncStatus.Outgoing:SyncStatus.Synced}class SyncManager{logger;remoteStorage;cursorStorage;channelFactory;operationIndex;reactor;eventBus;remotes;awaiter;syncAwaiter;isShutdown;eventUnsubscribe;failedEventUnsubscribe;batchAggregator;syncStatusTracker;loadJobs=new Map;constructor(e,M,tr,rr,ir,lr,dr){this.logger=e,this.remoteStorage=M,this.cursorStorage=tr,this.channelFactory=rr,this.operationIndex=ir,this.reactor=lr,this.eventBus=dr,this.remotes=new Map,this.awaiter=new JobAwaiter(dr,(hr,fr)=>lr.getJobStatus(hr,fr)),this.syncAwaiter=new SyncAwaiter(dr),this.isShutdown=!1,this.batchAggregator=new BatchAggregator(e,hr=>this.processCompleteBatch(hr)),this.syncStatusTracker=new SyncStatusTracker}async startup(){if(this.isShutdown)throw new Error("SyncManager is already shutdown and cannot be started");const e=await this.remoteStorage.list();for(const M of e){const tr=this.channelFactory.instance(M.id,M.name,M.channelConfig,this.cursorStorage,M.collectionId,M.filter,this.operationIndex),rr={id:M.id,name:M.name,collectionId:M.collectionId,filter:M.filter,options:M.options,channel:tr};this.remotes.set(M.name,rr),this.wireChannelCallbacks(rr);try{await tr.init()}catch(lr){this.logger.error("Error initializing channel for remote (@name, @error)",M.name,lr instanceof Error?lr.message:String(lr)),this.remotes.delete(M.name);continue}const ir=rr.channel.outbox.ackOrdinal;ir>0&&await this.updateOutbox(rr,ir)}this.eventUnsubscribe=this.eventBus.subscribe(ReactorEventTypes.JOB_WRITE_READY,async(M,tr)=>this.batchAggregator.enqueueWriteReady(tr)),this.failedEventUnsubscribe=this.eventBus.subscribe(ReactorEventTypes.JOB_FAILED,async(M,tr)=>this.batchAggregator.handleJobFailed(tr))}shutdown(){this.isShutdown=!0,this.batchAggregator.clear(),this.eventUnsubscribe&&(this.eventUnsubscribe(),this.eventUnsubscribe=void 0),this.failedEventUnsubscribe&&(this.failedEventUnsubscribe(),this.failedEventUnsubscribe=void 0),this.awaiter.shutdown(),this.syncAwaiter.shutdown(),this.syncStatusTracker.clear();const e=[];for(const M of this.remotes.values())e.push(M.channel.shutdown());return this.remotes.clear(),{isShutdown:!0,completed:Promise.all(e).then(()=>{})}}getByName(e){const M=this.remotes.get(e);if(!M)throw new Error(`Remote with name '${e}' does not exist`);return M}getById(e){for(const M of this.remotes.values())if(M.id===e)return M;throw new Error(`Remote with id '${e}' does not exist`)}async add(e,M,tr,rr={documentId:[],scope:[],branch:""},ir={sinceTimestampUtcMs:"0"},lr){if(this.isShutdown)throw new Error("SyncManager is shutdown and cannot add remotes");if(this.remotes.has(e))throw new Error(`Remote with name '${e}' already exists`);this.logger.debug("Adding remote (@name, @collectionId, @channelConfig, @filter, @options, @id)",e,M,tr,rr,ir,lr);const dr=lr??crypto.randomUUID(),hr={push:createIdleHealth(),pull:createIdleHealth()},fr={id:dr,name:e,collectionId:M,channelConfig:tr,filter:rr,options:ir,status:hr};await this.remoteStorage.upsert(fr);const mr=this.channelFactory.instance(dr,e,tr,this.cursorStorage,M,rr,this.operationIndex),_r={id:dr,name:e,collectionId:M,filter:rr,options:ir,channel:mr};this.remotes.set(e,_r),this.wireChannelCallbacks(_r);try{await mr.init()}catch(gr){throw this.remotes.delete(e),await this.remoteStorage.remove(e),gr}return await this.updateOutbox(_r,0),_r}async remove(e){const M=this.remotes.get(e);if(!M)throw new Error(`Remote with name '${e}' does not exist`);await M.channel.shutdown(),await this.remoteStorage.remove(e),await this.cursorStorage.remove(e),this.syncStatusTracker.untrackRemote(e),this.remotes.delete(e)}list(){return Array.from(this.remotes.values())}waitForSync(e,M){return this.syncAwaiter.waitForSync(e,M)}getSyncStatus(e){return this.syncStatusTracker.getStatus(e)}onSyncStatusChange(e){return this.syncStatusTracker.onChange(e)}wireChannelCallbacks(e){e.channel.inbox.onAdded(M=>this.handleInboxAdded(e,M)),this.syncStatusTracker.trackRemote(e.name,e.channel),e.channel.deadLetter.onAdded(M=>{for(const tr of M)this.logger.error("Dead letter (@remote, @documentId, @jobId, @error, @dependencies)",e.name,tr.documentId,tr.jobId,tr.error?.message??"unknown",tr.jobDependencies)})}getRemotesForCollection(e){return Array.from(this.remotes.values()).filter(M=>M.collectionId===e)}async processCompleteBatch(e){const M=[...new Set(Object.values(e.collectionMemberships).flatMap(rr=>rr))],tr=[];for(const rr of M){const ir=this.getRemotesForCollection(rr);for(const lr of ir)tr.includes(lr)||tr.push(lr)}for(const rr of tr)trimMailboxFromBatch(rr.channel.inbox,e);for(const rr of tr)await this.updateOutbox(rr,rr.channel.outbox.latestOrdinal)}handleInboxAdded(e,M){if(this.isShutdown)return;const tr=[],rr=[];for(const ir of M)ir.jobId?tr.push(ir):rr.push(ir);for(const ir of rr)this.applyInboxJob(e,ir);tr.length>0&&this.applyInboxBatch(tr.map(ir=>({remote:e,syncOp:ir})))}async applyInboxJob(e,M){const tr=M.operations.map(dr=>dr.operation);let rr;try{rr=await this.reactor.load(M.documentId,M.branch,tr,void 0,{sourceRemote:e.name})}catch(dr){const hr=dr instanceof Error?dr:new Error(String(dr));this.logger.error("Failed to load operations from inbox (@remote, @documentId, @error)",e.name,M.documentId,hr.message);const fr=new ChannelError(ChannelErrorSource.Inbox,hr);M.failed(fr),e.channel.deadLetter.add(M),e.channel.inbox.remove(M);return}let ir;try{ir=await this.awaiter.waitForJob(rr.id)}catch(dr){const hr=dr instanceof Error?dr:new Error(String(dr));this.logger.error("Failed to wait for job completion (@remote, @documentId, @jobId, @error)",e.name,M.documentId,rr.id,hr.message);const fr=new ChannelError(ChannelErrorSource.Inbox,hr);M.failed(fr),e.channel.deadLetter.add(M),e.channel.inbox.remove(M);return}const lr=`${M.documentId}:${M.branch}`;if(this.loadJobs.set(lr,ir),ir.status===JobStatus.FAILED){const dr=ir.error?.message||"Unknown error";this.logger.error("Failed to apply operations from inbox (@remote, @documentId, @jobId, @error)",e.name,M.documentId,ir.id,dr);const hr=new ChannelError(ChannelErrorSource.Inbox,new Error(`Failed to apply operations: ${dr}`));M.failed(hr),e.channel.deadLetter.add(M)}else M.executed();e.channel.inbox.remove(M)}async applyInboxBatch(e){const M=e[0].remote.name,rr={jobs:e.map(({syncOp:lr})=>({key:lr.jobId,documentId:lr.documentId,scope:lr.scopes[0],branch:lr.branch,operations:lr.operations.map(dr=>dr.operation),dependsOn:lr.jobDependencies.filter(Boolean)}))};let ir;try{ir=await this.reactor.loadBatch(rr,void 0,{sourceRemote:M})}catch(lr){for(const{remote:dr,syncOp:hr}of e){const fr=lr instanceof Error?lr:new Error(String(lr));hr.failed(new ChannelError(ChannelErrorSource.Inbox,fr)),dr.channel.deadLetter.add(hr),dr.channel.inbox.remove(hr)}return}for(const{remote:lr,syncOp:dr}of e){if(!(dr.jobId in ir.jobs)){this.logger.error("Job key missing from batch load result (@remote, @documentId, @jobId)",lr.name,dr.documentId,dr.jobId);const _r=new ChannelError(ChannelErrorSource.Inbox,new Error(`Job key '${dr.jobId}' missing from batch load result`));dr.failed(_r),lr.channel.deadLetter.add(dr),lr.channel.inbox.remove(dr);continue}const hr=ir.jobs[dr.jobId];let fr;try{fr=await this.awaiter.waitForJob(hr.id)}catch(_r){const gr=_r instanceof Error?_r:new Error(String(_r));dr.failed(new ChannelError(ChannelErrorSource.Inbox,gr)),lr.channel.deadLetter.add(dr),lr.channel.inbox.remove(dr);continue}const mr=`${dr.documentId}:${dr.branch}`;if(this.loadJobs.set(mr,fr),fr.status===JobStatus.FAILED){const _r=fr.error?.message||"Unknown error",gr=new ChannelError(ChannelErrorSource.Inbox,new Error(`Failed to apply operations: ${_r}`));dr.failed(gr),lr.channel.deadLetter.add(dr)}else dr.executed();lr.channel.inbox.remove(dr)}}async updateOutbox(e,M){const tr=await this.getOperationsForRemote(e,M);if(tr.length===0)return;const rr=batchOperationsByDocument(tr);let ir;const lr=[];for(const dr of rr){const hr=crypto.randomUUID(),fr=new SyncOperation(crypto.randomUUID(),hr,ir?[ir]:[],e.name,dr.documentId,[dr.scope],dr.branch,dr.operations);lr.push(fr),ir=hr}e.channel.outbox.add(...lr)}async getOperationsForRemote(e,M){let rr=(await this.operationIndex.find(e.collectionId,M,{excludeSourceRemote:e.name})).results.map(lr=>toOperationWithContext(lr));const ir=e.options.sinceTimestampUtcMs;return ir&&ir!=="0"&&(rr=rr.filter(lr=>lr.operation.timestampUtcMs>=ir)),filterOperations(rr,e.filter)}}class SyncBuilder{channelFactory;remoteStorage;cursorStorage;withChannelFactory(e){return this.channelFactory=e,this}withRemoteStorage(e){return this.remoteStorage=e,this}withCursorStorage(e){return this.cursorStorage=e,this}build(e,M,tr,rr,ir){return this.buildModule(e,M,tr,rr,ir).syncManager}buildModule(e,M,tr,rr,ir){if(!this.channelFactory)throw new Error("Channel factory is required");const lr=this.remoteStorage??new KyselySyncRemoteStorage(ir),dr=this.cursorStorage??new KyselySyncCursorStorage(ir),hr=new SyncManager(M,lr,dr,this.channelFactory,tr,e,rr);return{remoteStorage:lr,cursorStorage:dr,channelFactory:this.channelFactory,syncManager:hr}}}function createMutableShutdownStatus(r=!1){let e=r,M=Promise.resolve();return[{get isShutdown(){return e},get completed(){return M}},lr=>{e=lr},lr=>{M=lr}]}function matchesScope(r={},e){return r.scopes?r.scopes.includes(e):!0}class Reactor{logger;documentModelRegistry;shutdownStatus;setShutdown;setCompleted;queue;jobTracker;readModelCoordinator;features;documentView;documentIndexer;operationStore;eventBus;executorManager;constructor(e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r){this.logger=e,this.documentModelRegistry=M,this.queue=tr,this.jobTracker=rr,this.readModelCoordinator=ir,this.features=lr,this.documentView=dr,this.documentIndexer=hr,this.operationStore=fr,this.eventBus=mr,this.executorManager=_r;const[gr,wr,yr]=createMutableShutdownStatus(!1);this.shutdownStatus=gr,this.setShutdown=wr,this.setCompleted=yr,this.eventBus.subscribe(ReactorEventTypes.JOB_FAILED,(br,Mr)=>{this.logger.error("Job @JobId failed with @Message: @Job",Mr.jobId,Mr.error.message,Mr.job)}),this.readModelCoordinator.start()}kill(){if(this.logger.verbose("kill()"),this.shutdownStatus.isShutdown)return this.shutdownStatus;this.setShutdown(!0);const e=async()=>{await this.executorManager.stop(!0),this.readModelCoordinator.stop(),this.jobTracker.shutdown()};return this.setCompleted(e()),this.shutdownStatus}getDocumentModels(e,M,tr){if(this.logger.verbose("getDocumentModels(@namespace, @paging)",e,M),tr?.aborted)throw new AbortError;const ir=this.documentModelRegistry.getAllModules().filter(_r=>!e||_r.documentModel.global.id.startsWith(e)),lr=M&&parseInt(M.cursor)||0,dr=M?.limit||ir.length,hr=ir.slice(lr,lr+dr),fr=lr+dr<ir.length,mr=fr?String(lr+dr):void 0;return Promise.resolve({results:hr,options:M||{cursor:"0",limit:ir.length},nextCursor:mr,next:fr?()=>this.getDocumentModels(e,{cursor:mr,limit:dr},tr):void 0})}async get(e,M,tr,rr){return this.logger.verbose("get(@id, @view)",e,M),await this.documentView.get(e,M,tr,rr)}async getBySlug(e,M,tr,rr){this.logger.verbose("getBySlug(@slug, @view)",e,M);const ir=await this.documentView.resolveSlug(e,M,tr,rr);if(!ir)throw new Error(`Document not found with slug: ${e}`);return await this.get(ir,M,tr,rr)}async getByIdOrSlug(e,M,tr,rr){return this.logger.verbose("getByIdOrSlug(@identifier, @view)",e,M),await this.documentView.getByIdOrSlug(e,M,tr,rr)}async getChildren(e,M,tr){const rr=await this.documentIndexer.getOutgoing(e,["child"],void 0,M,tr);if(tr?.aborted)throw new AbortError;return rr.results.map(ir=>ir.targetId)}async getParents(e,M,tr){const rr=await this.documentIndexer.getIncoming(e,["parent"],void 0,M,tr);if(tr?.aborted)throw new AbortError;return rr.results.map(ir=>ir.sourceId)}async getOperations(e,M,tr,rr,ir,lr){this.logger.verbose("getOperations(@documentId, @view, @filter, @paging)",e,M,tr,rr);const dr=M?.branch||"main",hr=await this.operationStore.getRevisions(e,dr,lr);if(lr?.aborted)throw new AbortError;const fr=Object.keys(hr.revision),mr={};for(const _r of fr){if(!matchesScope(M,_r))continue;if(lr?.aborted)throw new AbortError;const gr=await this.operationStore.getSince(e,_r,dr,-1,tr,rr,lr);mr[_r]={results:gr.results,options:gr.options,nextCursor:gr.nextCursor,next:gr.next?async()=>(await this.getOperations(e,M,tr,{cursor:gr.nextCursor,limit:gr.options.limit},ir,lr))[_r]:void 0}}return mr}async find(e,M,tr,rr,ir){this.logger.verbose("find(@search, @view, @paging)",e,M,tr);let lr;if(e.ids){if(e.slugs&&e.slugs.length>0)throw new Error("Cannot use both ids and slugs in the same search");lr=await this.findByIds(e.ids,M,tr,rr,ir),e.type&&(lr=filterByType(lr,e.type))}else if(e.slugs)lr=await this.findBySlugs(e.slugs,M,tr,rr,ir),e.type&&(lr=filterByType(lr,e.type));else if(e.parentId)lr=await this.findByParentId(e.parentId,M,tr,rr,ir),e.type&&(lr=filterByType(lr,e.type));else if(e.type)lr=await this.findByType(e.type,M,tr,rr,ir);else throw new Error("No search criteria provided");if(ir?.aborted)throw new AbortError;return lr}async create(e,M,tr,rr){this.logger.verbose("create(@id, @type, @slug)",e.header.id,e.header.documentType,e.header.slug);const ir=new Date().toISOString();if(tr?.aborted)throw new AbortError;const lr={model:e.header.documentType,version:0,documentId:e.header.id,signing:{signature:e.header.id,publicKey:e.header.sig.publicKey,nonce:e.header.sig.nonce,createdAtUtcIso:e.header.createdAtUtcIso,documentType:e.header.documentType},slug:e.header.slug,name:e.header.name,branch:e.header.branch,meta:e.header.meta,protocolVersions:e.header.protocolVersions??{"base-reducer":2}},dr=createDocumentAction(lr),hr=upgradeDocumentAction({documentId:e.header.id,model:e.header.documentType,fromVersion:0,toVersion:e.state.document.version,initialState:e.state});let fr=[dr,hr];M&&(fr=await signActions(fr,M,tr));const mr=v4(),_r=buildSingleJobMeta(mr,rr),gr={id:mr,kind:"mutation",documentId:e.header.id,scope:"document",branch:"main",actions:fr,operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:_r},wr={id:mr,status:JobStatus.PENDING,createdAtUtcIso:ir,consistencyToken:{version:1,createdAtUtcIso:ir,coordinates:[]},meta:_r};return this.jobTracker.registerJob(wr),this.emitJobPending(wr.id,_r),await this.queue.enqueue(gr),wr}async deleteDocument(e,M,tr,rr){this.logger.verbose("deleteDocument(@id)",e);const ir=new Date().toISOString();if(tr?.aborted)throw new AbortError;let lr=deleteDocumentAction(e);M&&(lr=await signAction(lr,M,tr));const dr=v4(),hr=buildSingleJobMeta(dr,rr),fr={id:dr,kind:"mutation",documentId:e,scope:"document",branch:"main",actions:[lr],operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:hr},mr={id:dr,status:JobStatus.PENDING,createdAtUtcIso:ir,consistencyToken:{version:1,createdAtUtcIso:ir,coordinates:[]},meta:hr};return this.jobTracker.registerJob(mr),this.emitJobPending(mr.id,hr),await this.queue.enqueue(fr),mr}async execute(e,M,tr,rr,ir){if(this.logger.verbose("execute(@docId, @branch, @actions)",e,M,tr),rr?.aborted)throw new AbortError;const lr=new Date().toISOString(),dr=getSharedActionScope(tr),hr=v4(),fr=buildSingleJobMeta(hr,ir),mr={id:hr,kind:"mutation",documentId:e,scope:dr,branch:M,actions:tr,operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:fr},_r={id:hr,status:JobStatus.PENDING,createdAtUtcIso:lr,consistencyToken:{version:1,createdAtUtcIso:lr,coordinates:[]},meta:fr};if(this.jobTracker.registerJob(_r),this.emitJobPending(_r.id,fr),await this.queue.enqueue(mr),rr?.aborted)throw new AbortError;return _r}async load(e,M,tr,rr,ir){if(this.logger.verbose("load(@docId, @branch, @count, @operations)",e,M,tr.length,tr),rr?.aborted)throw new AbortError;if(tr.length===0)throw new Error("load requires at least one operation");const lr=getSharedOperationScope(tr),dr=new Date().toISOString(),hr=v4(),fr=buildSingleJobMeta(hr,ir),mr={id:hr,kind:"load",documentId:e,scope:lr,branch:M,actions:[],operations:tr,createdAt:dr,queueHint:[],maxRetries:3,errorHistory:[],meta:fr},_r={id:hr,status:JobStatus.PENDING,createdAtUtcIso:dr,consistencyToken:{version:1,createdAtUtcIso:dr,coordinates:[]},meta:fr};if(this.jobTracker.registerJob(_r),this.emitJobPending(_r.id,fr),await this.queue.enqueue(mr),rr?.aborted)throw new AbortError;return _r}async executeBatch(e,M,tr){if(this.logger.verbose("executeBatch(@count jobs)",e.jobs.length),M?.aborted)throw new AbortError;validateBatchRequest(e.jobs);for(const wr of e.jobs)validateActionScopes(wr);const rr=new Date().toISOString(),ir=new Map;for(const wr of e.jobs)ir.set(wr.key,v4());const lr=v4(),dr=[...ir.values()],hr={...tr,batchId:lr,batchJobIds:dr},fr=new Map;for(const wr of e.jobs){const br={id:ir.get(wr.key),status:JobStatus.PENDING,createdAtUtcIso:rr,consistencyToken:{version:1,createdAtUtcIso:rr,coordinates:[]},meta:hr};this.jobTracker.registerJob(br),this.emitJobPending(br.id,hr),fr.set(wr.key,br)}const mr=topologicalSort(e.jobs),_r=[];try{for(const wr of mr){if(M?.aborted)throw new AbortError;const yr=e.jobs.find(Sr=>Sr.key===wr),br=ir.get(wr),Mr=yr.dependsOn.map(Sr=>ir.get(Sr)),vr={id:br,kind:"mutation",documentId:yr.documentId,scope:yr.scope,branch:yr.branch,actions:yr.actions,operations:[],createdAt:rr,queueHint:Mr,maxRetries:3,errorHistory:[],meta:hr};await this.queue.enqueue(vr),_r.push(wr)}}catch(wr){for(const yr of _r){const br=ir.get(yr);try{await this.queue.remove(br)}catch{}}for(const yr of fr.values())this.jobTracker.markFailed(yr.id,toErrorInfo("Batch enqueue failed"));throw wr}return{jobs:Object.fromEntries(fr)}}async loadBatch(e,M,tr){if(this.logger.verbose("loadBatch(@count jobs)",e.jobs.length),M?.aborted)throw new AbortError;validateBatchLoadRequest(e.jobs);for(const wr of e.jobs)validateOperationScopes(wr);const rr=new Date().toISOString(),ir=new Map;for(const wr of e.jobs)ir.set(wr.key,v4());const lr=v4(),dr=[...ir.values()],hr={...tr,batchId:lr,batchJobIds:dr},fr=new Map;for(const wr of e.jobs){const br={id:ir.get(wr.key),status:JobStatus.PENDING,createdAtUtcIso:rr,consistencyToken:{version:1,createdAtUtcIso:rr,coordinates:[]},meta:hr};this.jobTracker.registerJob(br),this.emitJobPending(br.id,hr),fr.set(wr.key,br)}const mr=topologicalSort(e.jobs),_r=[];try{for(const wr of mr){if(M?.aborted)throw new AbortError;const yr=e.jobs.find(Sr=>Sr.key===wr),br=ir.get(wr),Mr=yr.dependsOn.map(Sr=>ir.get(Sr)),vr={id:br,kind:"load",documentId:yr.documentId,scope:yr.scope,branch:yr.branch,actions:[],operations:yr.operations,createdAt:rr,queueHint:Mr,maxRetries:3,errorHistory:[],meta:hr};await this.queue.enqueue(vr),_r.push(wr)}}catch(wr){for(const yr of _r){const br=ir.get(yr);try{await this.queue.remove(br)}catch{}}for(const yr of fr.values())this.jobTracker.markFailed(yr.id,toErrorInfo("Batch enqueue failed"));throw wr}return{jobs:Object.fromEntries(fr)}}async addChildren(e,M,tr="main",rr,ir){if(this.logger.verbose("addChildren(@parentId, @count children, @branch)",e,M.length,tr),ir?.aborted)throw new AbortError;let lr=M.map(dr=>addRelationshipAction(e,dr,"child"));return rr&&(lr=await signActions(lr,rr,ir)),await this.execute(e,tr,lr,ir)}async removeChildren(e,M,tr="main",rr,ir){if(this.logger.verbose("removeChildren(@parentId, @count children, @branch)",e,M.length,tr),ir?.aborted)throw new AbortError;let lr=M.map(dr=>removeRelationshipAction(e,dr,"child"));return rr&&(lr=await signActions(lr,rr,ir)),await this.execute(e,tr,lr,ir)}getJobStatus(e,M){if(this.logger.verbose("getJobStatus(@jobId)",e),M?.aborted)throw new AbortError;const tr=this.jobTracker.getJobStatus(e);if(!tr){const rr=new Date().toISOString();return Promise.resolve({id:e,status:JobStatus.FAILED,createdAtUtcIso:rr,completedAtUtcIso:rr,error:toErrorInfo("Job not found"),consistencyToken:{version:1,createdAtUtcIso:rr,coordinates:[]},meta:{batchId:e,batchJobIds:[e]}})}return Promise.resolve(tr)}async findByIds(e,M,tr,rr,ir){this.logger.verbose("findByIds(@count ids)",e.length);const lr=tr?.cursor&&parseInt(tr.cursor)||0,dr=tr?.limit||e.length,hr=e.slice(lr,lr+dr),fr=await this.documentView.getMany(hr,M,rr,ir),_r=lr+dr<e.length?String(lr+dr):void 0;return{results:fr,options:tr||{cursor:"0",limit:e.length},nextCursor:_r}}async findBySlugs(e,M,tr,rr,ir){this.logger.verbose("findBySlugs(@count slugs)",e.length);const lr=await this.documentView.resolveSlugs(e,M,rr,ir);return await this.findByIds(lr,M,tr,rr,ir)}async findByParentId(e,M,tr,rr,ir){this.logger.verbose("findByParentId(@parentId)",e);const dr=(await this.documentIndexer.getOutgoing(e,["child"],tr,rr,ir)).results.map(hr=>hr.targetId);return await this.findByIds(dr,M,tr,void 0,ir)}async findByType(e,M,tr,rr,ir){return this.logger.verbose("findByType(@type)",e),await this.documentView.findByType(e,M,tr,rr,ir)}emitJobPending(e,M){const tr={jobId:e,jobMeta:M};this.eventBus.emit(ReactorEventTypes.JOB_PENDING,tr).catch(()=>{})}}class ReactorBuilder{logger;documentModels=[];upgradeManifests=[];storage;features={legacyStorageEnabled:!1};readModels=[];executorManager;executorConfig={};writeCacheConfig;migrationStrategy="auto";syncBuilder;eventBus;readModelCoordinator;signatureVerifier;kyselyInstance;signalHandlersEnabled=!1;queueInstance;channelScheme;jwtHandler;documentModelLoader;withLogger(e){return this.logger=e,this}withDocumentModels(e){return this.documentModels=e,this}withUpgradeManifests(e){return this.upgradeManifests=e,this}withLegacyStorage(e){return this.storage=e,this}withFeatures(e){return this.features={...this.features,...e},this}withReadModel(e){return this.readModels.push(e),this}withReadModelCoordinator(e){return this.readModelCoordinator=e,this}withExecutor(e){return this.executorManager=e,this}withExecutorConfig(e){return this.executorConfig={...this.executorConfig,...e},this}withWriteCacheConfig(e){return this.writeCacheConfig=e,this}withMigrationStrategy(e){return this.migrationStrategy=e,this}withSync(e){return this.syncBuilder=e,this}withEventBus(e){return this.eventBus=e,this}withSignatureVerifier(e){return this.signatureVerifier=e,this}withKysely(e){return this.kyselyInstance=e,this}withQueue(e){return this.queueInstance=e,this}withChannelScheme(e){return this.channelScheme=e,this}withJwtHandler(e){return this.jwtHandler=e,this}withDocumentModelLoader(e){return this.documentModelLoader=e,this}withSignalHandlers(){return this.signalHandlersEnabled=!0,this}async build(){return(await this.buildModule()).reactor}async buildModule(){this.logger||(this.logger=new ConsoleLogger(["reactor"]));const e=new DocumentModelRegistry;this.upgradeManifests.length>0&&e.registerUpgradeManifests(...this.upgradeManifests),this.documentModels.length>0&&e.registerModules(...this.documentModels);const M=this.kyselyInstance??new Kysely({dialect:new PGliteDialect(new We)});if(this.migrationStrategy==="auto"){const Gr=await runMigrations(M,REACTOR_SCHEMA);if(!Gr.success&&Gr.error)throw new Error(`Database migration failed: ${Gr.error.message}`)}const tr=M.withSchema(REACTOR_SCHEMA),rr=new KyselyOperationStore(tr),ir=new KyselyKeyframeStore(tr),lr=this.eventBus||new EventBus,dr=this.queueInstance??new InMemoryQueue(lr,e,this.documentModelLoader),hr=new InMemoryJobTracker(lr),fr={maxDocuments:this.writeCacheConfig?.maxDocuments??100,ringBufferSize:this.writeCacheConfig?.ringBufferSize??10,keyframeInterval:this.writeCacheConfig?.keyframeInterval??10},mr=new KyselyWriteCache(ir,rr,e,fr);await mr.startup();const _r=new KyselyOperationIndex(tr),gr=new DocumentMetaCache(rr,{maxDocuments:1e3});await gr.startup();const wr=new CollectionMembershipCache(_r);let yr=this.executorManager;yr||(yr=new SimpleJobExecutorManager(()=>new SimpleJobExecutor(this.logger,e,rr,lr,mr,_r,gr,wr,this.executorConfig,this.signatureVerifier),lr,dr,hr,this.logger)),await yr.start(this.executorConfig.maxConcurrency??1);const br=Array.from(new Set([...this.readModels])),Mr=new ConsistencyTracker,vr=new KyselyDocumentView(tr,rr,_r,mr,Mr);try{await vr.init()}catch(Gr){console.error("Error initializing document view",Gr)}br.push(vr);const Sr=new ConsistencyTracker,xr=new KyselyDocumentIndexer(tr,rr,Sr);try{await xr.init()}catch(Gr){console.error("Error initializing document indexer",Gr)}br.push(xr);const Ar=new ReactorSubscriptionManager(new DefaultSubscriptionErrorHandler),Dr=new SubscriptionNotificationReadModel(Ar,vr),Ir=new ConsistencyTracker,kr=new ProcessorManager(tr,_r,mr,Ir);try{await kr.init()}catch(Gr){console.error("Error initializing processor manager",Gr)}const Or=this.readModelCoordinator?this.readModelCoordinator:new ReadModelCoordinator(lr,br,[Dr,kr]),Fr=new Reactor(this.logger,e,dr,hr,Or,this.features,vr,xr,rr,lr,yr);let Jr;if(this.channelScheme){const Gr=this.channelScheme===ChannelScheme.CONNECT?new GqlRequestChannelFactory(this.logger,this.jwtHandler,dr):new GqlResponseChannelFactory(this.logger);Jr=new SyncBuilder().withChannelFactory(Gr).buildModule(Fr,this.logger,_r,lr,tr),await Jr.syncManager.startup()}else this.syncBuilder&&(Jr=this.syncBuilder.buildModule(Fr,this.logger,_r,lr,tr),await Jr.syncManager.startup());const $n={eventBus:lr,documentModelRegistry:e,queue:dr,jobTracker:hr,executorManager:yr,database:tr,operationStore:rr,keyframeStore:ir,writeCache:mr,operationIndex:_r,documentView:vr,documentViewConsistencyTracker:Mr,documentIndexer:xr,documentIndexerConsistencyTracker:Sr,readModelCoordinator:Or,subscriptionManager:Ar,processorManager:kr,processorManagerConsistencyTracker:Ir,syncModule:Jr,reactor:Fr};return this.signalHandlersEnabled&&this.attachSignalHandlers($n),$n}attachSignalHandlers(e){if(typeof globalThis>"u"||!("process"in globalThis)||typeof globalThis.process.on!="function")return;const M=globalThis.process;let tr=!1;const rr=async ir=>{tr&&(this.logger.warn(`Received ${ir} again, forcing exit`),M.exit(1)),tr=!0,this.logger.info(`Received ${ir}, starting graceful shutdown...`);const lr=e.reactor.kill();try{await lr.completed}catch(dr){this.logger.error("Shutdown failed waiting for reactor:",dr),M.exit(1);return}try{await e.database.destroy()}catch(dr){this.logger.error("Shutdown failed destroying database:",dr),M.exit(1);return}this.logger.info("Shutdown complete"),M.exit(0)};M.on("SIGINT",()=>{rr("SIGINT")}),M.on("SIGTERM",()=>{rr("SIGTERM")})}}class PassthroughSigner{publicKey={};sign(){return Promise.resolve(new Uint8Array(0))}verify(){return Promise.resolve()}signAction(){return Promise.resolve(["","","","",""])}}class ReactorClientBuilder{logger;reactorBuilder;reactor;eventBus;documentIndexer;documentView;signer;signatureVerifier;subscriptionManager;jobAwaiter;withLogger(e){return this.logger=e,this}withReactorBuilder(e){if(this.reactor)throw new Error("Reactor is already set");return this.reactorBuilder=e,this}withReactor(e,M,tr,rr){if(this.reactorBuilder)throw new Error("ReactorBuilder is already set");return this.reactor=e,this.eventBus=M,this.documentIndexer=tr,this.documentView=rr,this}withSigner(e){return"signer"in e?(this.signer=e.signer,this.signatureVerifier=e.verifier):this.signer=e,this}withSubscriptionManager(e){return this.subscriptionManager=e,this}withJobAwaiter(e){return this.jobAwaiter=e,this}async build(){return(await this.buildModule()).client}async buildModule(){this.logger||(this.logger=new ConsoleLogger(["reactor-client"]));let e,M,tr,rr,ir;if(this.reactorBuilder)this.signatureVerifier&&this.reactorBuilder.withSignatureVerifier(this.signatureVerifier),ir=await this.reactorBuilder.buildModule(),e=ir.reactor,M=ir.eventBus,tr=ir.documentIndexer,rr=ir.documentView;else if(this.reactor&&this.eventBus&&this.documentIndexer&&this.documentView)e=this.reactor,M=this.eventBus,tr=this.documentIndexer,rr=this.documentView,ir=void 0;else throw new Error("Either ReactorBuilder or (Reactor + EventBus + DocumentIndexer + DocumentView) is required");const lr=this.signer??new PassthroughSigner,dr=this.subscriptionManager??ir?.subscriptionManager??new ReactorSubscriptionManager(new DefaultSubscriptionErrorHandler),hr=this.jobAwaiter??new JobAwaiter(M,(mr,_r)=>e.getJobStatus(mr,_r));return{client:new ReactorClient(this.logger,e,lr,dr,hr,tr,rr),reactor:e,eventBus:M,documentIndexer:tr,documentView:rr,signer:lr,subscriptionManager:dr,jobAwaiter:hr,reactorModule:ir}}}const DEFAULT_ANALYTICS_PROCESSOR_DB_NAME="analytics-db",SUPPORTED_SIZES=[32,64,128,256,512,1024],LOG2_26=Math.log2(26);function hashNamespace(r,e=10){const M=Math.ceil(e*LOG2_26),tr=SUPPORTED_SIZES.find(ir=>ir&&ir>=M)??1024,rr=fnv1a(r,{size:tr});return toBase26(rr,e)}function toBase26(r,e=10){const M="abcdefghijklmnopqrstuvwxyz";let tr="";for(;r>0n&&tr.length<e;)tr=M[Number(r%26n)]+tr,r/=26n;return tr.padStart(e,"a")}function createRelationalDb(r,e){const M=r;return M.createNamespace=(tr,rr)=>createNamespacedDb(r,tr,rr??e),M.queryNamespace=(tr,rr)=>createNamespacedQueryBuilder(r,tr,rr??e),M}async function createNamespacedDb(r,e,M){const rr=M?.hashNamespace??!0?hashNamespace(e):e;return await r.schema.createSchema(rr).ifNotExists().execute(),r.withSchema(rr)}function createNamespacedQueryBuilder(r,e,M){const rr=M?.hashNamespace??!0?hashNamespace(e):e,ir=r.withSchema(rr);return relationalDbToQueryBuilder(ir)}function relationalDbToQueryBuilder(r){return{selectFrom:r.selectFrom.bind(r),selectNoFrom:r.selectNoFrom.bind(r),with:r.with.bind(r),withRecursive:r.withRecursive.bind(r),withSchema:e=>relationalDbToQueryBuilder(r.withSchema(e))}}async function addDrive(r,e){const{isAllowedToCreateDocuments:M}=getUserPermissions();if(!M)throw new Error("User is not allowed to create drives");const tr=window.ph?.reactorClient;if(!tr)throw new Error("ReactorClient not initialized");const rr=driveCreateDocument({global:{name:r.global.name||"",icon:r.global.icon??null,nodes:[]}});return e&&(rr.header.meta={preferredEditor:e}),await tr.create(rr)}async function addRemoteDrive(r,e,M){if(!window.ph?.reactorClient)throw new Error("ReactorClient not initialized");const rr=window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;if(!rr)throw new Error("Sync not initialized");const ir=await fetch(r);if(!ir.ok)throw new Error(`Failed to resolve drive info from ${r}`);const lr=await ir.json(),dr=M??lr.id,hr=crypto.randomUUID();return await rr.add(hr,driveCollectionId("main",dr),{type:"gql",parameters:{url:lr.graphqlEndpoint}}),dr}async function deleteDrive(r){const{isAllowedToCreateDocuments:e}=getUserPermissions();if(!e)throw new Error("User is not allowed to delete drives");const M=window.ph?.reactorClient;if(!M)throw new Error("ReactorClient not initialized");await M.deleteDocument(r)}async function renameDrive(r,e){const{isAllowedToCreateDocuments:M}=getUserPermissions();if(!M)throw new Error("User is not allowed to rename drives");const tr=window.ph?.reactorClient;if(!tr)throw new Error("ReactorClient not initialized");return await tr.rename(r,e)}async function setDriveAvailableOffline(r,e){const{isAllowedToCreateDocuments:M}=getUserPermissions();if(!M)throw new Error("User is not allowed to change drive availability");const tr=window.ph?.reactorClient;if(!tr)throw new Error("ReactorClient not initialized");return await tr.execute(r,"main",[setAvailableOffline({availableOffline:e})])}async function setDriveSharingType(r,e){const{isAllowedToCreateDocuments:M}=getUserPermissions();if(!M)throw new Error("User is not allowed to change drive sharing type");const tr=window.ph?.reactorClient;if(!tr)throw new Error("ReactorClient not initialized");return await tr.execute(r,"main",[setSharingType({type:e})])}async function removeTrigger(r,e){}async function registerNewPullResponderTrigger(r,e,M){}async function addTrigger(r,e){}var Subscribable=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(r){return this.listeners.add(r),this.onSubscribe(),()=>{this.listeners.delete(r),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},defaultTimeoutProvider={setTimeout:(r,e)=>setTimeout(r,e),clearTimeout:r=>clearTimeout(r),setInterval:(r,e)=>setInterval(r,e),clearInterval:r=>clearInterval(r)},TimeoutManager=class{#e=defaultTimeoutProvider;#t=!1;setTimeoutProvider(r){this.#e=r}setTimeout(r,e){return this.#e.setTimeout(r,e)}clearTimeout(r){this.#e.clearTimeout(r)}setInterval(r,e){return this.#e.setInterval(r,e)}clearInterval(r){this.#e.clearInterval(r)}},timeoutManager=new TimeoutManager;function systemSetTimeoutZero(r){setTimeout(r,0)}var isServer=typeof window>"u"||"Deno"in globalThis;function noop(){}function functionalUpdate(r,e){return typeof r=="function"?r(e):r}function isValidTimeout(r){return typeof r=="number"&&r>=0&&r!==1/0}function timeUntilStale(r,e){return Math.max(r+(e||0)-Date.now(),0)}function resolveStaleTime(r,e){return typeof r=="function"?r(e):r}function resolveEnabled(r,e){return typeof r=="function"?r(e):r}function matchQuery(r,e){const{type:M="all",exact:tr,fetchStatus:rr,predicate:ir,queryKey:lr,stale:dr}=r;if(lr){if(tr){if(e.queryHash!==hashQueryKeyByOptions(lr,e.options))return!1}else if(!partialMatchKey(e.queryKey,lr))return!1}if(M!=="all"){const hr=e.isActive();if(M==="active"&&!hr||M==="inactive"&&hr)return!1}return!(typeof dr=="boolean"&&e.isStale()!==dr||rr&&rr!==e.state.fetchStatus||ir&&!ir(e))}function matchMutation(r,e){const{exact:M,status:tr,predicate:rr,mutationKey:ir}=r;if(ir){if(!e.options.mutationKey)return!1;if(M){if(hashKey(e.options.mutationKey)!==hashKey(ir))return!1}else if(!partialMatchKey(e.options.mutationKey,ir))return!1}return!(tr&&e.state.status!==tr||rr&&!rr(e))}function hashQueryKeyByOptions(r,e){return(e?.queryKeyHashFn||hashKey)(r)}function hashKey(r){return JSON.stringify(r,(e,M)=>isPlainObject(M)?Object.keys(M).sort().reduce((tr,rr)=>(tr[rr]=M[rr],tr),{}):M)}function partialMatchKey(r,e){return r===e?!0:typeof r!=typeof e?!1:r&&e&&typeof r=="object"&&typeof e=="object"?Object.keys(e).every(M=>partialMatchKey(r[M],e[M])):!1}var hasOwn=Object.prototype.hasOwnProperty;function replaceEqualDeep(r,e){if(r===e)return r;const M=isPlainArray(r)&&isPlainArray(e);if(!M&&!(isPlainObject(r)&&isPlainObject(e)))return e;const rr=(M?r:Object.keys(r)).length,ir=M?e:Object.keys(e),lr=ir.length,dr=M?new Array(lr):{};let hr=0;for(let fr=0;fr<lr;fr++){const mr=M?fr:ir[fr],_r=r[mr],gr=e[mr];if(_r===gr){dr[mr]=_r,(M?fr<rr:hasOwn.call(r,mr))&&hr++;continue}if(_r===null||gr===null||typeof _r!="object"||typeof gr!="object"){dr[mr]=gr;continue}const wr=replaceEqualDeep(_r,gr);dr[mr]=wr,wr===_r&&hr++}return rr===lr&&hr===rr?r:dr}function shallowEqualObjects(r,e){if(!e||Object.keys(r).length!==Object.keys(e).length)return!1;for(const M in r)if(r[M]!==e[M])return!1;return!0}function isPlainArray(r){return Array.isArray(r)&&r.length===Object.keys(r).length}function isPlainObject(r){if(!hasObjectPrototype(r))return!1;const e=r.constructor;if(e===void 0)return!0;const M=e.prototype;return!(!hasObjectPrototype(M)||!M.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(r)!==Object.prototype)}function hasObjectPrototype(r){return Object.prototype.toString.call(r)==="[object Object]"}function sleep(r){return new Promise(e=>{timeoutManager.setTimeout(e,r)})}function replaceData(r,e,M){return typeof M.structuralSharing=="function"?M.structuralSharing(r,e):M.structuralSharing!==!1?replaceEqualDeep(r,e):e}function addToEnd(r,e,M=0){const tr=[...r,e];return M&&tr.length>M?tr.slice(1):tr}function addToStart(r,e,M=0){const tr=[e,...r];return M&&tr.length>M?tr.slice(0,-1):tr}var skipToken=Symbol();function ensureQueryFn(r,e){return!r.queryFn&&e?.initialPromise?()=>e.initialPromise:!r.queryFn||r.queryFn===skipToken?()=>Promise.reject(new Error(`Missing queryFn: '${r.queryHash}'`)):r.queryFn}function shouldThrowError(r,e){return typeof r=="function"?r(...e):!!r}var FocusManager=class extends Subscribable{#e;#t;#r;constructor(){super(),this.#r=r=>{if(!isServer&&window.addEventListener){const e=()=>r();return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(r){this.#r=r,this.#t?.(),this.#t=r(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(r){this.#e!==r&&(this.#e=r,this.onFocus())}onFocus(){const r=this.isFocused();this.listeners.forEach(e=>{e(r)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},focusManager=new FocusManager;function pendingThenable(){let r,e;const M=new Promise((rr,ir)=>{r=rr,e=ir});M.status="pending",M.catch(()=>{});function tr(rr){Object.assign(M,rr),delete M.resolve,delete M.reject}return M.resolve=rr=>{tr({status:"fulfilled",value:rr}),r(rr)},M.reject=rr=>{tr({status:"rejected",reason:rr}),e(rr)},M}var defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let r=[],e=0,M=dr=>{dr()},tr=dr=>{dr()},rr=defaultScheduler;const ir=dr=>{e?r.push(dr):rr(()=>{M(dr)})},lr=()=>{const dr=r;r=[],dr.length&&rr(()=>{tr(()=>{dr.forEach(hr=>{M(hr)})})})};return{batch:dr=>{let hr;e++;try{hr=dr()}finally{e--,e||lr()}return hr},batchCalls:dr=>(...hr)=>{ir(()=>{dr(...hr)})},schedule:ir,setNotifyFunction:dr=>{M=dr},setBatchNotifyFunction:dr=>{tr=dr},setScheduler:dr=>{rr=dr}}}var notifyManager=createNotifyManager(),OnlineManager=class extends Subscribable{#e=!0;#t;#r;constructor(){super(),this.#r=r=>{if(!isServer&&window.addEventListener){const e=()=>r(!0),M=()=>r(!1);return window.addEventListener("online",e,!1),window.addEventListener("offline",M,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",M)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(r){this.#r=r,this.#t?.(),this.#t=r(this.setOnline.bind(this))}setOnline(r){this.#e!==r&&(this.#e=r,this.listeners.forEach(M=>{M(r)}))}isOnline(){return this.#e}},onlineManager=new OnlineManager;function defaultRetryDelay(r){return Math.min(1e3*2**r,3e4)}function canFetch(r){return(r??"online")==="online"?onlineManager.isOnline():!0}var CancelledError=class extends Error{constructor(r){super("CancelledError"),this.revert=r?.revert,this.silent=r?.silent}};function createRetryer(r){let e=!1,M=0,tr;const rr=pendingThenable(),ir=()=>rr.status!=="pending",lr=br=>{if(!ir()){const Mr=new CancelledError(br);gr(Mr),r.onCancel?.(Mr)}},dr=()=>{e=!0},hr=()=>{e=!1},fr=()=>focusManager.isFocused()&&(r.networkMode==="always"||onlineManager.isOnline())&&r.canRun(),mr=()=>canFetch(r.networkMode)&&r.canRun(),_r=br=>{ir()||(tr?.(),rr.resolve(br))},gr=br=>{ir()||(tr?.(),rr.reject(br))},wr=()=>new Promise(br=>{tr=Mr=>{(ir()||fr())&&br(Mr)},r.onPause?.()}).then(()=>{tr=void 0,ir()||r.onContinue?.()}),yr=()=>{if(ir())return;let br;const Mr=M===0?r.initialPromise:void 0;try{br=Mr??r.fn()}catch(vr){br=Promise.reject(vr)}Promise.resolve(br).then(_r).catch(vr=>{if(ir())return;const Sr=r.retry??(isServer?0:3),xr=r.retryDelay??defaultRetryDelay,Ar=typeof xr=="function"?xr(M,vr):xr,Dr=Sr===!0||typeof Sr=="number"&&M<Sr||typeof Sr=="function"&&Sr(M,vr);if(e||!Dr){gr(vr);return}M++,r.onFail?.(M,vr),sleep(Ar).then(()=>fr()?void 0:wr()).then(()=>{e?gr(vr):yr()})})};return{promise:rr,status:()=>rr.status,cancel:lr,continue:()=>(tr?.(),rr),cancelRetry:dr,continueRetry:hr,canStart:mr,start:()=>(mr()?yr():wr().then(yr),rr)}}var Removable=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),isValidTimeout(this.gcTime)&&(this.#e=timeoutManager.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(r){this.gcTime=Math.max(this.gcTime||0,r??(isServer?1/0:300*1e3))}clearGcTimeout(){this.#e&&(timeoutManager.clearTimeout(this.#e),this.#e=void 0)}},Query=class extends Removable{#e;#t;#r;#s;#n;#a;#o;constructor(r){super(),this.#o=!1,this.#a=r.defaultOptions,this.setOptions(r.options),this.observers=[],this.#s=r.client,this.#r=this.#s.getQueryCache(),this.queryKey=r.queryKey,this.queryHash=r.queryHash,this.#e=getDefaultState$1(this.options),this.state=r.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#n?.promise}setOptions(r){if(this.options={...this.#a,...r},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const e=getDefaultState$1(this.options);e.data!==void 0&&(this.setState(successState(e.data,e.dataUpdatedAt)),this.#e=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(r,e){const M=replaceData(this.state.data,r,this.options);return this.#i({data:M,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),M}setState(r,e){this.#i({type:"setState",state:r,setStateOptions:e})}cancel(r){const e=this.#n?.promise;return this.#n?.cancel(r),e?e.then(noop).catch(noop):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(r=>resolveEnabled(r.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===skipToken||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(r=>resolveStaleTime(r.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(r=>r.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(r=0){return this.state.data===void 0?!0:r==="static"?!1:this.state.isInvalidated?!0:!timeUntilStale(this.state.dataUpdatedAt,r)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#n?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#n?.continue()}addObserver(r){this.observers.includes(r)||(this.observers.push(r),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:r}))}removeObserver(r){this.observers.includes(r)&&(this.observers=this.observers.filter(e=>e!==r),this.observers.length||(this.#n&&(this.#o?this.#n.cancel({revert:!0}):this.#n.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:r}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(r,e){if(this.state.fetchStatus!=="idle"&&this.#n?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#n)return this.#n.continueRetry(),this.#n.promise}if(r&&this.setOptions(r),!this.options.queryFn){const dr=this.observers.find(hr=>hr.options.queryFn);dr&&this.setOptions(dr.options)}const M=new AbortController,tr=dr=>{Object.defineProperty(dr,"signal",{enumerable:!0,get:()=>(this.#o=!0,M.signal)})},rr=()=>{const dr=ensureQueryFn(this.options,e),fr=(()=>{const mr={client:this.#s,queryKey:this.queryKey,meta:this.meta};return tr(mr),mr})();return this.#o=!1,this.options.persister?this.options.persister(dr,fr,this):dr(fr)},lr=(()=>{const dr={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#s,state:this.state,fetchFn:rr};return tr(dr),dr})();this.options.behavior?.onFetch(lr,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==lr.fetchOptions?.meta)&&this.#i({type:"fetch",meta:lr.fetchOptions?.meta}),this.#n=createRetryer({initialPromise:e?.initialPromise,fn:lr.fetchFn,onCancel:dr=>{dr instanceof CancelledError&&dr.revert&&this.setState({...this.#t,fetchStatus:"idle"}),M.abort()},onFail:(dr,hr)=>{this.#i({type:"failed",failureCount:dr,error:hr})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:lr.options.retry,retryDelay:lr.options.retryDelay,networkMode:lr.options.networkMode,canRun:()=>!0});try{const dr=await this.#n.start();if(dr===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(dr),this.#r.config.onSuccess?.(dr,this),this.#r.config.onSettled?.(dr,this.state.error,this),dr}catch(dr){if(dr instanceof CancelledError){if(dr.silent)return this.#n.promise;if(dr.revert){if(this.state.data===void 0)throw dr;return this.state.data}}throw this.#i({type:"error",error:dr}),this.#r.config.onError?.(dr,this),this.#r.config.onSettled?.(this.state.data,dr,this),dr}finally{this.scheduleGc()}}#i(r){const e=M=>{switch(r.type){case"failed":return{...M,fetchFailureCount:r.failureCount,fetchFailureReason:r.error};case"pause":return{...M,fetchStatus:"paused"};case"continue":return{...M,fetchStatus:"fetching"};case"fetch":return{...M,...fetchState(M.data,this.options),fetchMeta:r.meta??null};case"success":const tr={...M,...successState(r.data,r.dataUpdatedAt),dataUpdateCount:M.dataUpdateCount+1,...!r.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=r.manual?tr:void 0,tr;case"error":const rr=r.error;return{...M,error:rr,errorUpdateCount:M.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:M.fetchFailureCount+1,fetchFailureReason:rr,fetchStatus:"idle",status:"error"};case"invalidate":return{...M,isInvalidated:!0};case"setState":return{...M,...r.state}}};this.state=e(this.state),notifyManager.batch(()=>{this.observers.forEach(M=>{M.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:r})})}};function fetchState(r,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch(e.networkMode)?"fetching":"paused",...r===void 0&&{error:null,status:"pending"}}}function successState(r,e){return{data:r,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function getDefaultState$1(r){const e=typeof r.initialData=="function"?r.initialData():r.initialData,M=e!==void 0,tr=M?typeof r.initialDataUpdatedAt=="function"?r.initialDataUpdatedAt():r.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:M?tr??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:M?"success":"pending",fetchStatus:"idle"}}var QueryObserver=class extends Subscribable{constructor(r,e){super(),this.options=e,this.#e=r,this.#i=null,this.#o=pendingThenable(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#r=void 0;#s=void 0;#n;#a;#o;#i;#l;#c;#d;#p;#u;#h;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),shouldFetchOnMount(this.#t,this.options)?this.#f():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#E(),this.#x(),this.#t.removeObserver(this)}setOptions(r){const e=this.options,M=this.#t;if(this.options=this.#e.defaultQueryOptions(r),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof resolveEnabled(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),e._defaulted&&!shallowEqualObjects(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const tr=this.hasListeners();tr&&shouldFetchOptionally(this.#t,M,this.options,e)&&this.#f(),this.updateResult(),tr&&(this.#t!==M||resolveEnabled(this.options.enabled,this.#t)!==resolveEnabled(e.enabled,this.#t)||resolveStaleTime(this.options.staleTime,this.#t)!==resolveStaleTime(e.staleTime,this.#t))&&this.#y();const rr=this.#_();tr&&(this.#t!==M||resolveEnabled(this.options.enabled,this.#t)!==resolveEnabled(e.enabled,this.#t)||rr!==this.#h)&&this.#w(rr)}getOptimisticResult(r){const e=this.#e.getQueryCache().build(this.#e,r),M=this.createResult(e,r);return shouldAssignObserverCurrentProperties(this,M)&&(this.#s=M,this.#a=this.options,this.#n=this.#t.state),M}getCurrentResult(){return this.#s}trackResult(r,e){return new Proxy(r,{get:(M,tr)=>(this.trackProp(tr),e?.(tr),tr==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(M,tr))})}trackProp(r){this.#m.add(r)}getCurrentQuery(){return this.#t}refetch({...r}={}){return this.fetch({...r})}fetchOptimistic(r){const e=this.#e.defaultQueryOptions(r),M=this.#e.getQueryCache().build(this.#e,e);return M.fetch().then(()=>this.createResult(M,e))}fetch(r){return this.#f({...r,cancelRefetch:r.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#f(r){this.#S();let e=this.#t.fetch(this.options,r);return r?.throwOnError||(e=e.catch(noop)),e}#y(){this.#E();const r=resolveStaleTime(this.options.staleTime,this.#t);if(isServer||this.#s.isStale||!isValidTimeout(r))return;const M=timeUntilStale(this.#s.dataUpdatedAt,r)+1;this.#p=timeoutManager.setTimeout(()=>{this.#s.isStale||this.updateResult()},M)}#_(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#w(r){this.#x(),this.#h=r,!(isServer||resolveEnabled(this.options.enabled,this.#t)===!1||!isValidTimeout(this.#h)||this.#h===0)&&(this.#u=timeoutManager.setInterval(()=>{(this.options.refetchIntervalInBackground||focusManager.isFocused())&&this.#f()},this.#h))}#b(){this.#y(),this.#w(this.#_())}#E(){this.#p&&(timeoutManager.clearTimeout(this.#p),this.#p=void 0)}#x(){this.#u&&(timeoutManager.clearInterval(this.#u),this.#u=void 0)}createResult(r,e){const M=this.#t,tr=this.options,rr=this.#s,ir=this.#n,lr=this.#a,hr=r!==M?r.state:this.#r,{state:fr}=r;let mr={...fr},_r=!1,gr;if(e._optimisticResults){const Or=this.hasListeners(),Fr=!Or&&shouldFetchOnMount(r,e),Jr=Or&&shouldFetchOptionally(r,M,e,tr);(Fr||Jr)&&(mr={...mr,...fetchState(fr.data,r.options)}),e._optimisticResults==="isRestoring"&&(mr.fetchStatus="idle")}let{error:wr,errorUpdatedAt:yr,status:br}=mr;gr=mr.data;let Mr=!1;if(e.placeholderData!==void 0&&gr===void 0&&br==="pending"){let Or;rr?.isPlaceholderData&&e.placeholderData===lr?.placeholderData?(Or=rr.data,Mr=!0):Or=typeof e.placeholderData=="function"?e.placeholderData(this.#d?.state.data,this.#d):e.placeholderData,Or!==void 0&&(br="success",gr=replaceData(rr?.data,Or,e),_r=!0)}if(e.select&&gr!==void 0&&!Mr)if(rr&&gr===ir?.data&&e.select===this.#l)gr=this.#c;else try{this.#l=e.select,gr=e.select(gr),gr=replaceData(rr?.data,gr,e),this.#c=gr,this.#i=null}catch(Or){this.#i=Or}this.#i&&(wr=this.#i,gr=this.#c,yr=Date.now(),br="error");const vr=mr.fetchStatus==="fetching",Sr=br==="pending",xr=br==="error",Ar=Sr&&vr,Dr=gr!==void 0,kr={status:br,fetchStatus:mr.fetchStatus,isPending:Sr,isSuccess:br==="success",isError:xr,isInitialLoading:Ar,isLoading:Ar,data:gr,dataUpdatedAt:mr.dataUpdatedAt,error:wr,errorUpdatedAt:yr,failureCount:mr.fetchFailureCount,failureReason:mr.fetchFailureReason,errorUpdateCount:mr.errorUpdateCount,isFetched:mr.dataUpdateCount>0||mr.errorUpdateCount>0,isFetchedAfterMount:mr.dataUpdateCount>hr.dataUpdateCount||mr.errorUpdateCount>hr.errorUpdateCount,isFetching:vr,isRefetching:vr&&!Sr,isLoadingError:xr&&!Dr,isPaused:mr.fetchStatus==="paused",isPlaceholderData:_r,isRefetchError:xr&&Dr,isStale:isStale(r,e),refetch:this.refetch,promise:this.#o,isEnabled:resolveEnabled(e.enabled,r)!==!1};if(this.options.experimental_prefetchInRender){const Or=$n=>{kr.status==="error"?$n.reject(kr.error):kr.data!==void 0&&$n.resolve(kr.data)},Fr=()=>{const $n=this.#o=kr.promise=pendingThenable();Or($n)},Jr=this.#o;switch(Jr.status){case"pending":r.queryHash===M.queryHash&&Or(Jr);break;case"fulfilled":(kr.status==="error"||kr.data!==Jr.value)&&Fr();break;case"rejected":(kr.status!=="error"||kr.error!==Jr.reason)&&Fr();break}}return kr}updateResult(){const r=this.#s,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#a=this.options,this.#n.data!==void 0&&(this.#d=this.#t),shallowEqualObjects(e,r))return;this.#s=e;const M=()=>{if(!r)return!0;const{notifyOnChangeProps:tr}=this.options,rr=typeof tr=="function"?tr():tr;if(rr==="all"||!rr&&!this.#m.size)return!0;const ir=new Set(rr??this.#m);return this.options.throwOnError&&ir.add("error"),Object.keys(this.#s).some(lr=>{const dr=lr;return this.#s[dr]!==r[dr]&&ir.has(dr)})};this.#g({listeners:M()})}#S(){const r=this.#e.getQueryCache().build(this.#e,this.options);if(r===this.#t)return;const e=this.#t;this.#t=r,this.#r=r.state,this.hasListeners()&&(e?.removeObserver(this),r.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#b()}#g(r){notifyManager.batch(()=>{r.listeners&&this.listeners.forEach(e=>{e(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function shouldLoadOnMount(r,e){return resolveEnabled(e.enabled,r)!==!1&&r.state.data===void 0&&!(r.state.status==="error"&&e.retryOnMount===!1)}function shouldFetchOnMount(r,e){return shouldLoadOnMount(r,e)||r.state.data!==void 0&&shouldFetchOn(r,e,e.refetchOnMount)}function shouldFetchOn(r,e,M){if(resolveEnabled(e.enabled,r)!==!1&&resolveStaleTime(e.staleTime,r)!=="static"){const tr=typeof M=="function"?M(r):M;return tr==="always"||tr!==!1&&isStale(r,e)}return!1}function shouldFetchOptionally(r,e,M,tr){return(r!==e||resolveEnabled(tr.enabled,r)===!1)&&(!M.suspense||r.state.status!=="error")&&isStale(r,M)}function isStale(r,e){return resolveEnabled(e.enabled,r)!==!1&&r.isStaleByTime(resolveStaleTime(e.staleTime,r))}function shouldAssignObserverCurrentProperties(r,e){return!shallowEqualObjects(r.getCurrentResult(),e)}function infiniteQueryBehavior(r){return{onFetch:(e,M)=>{const tr=e.options,rr=e.fetchOptions?.meta?.fetchMore?.direction,ir=e.state.data?.pages||[],lr=e.state.data?.pageParams||[];let dr={pages:[],pageParams:[]},hr=0;const fr=async()=>{let mr=!1;const _r=yr=>{Object.defineProperty(yr,"signal",{enumerable:!0,get:()=>(e.signal.aborted?mr=!0:e.signal.addEventListener("abort",()=>{mr=!0}),e.signal)})},gr=ensureQueryFn(e.options,e.fetchOptions),wr=async(yr,br,Mr)=>{if(mr)return Promise.reject();if(br==null&&yr.pages.length)return Promise.resolve(yr);const Sr=(()=>{const Ir={client:e.client,queryKey:e.queryKey,pageParam:br,direction:Mr?"backward":"forward",meta:e.options.meta};return _r(Ir),Ir})(),xr=await gr(Sr),{maxPages:Ar}=e.options,Dr=Mr?addToStart:addToEnd;return{pages:Dr(yr.pages,xr,Ar),pageParams:Dr(yr.pageParams,br,Ar)}};if(rr&&ir.length){const yr=rr==="backward",br=yr?getPreviousPageParam:getNextPageParam,Mr={pages:ir,pageParams:lr},vr=br(tr,Mr);dr=await wr(Mr,vr,yr)}else{const yr=r??ir.length;do{const br=hr===0?lr[0]??tr.initialPageParam:getNextPageParam(tr,dr);if(hr>0&&br==null)break;dr=await wr(dr,br),hr++}while(hr<yr)}return dr};e.options.persister?e.fetchFn=()=>e.options.persister?.(fr,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},M):e.fetchFn=fr}}}function getNextPageParam(r,{pages:e,pageParams:M}){const tr=e.length-1;return e.length>0?r.getNextPageParam(e[tr],e,M[tr],M):void 0}function getPreviousPageParam(r,{pages:e,pageParams:M}){return e.length>0?r.getPreviousPageParam?.(e[0],e,M[0],M):void 0}var Mutation=class extends Removable{#e;#t;#r;#s;constructor(r){super(),this.#e=r.client,this.mutationId=r.mutationId,this.#r=r.mutationCache,this.#t=[],this.state=r.state||getDefaultState(),this.setOptions(r.options),this.scheduleGc()}setOptions(r){this.options=r,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(r){this.#t.includes(r)||(this.#t.push(r),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",mutation:this,observer:r}))}removeObserver(r){this.#t=this.#t.filter(e=>e!==r),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:r})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(r){const e=()=>{this.#n({type:"continue"})},M={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=createRetryer({fn:()=>this.options.mutationFn?this.options.mutationFn(r,M):Promise.reject(new Error("No mutationFn found")),onFail:(ir,lr)=>{this.#n({type:"failed",failureCount:ir,error:lr})},onPause:()=>{this.#n({type:"pause"})},onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#r.canRun(this)});const tr=this.state.status==="pending",rr=!this.#s.canStart();try{if(tr)e();else{this.#n({type:"pending",variables:r,isPaused:rr}),await this.#r.config.onMutate?.(r,this,M);const lr=await this.options.onMutate?.(r,M);lr!==this.state.context&&this.#n({type:"pending",context:lr,variables:r,isPaused:rr})}const ir=await this.#s.start();return await this.#r.config.onSuccess?.(ir,r,this.state.context,this,M),await this.options.onSuccess?.(ir,r,this.state.context,M),await this.#r.config.onSettled?.(ir,null,this.state.variables,this.state.context,this,M),await this.options.onSettled?.(ir,null,r,this.state.context,M),this.#n({type:"success",data:ir}),ir}catch(ir){try{throw await this.#r.config.onError?.(ir,r,this.state.context,this,M),await this.options.onError?.(ir,r,this.state.context,M),await this.#r.config.onSettled?.(void 0,ir,this.state.variables,this.state.context,this,M),await this.options.onSettled?.(void 0,ir,r,this.state.context,M),ir}finally{this.#n({type:"error",error:ir})}}finally{this.#r.runNext(this)}}#n(r){const e=M=>{switch(r.type){case"failed":return{...M,failureCount:r.failureCount,failureReason:r.error};case"pause":return{...M,isPaused:!0};case"continue":return{...M,isPaused:!1};case"pending":return{...M,context:r.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:r.isPaused,status:"pending",variables:r.variables,submittedAt:Date.now()};case"success":return{...M,data:r.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...M,data:void 0,error:r.error,failureCount:M.failureCount+1,failureReason:r.error,isPaused:!1,status:"error"}}};this.state=e(this.state),notifyManager.batch(()=>{this.#t.forEach(M=>{M.onMutationUpdate(r)}),this.#r.notify({mutation:this,type:"updated",action:r})})}};function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var MutationCache=class extends Subscribable{constructor(r={}){super(),this.config=r,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(r,e,M){const tr=new Mutation({client:r,mutationCache:this,mutationId:++this.#r,options:r.defaultMutationOptions(e),state:M});return this.add(tr),tr}add(r){this.#e.add(r);const e=scopeFor(r);if(typeof e=="string"){const M=this.#t.get(e);M?M.push(r):this.#t.set(e,[r])}this.notify({type:"added",mutation:r})}remove(r){if(this.#e.delete(r)){const e=scopeFor(r);if(typeof e=="string"){const M=this.#t.get(e);if(M)if(M.length>1){const tr=M.indexOf(r);tr!==-1&&M.splice(tr,1)}else M[0]===r&&this.#t.delete(e)}}this.notify({type:"removed",mutation:r})}canRun(r){const e=scopeFor(r);if(typeof e=="string"){const tr=this.#t.get(e)?.find(rr=>rr.state.status==="pending");return!tr||tr===r}else return!0}runNext(r){const e=scopeFor(r);return typeof e=="string"?this.#t.get(e)?.find(tr=>tr!==r&&tr.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){notifyManager.batch(()=>{this.#e.forEach(r=>{this.notify({type:"removed",mutation:r})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(r){const e={exact:!0,...r};return this.getAll().find(M=>matchMutation(e,M))}findAll(r={}){return this.getAll().filter(e=>matchMutation(r,e))}notify(r){notifyManager.batch(()=>{this.listeners.forEach(e=>{e(r)})})}resumePausedMutations(){const r=this.getAll().filter(e=>e.state.isPaused);return notifyManager.batch(()=>Promise.all(r.map(e=>e.continue().catch(noop))))}};function scopeFor(r){return r.options.scope?.id}var QueryCache=class extends Subscribable{constructor(r={}){super(),this.config=r,this.#e=new Map}#e;build(r,e,M){const tr=e.queryKey,rr=e.queryHash??hashQueryKeyByOptions(tr,e);let ir=this.get(rr);return ir||(ir=new Query({client:r,queryKey:tr,queryHash:rr,options:r.defaultQueryOptions(e),state:M,defaultOptions:r.getQueryDefaults(tr)}),this.add(ir)),ir}add(r){this.#e.has(r.queryHash)||(this.#e.set(r.queryHash,r),this.notify({type:"added",query:r}))}remove(r){const e=this.#e.get(r.queryHash);e&&(r.destroy(),e===r&&this.#e.delete(r.queryHash),this.notify({type:"removed",query:r}))}clear(){notifyManager.batch(()=>{this.getAll().forEach(r=>{this.remove(r)})})}get(r){return this.#e.get(r)}getAll(){return[...this.#e.values()]}find(r){const e={exact:!0,...r};return this.getAll().find(M=>matchQuery(e,M))}findAll(r={}){const e=this.getAll();return Object.keys(r).length>0?e.filter(M=>matchQuery(r,M)):e}notify(r){notifyManager.batch(()=>{this.listeners.forEach(e=>{e(r)})})}onFocus(){notifyManager.batch(()=>{this.getAll().forEach(r=>{r.onFocus()})})}onOnline(){notifyManager.batch(()=>{this.getAll().forEach(r=>{r.onOnline()})})}},QueryClient=class{#e;#t;#r;#s;#n;#a;#o;#i;constructor(r={}){this.#e=r.queryCache||new QueryCache,this.#t=r.mutationCache||new MutationCache,this.#r=r.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=focusManager.subscribe(async r=>{r&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=onlineManager.subscribe(async r=>{r&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(r){return this.#e.findAll({...r,fetchStatus:"fetching"}).length}isMutating(r){return this.#t.findAll({...r,status:"pending"}).length}getQueryData(r){const e=this.defaultQueryOptions({queryKey:r});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(r){const e=this.defaultQueryOptions(r),M=this.#e.build(this,e),tr=M.state.data;return tr===void 0?this.fetchQuery(r):(r.revalidateIfStale&&M.isStaleByTime(resolveStaleTime(e.staleTime,M))&&this.prefetchQuery(e),Promise.resolve(tr))}getQueriesData(r){return this.#e.findAll(r).map(({queryKey:e,state:M})=>{const tr=M.data;return[e,tr]})}setQueryData(r,e,M){const tr=this.defaultQueryOptions({queryKey:r}),ir=this.#e.get(tr.queryHash)?.state.data,lr=functionalUpdate(e,ir);if(lr!==void 0)return this.#e.build(this,tr).setData(lr,{...M,manual:!0})}setQueriesData(r,e,M){return notifyManager.batch(()=>this.#e.findAll(r).map(({queryKey:tr})=>[tr,this.setQueryData(tr,e,M)]))}getQueryState(r){const e=this.defaultQueryOptions({queryKey:r});return this.#e.get(e.queryHash)?.state}removeQueries(r){const e=this.#e;notifyManager.batch(()=>{e.findAll(r).forEach(M=>{e.remove(M)})})}resetQueries(r,e){const M=this.#e;return notifyManager.batch(()=>(M.findAll(r).forEach(tr=>{tr.reset()}),this.refetchQueries({type:"active",...r},e)))}cancelQueries(r,e={}){const M={revert:!0,...e},tr=notifyManager.batch(()=>this.#e.findAll(r).map(rr=>rr.cancel(M)));return Promise.all(tr).then(noop).catch(noop)}invalidateQueries(r,e={}){return notifyManager.batch(()=>(this.#e.findAll(r).forEach(M=>{M.invalidate()}),r?.refetchType==="none"?Promise.resolve():this.refetchQueries({...r,type:r?.refetchType??r?.type??"active"},e)))}refetchQueries(r,e={}){const M={...e,cancelRefetch:e.cancelRefetch??!0},tr=notifyManager.batch(()=>this.#e.findAll(r).filter(rr=>!rr.isDisabled()&&!rr.isStatic()).map(rr=>{let ir=rr.fetch(void 0,M);return M.throwOnError||(ir=ir.catch(noop)),rr.state.fetchStatus==="paused"?Promise.resolve():ir}));return Promise.all(tr).then(noop)}fetchQuery(r){const e=this.defaultQueryOptions(r);e.retry===void 0&&(e.retry=!1);const M=this.#e.build(this,e);return M.isStaleByTime(resolveStaleTime(e.staleTime,M))?M.fetch(e):Promise.resolve(M.state.data)}prefetchQuery(r){return this.fetchQuery(r).then(noop).catch(noop)}fetchInfiniteQuery(r){return r.behavior=infiniteQueryBehavior(r.pages),this.fetchQuery(r)}prefetchInfiniteQuery(r){return this.fetchInfiniteQuery(r).then(noop).catch(noop)}ensureInfiniteQueryData(r){return r.behavior=infiniteQueryBehavior(r.pages),this.ensureQueryData(r)}resumePausedMutations(){return onlineManager.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(r){this.#r=r}setQueryDefaults(r,e){this.#s.set(hashKey(r),{queryKey:r,defaultOptions:e})}getQueryDefaults(r){const e=[...this.#s.values()],M={};return e.forEach(tr=>{partialMatchKey(r,tr.queryKey)&&Object.assign(M,tr.defaultOptions)}),M}setMutationDefaults(r,e){this.#n.set(hashKey(r),{mutationKey:r,defaultOptions:e})}getMutationDefaults(r){const e=[...this.#n.values()],M={};return e.forEach(tr=>{partialMatchKey(r,tr.mutationKey)&&Object.assign(M,tr.defaultOptions)}),M}defaultQueryOptions(r){if(r._defaulted)return r;const e={...this.#r.queries,...this.getQueryDefaults(r.queryKey),...r,_defaulted:!0};return e.queryHash||(e.queryHash=hashQueryKeyByOptions(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===skipToken&&(e.enabled=!1),e}defaultMutationOptions(r){return r?._defaulted?r:{...this.#r.mutations,...r?.mutationKey&&this.getMutationDefaults(r.mutationKey),...r,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},QueryClientContext=reactExports.createContext(void 0),useQueryClient=r=>{const e=reactExports.useContext(QueryClientContext);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},QueryClientProvider=({client:r,children:e})=>(reactExports.useEffect(()=>(r.mount(),()=>{r.unmount()}),[r]),jsxRuntimeExports.jsx(QueryClientContext.Provider,{value:r,children:e})),IsRestoringContext=reactExports.createContext(!1),useIsRestoring=()=>reactExports.useContext(IsRestoringContext);IsRestoringContext.Provider;function createValue(){let r=!1;return{clearReset:()=>{r=!1},reset:()=>{r=!0},isReset:()=>r}}var QueryErrorResetBoundaryContext=reactExports.createContext(createValue()),useQueryErrorResetBoundary=()=>reactExports.useContext(QueryErrorResetBoundaryContext),ensurePreventErrorBoundaryRetry=(r,e)=>{(r.suspense||r.throwOnError||r.experimental_prefetchInRender)&&(e.isReset()||(r.retryOnMount=!1))},useClearResetErrorBoundary=r=>{reactExports.useEffect(()=>{r.clearReset()},[r])},getHasError=({result:r,errorResetBoundary:e,throwOnError:M,query:tr,suspense:rr})=>r.isError&&!e.isReset()&&!r.isFetching&&tr&&(rr&&r.data===void 0||shouldThrowError(M,[r.error,tr])),ensureSuspenseTimers=r=>{if(r.suspense){const M=rr=>rr==="static"?rr:Math.max(rr??1e3,1e3),tr=r.staleTime;r.staleTime=typeof tr=="function"?(...rr)=>M(tr(...rr)):M(tr),typeof r.gcTime=="number"&&(r.gcTime=Math.max(r.gcTime,1e3))}},willFetch=(r,e)=>r.isLoading&&r.isFetching&&!e,shouldSuspend=(r,e)=>r?.suspense&&e.isPending,fetchOptimistic=(r,e,M)=>e.fetchOptimistic(r).catch(()=>{M.clearReset()});function useBaseQuery(r,e,M){const tr=useIsRestoring(),rr=useQueryErrorResetBoundary(),ir=useQueryClient(),lr=ir.defaultQueryOptions(r);ir.getDefaultOptions().queries?._experimental_beforeQuery?.(lr),lr._optimisticResults=tr?"isRestoring":"optimistic",ensureSuspenseTimers(lr),ensurePreventErrorBoundaryRetry(lr,rr),useClearResetErrorBoundary(rr);const dr=!ir.getQueryCache().get(lr.queryHash),[hr]=reactExports.useState(()=>new e(ir,lr)),fr=hr.getOptimisticResult(lr),mr=!tr&&r.subscribed!==!1;if(reactExports.useSyncExternalStore(reactExports.useCallback(_r=>{const gr=mr?hr.subscribe(notifyManager.batchCalls(_r)):noop;return hr.updateResult(),gr},[hr,mr]),()=>hr.getCurrentResult(),()=>hr.getCurrentResult()),reactExports.useEffect(()=>{hr.setOptions(lr)},[lr,hr]),shouldSuspend(lr,fr))throw fetchOptimistic(lr,hr,rr);if(getHasError({result:fr,errorResetBoundary:rr,throwOnError:lr.throwOnError,query:ir.getQueryCache().get(lr.queryHash),suspense:lr.suspense}))throw fr.error;return ir.getDefaultOptions().queries?._experimental_afterQuery?.(lr,fr),lr.experimental_prefetchInRender&&!isServer&&willFetch(fr,tr)&&(dr?fetchOptimistic(lr,hr,rr):ir.getQueryCache().get(lr.queryHash)?.promise)?.catch(noop).finally(()=>{hr.updateResult()}),lr.notifyOnChangeProps?fr:hr.trackResult(fr)}function useQuery(r,e){return useBaseQuery(r,QueryObserver)}function getGlobal(r){if(!(typeof window>"u"))return window.powerhouse?.[r]}function setGlobal(r,e){typeof window>"u"||(window.powerhouse=window.powerhouse||{},window.powerhouse[r]=e)}const logger=childLogger(["reactor-browser","analytics","provider"]);new QueryClient;async function createAnalyticsStore(r){const{BrowserAnalyticsStore:e}=await __vitePreload(async()=>{const{BrowserAnalyticsStore:ir}=await import("./index-nPVGMhnl.js").then(lr=>lr.i);return{BrowserAnalyticsStore:ir}},__vite__mapDeps([17,3,9,5,6])),M=new e(r);await M.init();const{AnalyticsQueryEngine:tr}=await __vitePreload(async()=>{const{AnalyticsQueryEngine:ir}=await Promise.resolve().then(()=>index);return{AnalyticsQueryEngine:ir}},void 0),rr=new tr(M);return{store:M,engine:rr,options:r}}async function getAnalyticsStore(r){const e=getGlobal("analytics");if(!r||!r.databaseName){if(e)return(await e).store;throw new Error("Analytics store options are required if no global analytics store is available")}return e&&r.databaseName===(await e).options.databaseName?(await e).store:null}async function createOrGetAnalyticsStore(r){const e=await getAnalyticsStore(r);if(e)return e;if(!r)throw new Error("Analytics store options are required if no global analytics store is available");const M=createAnalyticsStore(r);return setGlobal("analytics",M),M.then(({store:tr})=>{logger.verbose("Analytics store created",tr)}).catch(tr=>{logger.error("Analytics store creation failed",tr)}),(await M).store}class PassthroughAnalyticsProfiler{get prefix(){return""}push(e){}pop(){}popAndReturn(e){return e}async record(e,M){return await M()}recordSync(e,M){return M()}}var AnalyticsSerializerTypes;(function(r){r[r.AnalyticsPath=0]="AnalyticsPath",r[r.AnalyticsPathSegment=1]="AnalyticsPathSegment",r[r.AnalyticsPeriod=2]="AnalyticsPeriod"})(AnalyticsSerializerTypes||(AnalyticsSerializerTypes={}));var AnalyticsPeriodType;(function(r){r[r.Year=0]="Year",r[r.Quarter=1]="Quarter",r[r.Month=2]="Month"})(AnalyticsPeriodType||(AnalyticsPeriodType={}));class AnalyticsPath{get segments(){return this._segments}_segments;static fromString(e){const M=parseSeparatedList(e,"/").map(tr=>AnalyticsPathSegment.fromString(tr));return new AnalyticsPath(M)}static fromStringArray(e){return new AnalyticsPath(e.map(M=>AnalyticsPathSegment.fromString(M)))}static fromArray(e){return new AnalyticsPath(e)}static fromJSON(e){const M=e._v.split("/").map(tr=>AnalyticsPathSegment.fromString(tr));return new AnalyticsPath(M)}constructor(e){this._segments=e}toJSON(){return{_t:AnalyticsSerializerTypes.AnalyticsPath,_v:this.toString()}}toString(e=""){return this._segments.map(M=>M.toString()).join("/")+e}firstSegment(){return this._segments.length>0?this._segments[0]:new AnalyticsPathSegment}reduce(){const e=this._segments.slice(1);return e.length<1&&e.push(new AnalyticsPathSegment),new AnalyticsPath(e)}applyLod(e){const M=[...this._segments];for(;M.length<e;)M.push(new AnalyticsPathSegment);return new AnalyticsPath(M.slice(0,e))}}class AnalyticsPathSegment{get filters(){return this._filters}get groups(){return this._groups}_filters=null;_groups=null;static fromString(e){const M=parseSeparatedList(e,":");let tr;M[0]==="*"?tr=null:tr=parseSeparatedList(M[0],",").map(ir=>AnalyticsPathSegment.unescape(ir));let rr;return M[1]===void 0||M[1].length<1?rr=[]:M[1]==="*"?rr=null:rr=parseSeparatedList(M[1],",").map(ir=>AnalyticsPathSegment.unescape(ir)),new AnalyticsPathSegment(tr,rr)}static escape(e){return e.replace(/(\\|:|\/|,)/gi,"\\$1")}static unescape(e){return e.replace(/\\(.)/gi,"$1")}constructor(e=null,M=[]){this._filters=e,this._groups=M}toJSON(){return{_t:AnalyticsSerializerTypes.AnalyticsPathSegment,_v:this.toString()}}toString(){let e="";return this._filters===null?e+="*":e+=this._filters.map(M=>AnalyticsPathSegment.escape(M)).join(","),this._groups===null?e+=":*":this._groups.length>0&&(e+=":"+this._groups.map(M=>AnalyticsPathSegment.escape(M)).join(",")),e}}const unescapedSeparatorPattern={":":new RegExp("(?<!\\\\):"),",":new RegExp("(?<!\\\\),"),"/":new RegExp("(?<!\\\\)\\/")};function parseSeparatedList(r,e){let M="@@";for(;r.indexOf(M)>-1;)M+="@";return r.replaceAll("\\\\",M).split(unescapedSeparatorPattern[e]).map(tr=>tr.replaceAll(M,"\\\\"))}var AnalyticsMetric;(function(r){r[r.Budget=0]="Budget",r[r.Forecast=1]="Forecast",r[r.Actuals=2]="Actuals",r[r.PaymentsOnChain=3]="PaymentsOnChain",r[r.PaymentsOffChainIncluded=4]="PaymentsOffChainIncluded",r[r.FTEs=5]="FTEs"})(AnalyticsMetric||(AnalyticsMetric={}));var CompoundOperator;(function(r){r[r.VectorAdd=0]="VectorAdd",r[r.VectorSubtract=1]="VectorSubtract",r[r.ScalarMultiply=2]="ScalarMultiply",r[r.ScalarDivide=3]="ScalarDivide"})(CompoundOperator||(CompoundOperator={}));var AnalyticsGranularity;(function(r){r[r.Total=0]="Total",r[r.Annual=1]="Annual",r[r.SemiAnnual=2]="SemiAnnual",r[r.Quarterly=3]="Quarterly",r[r.Monthly=4]="Monthly",r[r.Weekly=5]="Weekly",r[r.Daily=6]="Daily",r[r.Hourly=7]="Hourly"})(AnalyticsGranularity||(AnalyticsGranularity={}));class LuxonError extends Error{}class InvalidDateTimeError extends LuxonError{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class InvalidIntervalError extends LuxonError{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class InvalidDurationError extends LuxonError{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class ConflictingSpecificationError extends LuxonError{}class InvalidUnitError extends LuxonError{constructor(e){super(`Invalid unit ${e}`)}}class InvalidArgumentError extends LuxonError{}class ZoneIsAbstractError extends LuxonError{constructor(){super("Zone is an abstract class")}}const n="numeric",s="short",l="long",DATE_SHORT={year:n,month:n,day:n},DATE_MED={year:n,month:s,day:n},DATE_MED_WITH_WEEKDAY={year:n,month:s,day:n,weekday:s},DATE_FULL={year:n,month:l,day:n},DATE_HUGE={year:n,month:l,day:n,weekday:l},TIME_SIMPLE={hour:n,minute:n},TIME_WITH_SECONDS={hour:n,minute:n,second:n},TIME_WITH_SHORT_OFFSET={hour:n,minute:n,second:n,timeZoneName:s},TIME_WITH_LONG_OFFSET={hour:n,minute:n,second:n,timeZoneName:l},TIME_24_SIMPLE={hour:n,minute:n,hourCycle:"h23"},TIME_24_WITH_SECONDS={hour:n,minute:n,second:n,hourCycle:"h23"},TIME_24_WITH_SHORT_OFFSET={hour:n,minute:n,second:n,hourCycle:"h23",timeZoneName:s},TIME_24_WITH_LONG_OFFSET={hour:n,minute:n,second:n,hourCycle:"h23",timeZoneName:l},DATETIME_SHORT={year:n,month:n,day:n,hour:n,minute:n},DATETIME_SHORT_WITH_SECONDS={year:n,month:n,day:n,hour:n,minute:n,second:n},DATETIME_MED={year:n,month:s,day:n,hour:n,minute:n},DATETIME_MED_WITH_SECONDS={year:n,month:s,day:n,hour:n,minute:n,second:n},DATETIME_MED_WITH_WEEKDAY={year:n,month:s,day:n,weekday:s,hour:n,minute:n},DATETIME_FULL={year:n,month:l,day:n,hour:n,minute:n,timeZoneName:s},DATETIME_FULL_WITH_SECONDS={year:n,month:l,day:n,hour:n,minute:n,second:n,timeZoneName:s},DATETIME_HUGE={year:n,month:l,day:n,weekday:l,hour:n,minute:n,timeZoneName:l},DATETIME_HUGE_WITH_SECONDS={year:n,month:l,day:n,weekday:l,hour:n,minute:n,second:n,timeZoneName:l};class Zone{get type(){throw new ZoneIsAbstractError}get name(){throw new ZoneIsAbstractError}get ianaName(){return this.name}get isUniversal(){throw new ZoneIsAbstractError}offsetName(e,M){throw new ZoneIsAbstractError}formatOffset(e,M){throw new ZoneIsAbstractError}offset(e){throw new ZoneIsAbstractError}equals(e){throw new ZoneIsAbstractError}get isValid(){throw new ZoneIsAbstractError}}let singleton$1=null;class SystemZone extends Zone{static get instance(){return singleton$1===null&&(singleton$1=new SystemZone),singleton$1}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:M,locale:tr}){return parseZoneInfo(e,M,tr)}formatOffset(e,M){return formatOffset(this.offset(e),M)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const dtfCache=new Map;function makeDTF(r){let e=dtfCache.get(r);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),dtfCache.set(r,e)),e}const typeToPos={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function hackyOffset(r,e){const M=r.format(e).replace(/\u200E/g,""),tr=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(M),[,rr,ir,lr,dr,hr,fr,mr]=tr;return[lr,rr,ir,dr,hr,fr,mr]}function partsOffset(r,e){const M=r.formatToParts(e),tr=[];for(let rr=0;rr<M.length;rr++){const{type:ir,value:lr}=M[rr],dr=typeToPos[ir];ir==="era"?tr[dr]=lr:isUndefined(dr)||(tr[dr]=parseInt(lr,10))}return tr}const ianaZoneCache=new Map;class IANAZone extends Zone{static create(e){let M=ianaZoneCache.get(e);return M===void 0&&ianaZoneCache.set(e,M=new IANAZone(e)),M}static resetCache(){ianaZoneCache.clear(),dtfCache.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=IANAZone.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:M,locale:tr}){return parseZoneInfo(e,M,tr,this.name)}formatOffset(e,M){return formatOffset(this.offset(e),M)}offset(e){if(!this.valid)return NaN;const M=new Date(e);if(isNaN(M))return NaN;const tr=makeDTF(this.name);let[rr,ir,lr,dr,hr,fr,mr]=tr.formatToParts?partsOffset(tr,M):hackyOffset(tr,M);dr==="BC"&&(rr=-Math.abs(rr)+1);const gr=objToLocalTS({year:rr,month:ir,day:lr,hour:hr===24?0:hr,minute:fr,second:mr,millisecond:0});let wr=+M;const yr=wr%1e3;return wr-=yr>=0?yr:1e3+yr,(gr-wr)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let intlLFCache={};function getCachedLF(r,e={}){const M=JSON.stringify([r,e]);let tr=intlLFCache[M];return tr||(tr=new Intl.ListFormat(r,e),intlLFCache[M]=tr),tr}const intlDTCache=new Map;function getCachedDTF(r,e={}){const M=JSON.stringify([r,e]);let tr=intlDTCache.get(M);return tr===void 0&&(tr=new Intl.DateTimeFormat(r,e),intlDTCache.set(M,tr)),tr}const intlNumCache=new Map;function getCachedINF(r,e={}){const M=JSON.stringify([r,e]);let tr=intlNumCache.get(M);return tr===void 0&&(tr=new Intl.NumberFormat(r,e),intlNumCache.set(M,tr)),tr}const intlRelCache=new Map;function getCachedRTF(r,e={}){const{base:M,...tr}=e,rr=JSON.stringify([r,tr]);let ir=intlRelCache.get(rr);return ir===void 0&&(ir=new Intl.RelativeTimeFormat(r,e),intlRelCache.set(rr,ir)),ir}let sysLocaleCache=null;function systemLocale(){return sysLocaleCache||(sysLocaleCache=new Intl.DateTimeFormat().resolvedOptions().locale,sysLocaleCache)}const intlResolvedOptionsCache=new Map;function getCachedIntResolvedOptions(r){let e=intlResolvedOptionsCache.get(r);return e===void 0&&(e=new Intl.DateTimeFormat(r).resolvedOptions(),intlResolvedOptionsCache.set(r,e)),e}const weekInfoCache=new Map;function getCachedWeekInfo(r){let e=weekInfoCache.get(r);if(!e){const M=new Intl.Locale(r);e="getWeekInfo"in M?M.getWeekInfo():M.weekInfo,"minimalDays"in e||(e={...fallbackWeekSettings,...e}),weekInfoCache.set(r,e)}return e}function parseLocaleString(r){const e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));const M=r.indexOf("-u-");if(M===-1)return[r];{let tr,rr;try{tr=getCachedDTF(r).resolvedOptions(),rr=r}catch{const hr=r.substring(0,M);tr=getCachedDTF(hr).resolvedOptions(),rr=hr}const{numberingSystem:ir,calendar:lr}=tr;return[rr,ir,lr]}}function intlConfigString(r,e,M){return(M||e)&&(r.includes("-u-")||(r+="-u"),M&&(r+=`-ca-${M}`),e&&(r+=`-nu-${e}`)),r}function mapMonths(r){const e=[];for(let M=1;M<=12;M++){const tr=DateTime.utc(2009,M,1);e.push(r(tr))}return e}function mapWeekdays(r){const e=[];for(let M=1;M<=7;M++){const tr=DateTime.utc(2016,11,13+M);e.push(r(tr))}return e}function listStuff(r,e,M,tr){const rr=r.listingMode();return rr==="error"?null:rr==="en"?M(e):tr(e)}function supportsFastNumbers(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||getCachedIntResolvedOptions(r.locale).numberingSystem==="latn"}class PolyNumberFormatter{constructor(e,M,tr){this.padTo=tr.padTo||0,this.floor=tr.floor||!1;const{padTo:rr,floor:ir,...lr}=tr;if(!M||Object.keys(lr).length>0){const dr={useGrouping:!1,...tr};tr.padTo>0&&(dr.minimumIntegerDigits=tr.padTo),this.inf=getCachedINF(e,dr)}}format(e){if(this.inf){const M=this.floor?Math.floor(e):e;return this.inf.format(M)}else{const M=this.floor?Math.floor(e):roundTo(e,3);return padStart(M,this.padTo)}}}class PolyDateFormatter{constructor(e,M,tr){this.opts=tr,this.originalZone=void 0;let rr;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const lr=-1*(e.offset/60),dr=lr>=0?`Etc/GMT+${lr}`:`Etc/GMT${lr}`;e.offset!==0&&IANAZone.create(dr).valid?(rr=dr,this.dt=e):(rr="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,rr=e.zone.name):(rr="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const ir={...this.opts};ir.timeZone=ir.timeZone||rr,this.dtf=getCachedDTF(M,ir)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(M=>{if(M.type==="timeZoneName"){const tr=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...M,value:tr}}else return M}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class PolyRelFormatter{constructor(e,M,tr){this.opts={style:"long",...tr},!M&&hasRelative()&&(this.rtf=getCachedRTF(e,tr))}format(e,M){return this.rtf?this.rtf.format(e,M):formatRelativeTime(M,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,M){return this.rtf?this.rtf.formatToParts(e,M):[]}}const fallbackWeekSettings={firstDay:1,minimalDays:4,weekend:[6,7]};class Locale{static fromOpts(e){return Locale.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,M,tr,rr,ir=!1){const lr=e||Settings.defaultLocale,dr=lr||(ir?"en-US":systemLocale()),hr=M||Settings.defaultNumberingSystem,fr=tr||Settings.defaultOutputCalendar,mr=validateWeekSettings(rr)||Settings.defaultWeekSettings;return new Locale(dr,hr,fr,mr,lr)}static resetCache(){sysLocaleCache=null,intlDTCache.clear(),intlNumCache.clear(),intlRelCache.clear(),intlResolvedOptionsCache.clear(),weekInfoCache.clear()}static fromObject({locale:e,numberingSystem:M,outputCalendar:tr,weekSettings:rr}={}){return Locale.create(e,M,tr,rr)}constructor(e,M,tr,rr,ir){const[lr,dr,hr]=parseLocaleString(e);this.locale=lr,this.numberingSystem=M||dr||null,this.outputCalendar=tr||hr||null,this.weekSettings=rr,this.intl=intlConfigString(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=ir,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=supportsFastNumbers(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),M=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&M?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:Locale.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,validateWeekSettings(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,M=!1){return listStuff(this,e,months,()=>{const tr=this.intl==="ja"||this.intl.startsWith("ja-");M&=!tr;const rr=M?{month:e,day:"numeric"}:{month:e},ir=M?"format":"standalone";if(!this.monthsCache[ir][e]){const lr=tr?dr=>this.dtFormatter(dr,rr).format():dr=>this.extract(dr,rr,"month");this.monthsCache[ir][e]=mapMonths(lr)}return this.monthsCache[ir][e]})}weekdays(e,M=!1){return listStuff(this,e,weekdays,()=>{const tr=M?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},rr=M?"format":"standalone";return this.weekdaysCache[rr][e]||(this.weekdaysCache[rr][e]=mapWeekdays(ir=>this.extract(ir,tr,"weekday"))),this.weekdaysCache[rr][e]})}meridiems(){return listStuff(this,void 0,()=>meridiems,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[DateTime.utc(2016,11,13,9),DateTime.utc(2016,11,13,19)].map(M=>this.extract(M,e,"dayperiod"))}return this.meridiemCache})}eras(e){return listStuff(this,e,eras,()=>{const M={era:e};return this.eraCache[e]||(this.eraCache[e]=[DateTime.utc(-40,1,1),DateTime.utc(2017,1,1)].map(tr=>this.extract(tr,M,"era"))),this.eraCache[e]})}extract(e,M,tr){const rr=this.dtFormatter(e,M),ir=rr.formatToParts(),lr=ir.find(dr=>dr.type.toLowerCase()===tr);return lr?lr.value:null}numberFormatter(e={}){return new PolyNumberFormatter(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,M={}){return new PolyDateFormatter(e,this.intl,M)}relFormatter(e={}){return new PolyRelFormatter(this.intl,this.isEnglish(),e)}listFormatter(e={}){return getCachedLF(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||getCachedIntResolvedOptions(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:hasLocaleWeekInfo()?getCachedWeekInfo(this.locale):fallbackWeekSettings}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let singleton=null;class FixedOffsetZone extends Zone{static get utcInstance(){return singleton===null&&(singleton=new FixedOffsetZone(0)),singleton}static instance(e){return e===0?FixedOffsetZone.utcInstance:new FixedOffsetZone(e)}static parseSpecifier(e){if(e){const M=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(M)return new FixedOffsetZone(signedOffset(M[1],M[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${formatOffset(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${formatOffset(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,M){return formatOffset(this.fixed,M)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class InvalidZone extends Zone{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function normalizeZone(r,e){if(isUndefined(r)||r===null)return e;if(r instanceof Zone)return r;if(isString(r)){const M=r.toLowerCase();return M==="default"?e:M==="local"||M==="system"?SystemZone.instance:M==="utc"||M==="gmt"?FixedOffsetZone.utcInstance:FixedOffsetZone.parseSpecifier(M)||IANAZone.create(r)}else return isNumber(r)?FixedOffsetZone.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new InvalidZone(r)}const numberingSystems={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},numberingSystemsUTF16={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},hanidecChars=numberingSystems.hanidec.replace(/[\[|\]]/g,"").split("");function parseDigits(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let M=0;M<r.length;M++){const tr=r.charCodeAt(M);if(r[M].search(numberingSystems.hanidec)!==-1)e+=hanidecChars.indexOf(r[M]);else for(const rr in numberingSystemsUTF16){const[ir,lr]=numberingSystemsUTF16[rr];tr>=ir&&tr<=lr&&(e+=tr-ir)}}return parseInt(e,10)}else return e}const digitRegexCache=new Map;function resetDigitRegexCache(){digitRegexCache.clear()}function digitRegex({numberingSystem:r},e=""){const M=r||"latn";let tr=digitRegexCache.get(M);tr===void 0&&(tr=new Map,digitRegexCache.set(M,tr));let rr=tr.get(e);return rr===void 0&&(rr=new RegExp(`${numberingSystems[M]}${e}`),tr.set(e,rr)),rr}let now=()=>Date.now(),defaultZone="system",defaultLocale$1=null,defaultNumberingSystem=null,defaultOutputCalendar=null,twoDigitCutoffYear=60,throwOnInvalid,defaultWeekSettings=null;class Settings{static get now(){return now}static set now(e){now=e}static set defaultZone(e){defaultZone=e}static get defaultZone(){return normalizeZone(defaultZone,SystemZone.instance)}static get defaultLocale(){return defaultLocale$1}static set defaultLocale(e){defaultLocale$1=e}static get defaultNumberingSystem(){return defaultNumberingSystem}static set defaultNumberingSystem(e){defaultNumberingSystem=e}static get defaultOutputCalendar(){return defaultOutputCalendar}static set defaultOutputCalendar(e){defaultOutputCalendar=e}static get defaultWeekSettings(){return defaultWeekSettings}static set defaultWeekSettings(e){defaultWeekSettings=validateWeekSettings(e)}static get twoDigitCutoffYear(){return twoDigitCutoffYear}static set twoDigitCutoffYear(e){twoDigitCutoffYear=e%100}static get throwOnInvalid(){return throwOnInvalid}static set throwOnInvalid(e){throwOnInvalid=e}static resetCaches(){Locale.resetCache(),IANAZone.resetCache(),DateTime.resetCache(),resetDigitRegexCache()}}class Invalid{constructor(e,M){this.reason=e,this.explanation=M}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const nonLeapLadder=[0,31,59,90,120,151,181,212,243,273,304,334],leapLadder=[0,31,60,91,121,152,182,213,244,274,305,335];function unitOutOfRange(r,e){return new Invalid("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function dayOfWeek(r,e,M){const tr=new Date(Date.UTC(r,e-1,M));r<100&&r>=0&&tr.setUTCFullYear(tr.getUTCFullYear()-1900);const rr=tr.getUTCDay();return rr===0?7:rr}function computeOrdinal(r,e,M){return M+(isLeapYear(r)?leapLadder:nonLeapLadder)[e-1]}function uncomputeOrdinal(r,e){const M=isLeapYear(r)?leapLadder:nonLeapLadder,tr=M.findIndex(ir=>ir<e),rr=e-M[tr];return{month:tr+1,day:rr}}function isoWeekdayToLocal(r,e){return(r-e+7)%7+1}function gregorianToWeek(r,e=4,M=1){const{year:tr,month:rr,day:ir}=r,lr=computeOrdinal(tr,rr,ir),dr=isoWeekdayToLocal(dayOfWeek(tr,rr,ir),M);let hr=Math.floor((lr-dr+14-e)/7),fr;return hr<1?(fr=tr-1,hr=weeksInWeekYear(fr,e,M)):hr>weeksInWeekYear(tr,e,M)?(fr=tr+1,hr=1):fr=tr,{weekYear:fr,weekNumber:hr,weekday:dr,...timeObject(r)}}function weekToGregorian(r,e=4,M=1){const{weekYear:tr,weekNumber:rr,weekday:ir}=r,lr=isoWeekdayToLocal(dayOfWeek(tr,1,e),M),dr=daysInYear(tr);let hr=rr*7+ir-lr-7+e,fr;hr<1?(fr=tr-1,hr+=daysInYear(fr)):hr>dr?(fr=tr+1,hr-=daysInYear(tr)):fr=tr;const{month:mr,day:_r}=uncomputeOrdinal(fr,hr);return{year:fr,month:mr,day:_r,...timeObject(r)}}function gregorianToOrdinal(r){const{year:e,month:M,day:tr}=r,rr=computeOrdinal(e,M,tr);return{year:e,ordinal:rr,...timeObject(r)}}function ordinalToGregorian(r){const{year:e,ordinal:M}=r,{month:tr,day:rr}=uncomputeOrdinal(e,M);return{year:e,month:tr,day:rr,...timeObject(r)}}function usesLocalWeekValues(r,e){if(!isUndefined(r.localWeekday)||!isUndefined(r.localWeekNumber)||!isUndefined(r.localWeekYear)){if(!isUndefined(r.weekday)||!isUndefined(r.weekNumber)||!isUndefined(r.weekYear))throw new ConflictingSpecificationError("Cannot mix locale-based week fields with ISO-based week fields");return isUndefined(r.localWeekday)||(r.weekday=r.localWeekday),isUndefined(r.localWeekNumber)||(r.weekNumber=r.localWeekNumber),isUndefined(r.localWeekYear)||(r.weekYear=r.localWeekYear),delete r.localWeekday,delete r.localWeekNumber,delete r.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function hasInvalidWeekData(r,e=4,M=1){const tr=isInteger(r.weekYear),rr=integerBetween(r.weekNumber,1,weeksInWeekYear(r.weekYear,e,M)),ir=integerBetween(r.weekday,1,7);return tr?rr?ir?!1:unitOutOfRange("weekday",r.weekday):unitOutOfRange("week",r.weekNumber):unitOutOfRange("weekYear",r.weekYear)}function hasInvalidOrdinalData(r){const e=isInteger(r.year),M=integerBetween(r.ordinal,1,daysInYear(r.year));return e?M?!1:unitOutOfRange("ordinal",r.ordinal):unitOutOfRange("year",r.year)}function hasInvalidGregorianData(r){const e=isInteger(r.year),M=integerBetween(r.month,1,12),tr=integerBetween(r.day,1,daysInMonth(r.year,r.month));return e?M?tr?!1:unitOutOfRange("day",r.day):unitOutOfRange("month",r.month):unitOutOfRange("year",r.year)}function hasInvalidTimeData(r){const{hour:e,minute:M,second:tr,millisecond:rr}=r,ir=integerBetween(e,0,23)||e===24&&M===0&&tr===0&&rr===0,lr=integerBetween(M,0,59),dr=integerBetween(tr,0,59),hr=integerBetween(rr,0,999);return ir?lr?dr?hr?!1:unitOutOfRange("millisecond",rr):unitOutOfRange("second",tr):unitOutOfRange("minute",M):unitOutOfRange("hour",e)}function isUndefined(r){return typeof r>"u"}function isNumber(r){return typeof r=="number"}function isInteger(r){return typeof r=="number"&&r%1===0}function isString(r){return typeof r=="string"}function isDate(r){return Object.prototype.toString.call(r)==="[object Date]"}function hasRelative(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function hasLocaleWeekInfo(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function maybeArray(r){return Array.isArray(r)?r:[r]}function bestBy(r,e,M){if(r.length!==0)return r.reduce((tr,rr)=>{const ir=[e(rr),rr];return tr&&M(tr[0],ir[0])===tr[0]?tr:ir},null)[1]}function pick(r,e){return e.reduce((M,tr)=>(M[tr]=r[tr],M),{})}function hasOwnProperty(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function validateWeekSettings(r){if(r==null)return null;if(typeof r!="object")throw new InvalidArgumentError("Week settings must be an object");if(!integerBetween(r.firstDay,1,7)||!integerBetween(r.minimalDays,1,7)||!Array.isArray(r.weekend)||r.weekend.some(e=>!integerBetween(e,1,7)))throw new InvalidArgumentError("Invalid week settings");return{firstDay:r.firstDay,minimalDays:r.minimalDays,weekend:Array.from(r.weekend)}}function integerBetween(r,e,M){return isInteger(r)&&r>=e&&r<=M}function floorMod(r,e){return r-e*Math.floor(r/e)}function padStart(r,e=2){const M=r<0;let tr;return M?tr="-"+(""+-r).padStart(e,"0"):tr=(""+r).padStart(e,"0"),tr}function parseInteger(r){if(!(isUndefined(r)||r===null||r===""))return parseInt(r,10)}function parseFloating(r){if(!(isUndefined(r)||r===null||r===""))return parseFloat(r)}function parseMillis(r){if(!(isUndefined(r)||r===null||r==="")){const e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function roundTo(r,e,M="round"){const tr=10**e;switch(M){case"expand":return r>0?Math.ceil(r*tr)/tr:Math.floor(r*tr)/tr;case"trunc":return Math.trunc(r*tr)/tr;case"round":return Math.round(r*tr)/tr;case"floor":return Math.floor(r*tr)/tr;case"ceil":return Math.ceil(r*tr)/tr;default:throw new RangeError(`Value rounding ${M} is out of range`)}}function isLeapYear(r){return r%4===0&&(r%100!==0||r%400===0)}function daysInYear(r){return isLeapYear(r)?366:365}function daysInMonth(r,e){const M=floorMod(e-1,12)+1,tr=r+(e-M)/12;return M===2?isLeapYear(tr)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][M-1]}function objToLocalTS(r){let e=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return r.year<100&&r.year>=0&&(e=new Date(e),e.setUTCFullYear(r.year,r.month-1,r.day)),+e}function firstWeekOffset(r,e,M){return-isoWeekdayToLocal(dayOfWeek(r,1,e),M)+e-1}function weeksInWeekYear(r,e=4,M=1){const tr=firstWeekOffset(r,e,M),rr=firstWeekOffset(r+1,e,M);return(daysInYear(r)-tr+rr)/7}function untruncateYear(r){return r>99?r:r>Settings.twoDigitCutoffYear?1900+r:2e3+r}function parseZoneInfo(r,e,M,tr=null){const rr=new Date(r),ir={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};tr&&(ir.timeZone=tr);const lr={timeZoneName:e,...ir},dr=new Intl.DateTimeFormat(M,lr).formatToParts(rr).find(hr=>hr.type.toLowerCase()==="timezonename");return dr?dr.value:null}function signedOffset(r,e){let M=parseInt(r,10);Number.isNaN(M)&&(M=0);const tr=parseInt(e,10)||0,rr=M<0||Object.is(M,-0)?-tr:tr;return M*60+rr}function asNumber(r){const e=Number(r);if(typeof r=="boolean"||r===""||!Number.isFinite(e))throw new InvalidArgumentError(`Invalid unit value ${r}`);return e}function normalizeObject(r,e){const M={};for(const tr in r)if(hasOwnProperty(r,tr)){const rr=r[tr];if(rr==null)continue;M[e(tr)]=asNumber(rr)}return M}function formatOffset(r,e){const M=Math.trunc(Math.abs(r/60)),tr=Math.trunc(Math.abs(r%60)),rr=r>=0?"+":"-";switch(e){case"short":return`${rr}${padStart(M,2)}:${padStart(tr,2)}`;case"narrow":return`${rr}${M}${tr>0?`:${tr}`:""}`;case"techie":return`${rr}${padStart(M,2)}${padStart(tr,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function timeObject(r){return pick(r,["hour","minute","second","millisecond"])}const monthsLong=["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],monthsNarrow=["J","F","M","A","M","J","J","A","S","O","N","D"];function months(r){switch(r){case"narrow":return[...monthsNarrow];case"short":return[...monthsShort];case"long":return[...monthsLong];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const weekdaysLong=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],weekdaysShort=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],weekdaysNarrow=["M","T","W","T","F","S","S"];function weekdays(r){switch(r){case"narrow":return[...weekdaysNarrow];case"short":return[...weekdaysShort];case"long":return[...weekdaysLong];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const meridiems=["AM","PM"],erasLong=["Before Christ","Anno Domini"],erasShort=["BC","AD"],erasNarrow=["B","A"];function eras(r){switch(r){case"narrow":return[...erasNarrow];case"short":return[...erasShort];case"long":return[...erasLong];default:return null}}function meridiemForDateTime(r){return meridiems[r.hour<12?0:1]}function weekdayForDateTime(r,e){return weekdays(e)[r.weekday-1]}function monthForDateTime(r,e){return months(e)[r.month-1]}function eraForDateTime(r,e){return eras(e)[r.year<0?0:1]}function formatRelativeTime(r,e,M="always",tr=!1){const rr={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},ir=["hours","minutes","seconds"].indexOf(r)===-1;if(M==="auto"&&ir){const _r=r==="days";switch(e){case 1:return _r?"tomorrow":`next ${rr[r][0]}`;case-1:return _r?"yesterday":`last ${rr[r][0]}`;case 0:return _r?"today":`this ${rr[r][0]}`}}const lr=Object.is(e,-0)||e<0,dr=Math.abs(e),hr=dr===1,fr=rr[r],mr=tr?hr?fr[1]:fr[2]||fr[1]:hr?rr[r][0]:r;return lr?`${dr} ${mr} ago`:`in ${dr} ${mr}`}function stringifyTokens(r,e){let M="";for(const tr of r)tr.literal?M+=tr.val:M+=e(tr.val);return M}const macroTokenToFormatOpts={D:DATE_SHORT,DD:DATE_MED,DDD:DATE_FULL,DDDD:DATE_HUGE,t:TIME_SIMPLE,tt:TIME_WITH_SECONDS,ttt:TIME_WITH_SHORT_OFFSET,tttt:TIME_WITH_LONG_OFFSET,T:TIME_24_SIMPLE,TT:TIME_24_WITH_SECONDS,TTT:TIME_24_WITH_SHORT_OFFSET,TTTT:TIME_24_WITH_LONG_OFFSET,f:DATETIME_SHORT,ff:DATETIME_MED,fff:DATETIME_FULL,ffff:DATETIME_HUGE,F:DATETIME_SHORT_WITH_SECONDS,FF:DATETIME_MED_WITH_SECONDS,FFF:DATETIME_FULL_WITH_SECONDS,FFFF:DATETIME_HUGE_WITH_SECONDS};class Formatter{static create(e,M={}){return new Formatter(e,M)}static parseFormat(e){let M=null,tr="",rr=!1;const ir=[];for(let lr=0;lr<e.length;lr++){const dr=e.charAt(lr);dr==="'"?((tr.length>0||rr)&&ir.push({literal:rr||/^\s+$/.test(tr),val:tr===""?"'":tr}),M=null,tr="",rr=!rr):rr||dr===M?tr+=dr:(tr.length>0&&ir.push({literal:/^\s+$/.test(tr),val:tr}),tr=dr,M=dr)}return tr.length>0&&ir.push({literal:rr||/^\s+$/.test(tr),val:tr}),ir}static macroTokenToFormatOpts(e){return macroTokenToFormatOpts[e]}constructor(e,M){this.opts=M,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,M){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...M}).format()}dtFormatter(e,M={}){return this.loc.dtFormatter(e,{...this.opts,...M})}formatDateTime(e,M){return this.dtFormatter(e,M).format()}formatDateTimeParts(e,M){return this.dtFormatter(e,M).formatToParts()}formatInterval(e,M){return this.dtFormatter(e.start,M).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,M){return this.dtFormatter(e,M).resolvedOptions()}num(e,M=0,tr=void 0){if(this.opts.forceSimple)return padStart(e,M);const rr={...this.opts};return M>0&&(rr.padTo=M),tr&&(rr.signDisplay=tr),this.loc.numberFormatter(rr).format(e)}formatDateTimeFromString(e,M){const tr=this.loc.listingMode()==="en",rr=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",ir=(wr,yr)=>this.loc.extract(e,wr,yr),lr=wr=>e.isOffsetFixed&&e.offset===0&&wr.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,wr.format):"",dr=()=>tr?meridiemForDateTime(e):ir({hour:"numeric",hourCycle:"h12"},"dayperiod"),hr=(wr,yr)=>tr?monthForDateTime(e,wr):ir(yr?{month:wr}:{month:wr,day:"numeric"},"month"),fr=(wr,yr)=>tr?weekdayForDateTime(e,wr):ir(yr?{weekday:wr}:{weekday:wr,month:"long",day:"numeric"},"weekday"),mr=wr=>{const yr=Formatter.macroTokenToFormatOpts(wr);return yr?this.formatWithSystemDefault(e,yr):wr},_r=wr=>tr?eraForDateTime(e,wr):ir({era:wr},"era"),gr=wr=>{switch(wr){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return lr({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return lr({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return lr({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return dr();case"d":return rr?ir({day:"numeric"},"day"):this.num(e.day);case"dd":return rr?ir({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return fr("short",!0);case"cccc":return fr("long",!0);case"ccccc":return fr("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return fr("short",!1);case"EEEE":return fr("long",!1);case"EEEEE":return fr("narrow",!1);case"L":return rr?ir({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return rr?ir({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return hr("short",!0);case"LLLL":return hr("long",!0);case"LLLLL":return hr("narrow",!0);case"M":return rr?ir({month:"numeric"},"month"):this.num(e.month);case"MM":return rr?ir({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return hr("short",!1);case"MMMM":return hr("long",!1);case"MMMMM":return hr("narrow",!1);case"y":return rr?ir({year:"numeric"},"year"):this.num(e.year);case"yy":return rr?ir({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return rr?ir({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return rr?ir({year:"numeric"},"year"):this.num(e.year,6);case"G":return _r("short");case"GG":return _r("long");case"GGGGG":return _r("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return mr(wr)}};return stringifyTokens(Formatter.parseFormat(M),gr)}formatDurationFromString(e,M){const tr=this.opts.signMode==="negativeLargestOnly"?-1:1,rr=mr=>{switch(mr[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},ir=(mr,_r)=>gr=>{const wr=rr(gr);if(wr){const yr=_r.isNegativeDuration&&wr!==_r.largestUnit?tr:1;let br;return this.opts.signMode==="negativeLargestOnly"&&wr!==_r.largestUnit?br="never":this.opts.signMode==="all"?br="always":br="auto",this.num(mr.get(wr)*yr,gr.length,br)}else return gr},lr=Formatter.parseFormat(M),dr=lr.reduce((mr,{literal:_r,val:gr})=>_r?mr:mr.concat(gr),[]),hr=e.shiftTo(...dr.map(rr).filter(mr=>mr)),fr={isNegativeDuration:hr<0,largestUnit:Object.keys(hr.values)[0]};return stringifyTokens(lr,ir(hr,fr))}}const ianaRegex=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function combineRegexes(...r){const e=r.reduce((M,tr)=>M+tr.source,"");return RegExp(`^${e}$`)}function combineExtractors(...r){return e=>r.reduce(([M,tr,rr],ir)=>{const[lr,dr,hr]=ir(e,rr);return[{...M,...lr},dr||tr,hr]},[{},null,1]).slice(0,2)}function parse$1(r,...e){if(r==null)return[null,null];for(const[M,tr]of e){const rr=M.exec(r);if(rr)return tr(rr)}return[null,null]}function simpleParse(...r){return(e,M)=>{const tr={};let rr;for(rr=0;rr<r.length;rr++)tr[r[rr]]=parseInteger(e[M+rr]);return[tr,null,M+rr]}}const offsetRegex=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,isoExtendedZone=`(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`,isoTimeBaseRegex=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,isoTimeRegex=RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`),isoTimeExtensionRegex=RegExp(`(?:[Tt]${isoTimeRegex.source})?`),isoYmdRegex=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,isoWeekRegex=/(\d{4})-?W(\d\d)(?:-?(\d))?/,isoOrdinalRegex=/(\d{4})-?(\d{3})/,extractISOWeekData=simpleParse("weekYear","weekNumber","weekDay"),extractISOOrdinalData=simpleParse("year","ordinal"),sqlYmdRegex=/(\d{4})-(\d\d)-(\d\d)/,sqlTimeRegex=RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`),sqlTimeExtensionRegex=RegExp(`(?: ${sqlTimeRegex.source})?`);function int(r,e,M){const tr=r[e];return isUndefined(tr)?M:parseInteger(tr)}function extractISOYmd(r,e){return[{year:int(r,e),month:int(r,e+1,1),day:int(r,e+2,1)},null,e+3]}function extractISOTime(r,e){return[{hours:int(r,e,0),minutes:int(r,e+1,0),seconds:int(r,e+2,0),milliseconds:parseMillis(r[e+3])},null,e+4]}function extractISOOffset(r,e){const M=!r[e]&&!r[e+1],tr=signedOffset(r[e+1],r[e+2]),rr=M?null:FixedOffsetZone.instance(tr);return[{},rr,e+3]}function extractIANAZone(r,e){const M=r[e]?IANAZone.create(r[e]):null;return[{},M,e+1]}const isoTimeOnly=RegExp(`^T?${isoTimeBaseRegex.source}$`),isoDuration=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function extractISODuration(r){const[e,M,tr,rr,ir,lr,dr,hr,fr]=r,mr=e[0]==="-",_r=hr&&hr[0]==="-",gr=(wr,yr=!1)=>wr!==void 0&&(yr||wr&&mr)?-wr:wr;return[{years:gr(parseFloating(M)),months:gr(parseFloating(tr)),weeks:gr(parseFloating(rr)),days:gr(parseFloating(ir)),hours:gr(parseFloating(lr)),minutes:gr(parseFloating(dr)),seconds:gr(parseFloating(hr),hr==="-0"),milliseconds:gr(parseMillis(fr),_r)}]}const obsOffsets={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function fromStrings(r,e,M,tr,rr,ir,lr){const dr={year:e.length===2?untruncateYear(parseInteger(e)):parseInteger(e),month:monthsShort.indexOf(M)+1,day:parseInteger(tr),hour:parseInteger(rr),minute:parseInteger(ir)};return lr&&(dr.second=parseInteger(lr)),r&&(dr.weekday=r.length>3?weekdaysLong.indexOf(r)+1:weekdaysShort.indexOf(r)+1),dr}const rfc2822=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function extractRFC2822(r){const[,e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r]=r,gr=fromStrings(e,rr,tr,M,ir,lr,dr);let wr;return hr?wr=obsOffsets[hr]:fr?wr=0:wr=signedOffset(mr,_r),[gr,new FixedOffsetZone(wr)]}function preprocessRFC2822(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const rfc1123=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,rfc850=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,ascii$2=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function extractRFC1123Or850(r){const[,e,M,tr,rr,ir,lr,dr]=r;return[fromStrings(e,rr,tr,M,ir,lr,dr),FixedOffsetZone.utcInstance]}function extractASCII(r){const[,e,M,tr,rr,ir,lr,dr]=r;return[fromStrings(e,dr,M,tr,rr,ir,lr),FixedOffsetZone.utcInstance]}const isoYmdWithTimeExtensionRegex=combineRegexes(isoYmdRegex,isoTimeExtensionRegex),isoWeekWithTimeExtensionRegex=combineRegexes(isoWeekRegex,isoTimeExtensionRegex),isoOrdinalWithTimeExtensionRegex=combineRegexes(isoOrdinalRegex,isoTimeExtensionRegex),isoTimeCombinedRegex=combineRegexes(isoTimeRegex),extractISOYmdTimeAndOffset=combineExtractors(extractISOYmd,extractISOTime,extractISOOffset,extractIANAZone),extractISOWeekTimeAndOffset=combineExtractors(extractISOWeekData,extractISOTime,extractISOOffset,extractIANAZone),extractISOOrdinalDateAndTime=combineExtractors(extractISOOrdinalData,extractISOTime,extractISOOffset,extractIANAZone),extractISOTimeAndOffset=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseISODate(r){return parse$1(r,[isoYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[isoWeekWithTimeExtensionRegex,extractISOWeekTimeAndOffset],[isoOrdinalWithTimeExtensionRegex,extractISOOrdinalDateAndTime],[isoTimeCombinedRegex,extractISOTimeAndOffset])}function parseRFC2822Date(r){return parse$1(preprocessRFC2822(r),[rfc2822,extractRFC2822])}function parseHTTPDate(r){return parse$1(r,[rfc1123,extractRFC1123Or850],[rfc850,extractRFC1123Or850],[ascii$2,extractASCII])}function parseISODuration(r){return parse$1(r,[isoDuration,extractISODuration])}const extractISOTimeOnly=combineExtractors(extractISOTime);function parseISOTimeOnly(r){return parse$1(r,[isoTimeOnly,extractISOTimeOnly])}const sqlYmdWithTimeExtensionRegex=combineRegexes(sqlYmdRegex,sqlTimeExtensionRegex),sqlTimeCombinedRegex=combineRegexes(sqlTimeRegex),extractISOTimeOffsetAndIANAZone=combineExtractors(extractISOTime,extractISOOffset,extractIANAZone);function parseSQL(r){return parse$1(r,[sqlYmdWithTimeExtensionRegex,extractISOYmdTimeAndOffset],[sqlTimeCombinedRegex,extractISOTimeOffsetAndIANAZone])}const INVALID$2="Invalid Duration",lowOrderMatrix={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},casualMatrix={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...lowOrderMatrix},daysInYearAccurate=146097/400,daysInMonthAccurate=146097/4800,accurateMatrix={years:{quarters:4,months:12,weeks:daysInYearAccurate/7,days:daysInYearAccurate,hours:daysInYearAccurate*24,minutes:daysInYearAccurate*24*60,seconds:daysInYearAccurate*24*60*60,milliseconds:daysInYearAccurate*24*60*60*1e3},quarters:{months:3,weeks:daysInYearAccurate/28,days:daysInYearAccurate/4,hours:daysInYearAccurate*24/4,minutes:daysInYearAccurate*24*60/4,seconds:daysInYearAccurate*24*60*60/4,milliseconds:daysInYearAccurate*24*60*60*1e3/4},months:{weeks:daysInMonthAccurate/7,days:daysInMonthAccurate,hours:daysInMonthAccurate*24,minutes:daysInMonthAccurate*24*60,seconds:daysInMonthAccurate*24*60*60,milliseconds:daysInMonthAccurate*24*60*60*1e3},...lowOrderMatrix},orderedUnits$1=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],reverseUnits=orderedUnits$1.slice(0).reverse();function clone$1(r,e,M=!1){const tr={values:M?e.values:{...r.values,...e.values||{}},loc:r.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||r.conversionAccuracy,matrix:e.matrix||r.matrix};return new Duration(tr)}function durationToMillis(r,e){let M=e.milliseconds??0;for(const tr of reverseUnits.slice(1))e[tr]&&(M+=e[tr]*r[tr].milliseconds);return M}function normalizeValues(r,e){const M=durationToMillis(r,e)<0?-1:1;orderedUnits$1.reduceRight((tr,rr)=>{if(isUndefined(e[rr]))return tr;if(tr){const ir=e[tr]*M,lr=r[rr][tr],dr=Math.floor(ir/lr);e[rr]+=dr*M,e[tr]-=dr*lr*M}return rr},null),orderedUnits$1.reduce((tr,rr)=>{if(isUndefined(e[rr]))return tr;if(tr){const ir=e[tr]%1;e[tr]-=ir,e[rr]+=ir*r[tr][rr]}return rr},null)}function removeZeroes(r){const e={};for(const[M,tr]of Object.entries(r))tr!==0&&(e[M]=tr);return e}class Duration{constructor(e){const M=e.conversionAccuracy==="longterm"||!1;let tr=M?accurateMatrix:casualMatrix;e.matrix&&(tr=e.matrix),this.values=e.values,this.loc=e.loc||Locale.create(),this.conversionAccuracy=M?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=tr,this.isLuxonDuration=!0}static fromMillis(e,M){return Duration.fromObject({milliseconds:e},M)}static fromObject(e,M={}){if(e==null||typeof e!="object")throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new Duration({values:normalizeObject(e,Duration.normalizeUnit),loc:Locale.fromObject(M),conversionAccuracy:M.conversionAccuracy,matrix:M.matrix})}static fromDurationLike(e){if(isNumber(e))return Duration.fromMillis(e);if(Duration.isDuration(e))return e;if(typeof e=="object")return Duration.fromObject(e);throw new InvalidArgumentError(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,M){const[tr]=parseISODuration(e);return tr?Duration.fromObject(tr,M):Duration.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,M){const[tr]=parseISOTimeOnly(e);return tr?Duration.fromObject(tr,M):Duration.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,M=null){if(!e)throw new InvalidArgumentError("need to specify a reason the Duration is invalid");const tr=e instanceof Invalid?e:new Invalid(e,M);if(Settings.throwOnInvalid)throw new InvalidDurationError(tr);return new Duration({invalid:tr})}static normalizeUnit(e){const M={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!M)throw new InvalidUnitError(e);return M}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,M={}){const tr={...M,floor:M.round!==!1&&M.floor!==!1};return this.isValid?Formatter.create(this.loc,tr).formatDurationFromString(this,e):INVALID$2}toHuman(e={}){if(!this.isValid)return INVALID$2;const M=e.showZeros!==!1,tr=orderedUnits$1.map(rr=>{const ir=this.values[rr];return isUndefined(ir)||ir===0&&!M?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:rr.slice(0,-1)}).format(ir)}).filter(rr=>rr);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(tr)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=roundTo(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const M=this.toMillis();return M<0||M>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},DateTime.fromMillis(M,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?durationToMillis(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const M=Duration.fromDurationLike(e),tr={};for(const rr of orderedUnits$1)(hasOwnProperty(M.values,rr)||hasOwnProperty(this.values,rr))&&(tr[rr]=M.get(rr)+this.get(rr));return clone$1(this,{values:tr},!0)}minus(e){if(!this.isValid)return this;const M=Duration.fromDurationLike(e);return this.plus(M.negate())}mapUnits(e){if(!this.isValid)return this;const M={};for(const tr of Object.keys(this.values))M[tr]=asNumber(e(this.values[tr],tr));return clone$1(this,{values:M},!0)}get(e){return this[Duration.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const M={...this.values,...normalizeObject(e,Duration.normalizeUnit)};return clone$1(this,{values:M})}reconfigure({locale:e,numberingSystem:M,conversionAccuracy:tr,matrix:rr}={}){const lr={loc:this.loc.clone({locale:e,numberingSystem:M}),matrix:rr,conversionAccuracy:tr};return clone$1(this,lr)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return normalizeValues(this.matrix,e),clone$1(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=removeZeroes(this.normalize().shiftToAll().toObject());return clone$1(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(lr=>Duration.normalizeUnit(lr));const M={},tr={},rr=this.toObject();let ir;for(const lr of orderedUnits$1)if(e.indexOf(lr)>=0){ir=lr;let dr=0;for(const fr in tr)dr+=this.matrix[fr][lr]*tr[fr],tr[fr]=0;isNumber(rr[lr])&&(dr+=rr[lr]);const hr=Math.trunc(dr);M[lr]=hr,tr[lr]=(dr*1e3-hr*1e3)/1e3}else isNumber(rr[lr])&&(tr[lr]=rr[lr]);for(const lr in tr)tr[lr]!==0&&(M[ir]+=lr===ir?tr[lr]:tr[lr]/this.matrix[ir][lr]);return normalizeValues(this.matrix,M),clone$1(this,{values:M},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const M of Object.keys(this.values))e[M]=this.values[M]===0?0:-this.values[M];return clone$1(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=removeZeroes(this.values);return clone$1(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function M(tr,rr){return tr===void 0||tr===0?rr===void 0||rr===0:tr===rr}for(const tr of orderedUnits$1)if(!M(this.values[tr],e.values[tr]))return!1;return!0}}const INVALID$1="Invalid Interval";function validateStartEnd(r,e){return!r||!r.isValid?Interval.invalid("missing or invalid start"):!e||!e.isValid?Interval.invalid("missing or invalid end"):e<r?Interval.invalid("end before start",`The end of an interval must be after its start, but you had start=${r.toISO()} and end=${e.toISO()}`):null}class Interval{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,M=null){if(!e)throw new InvalidArgumentError("need to specify a reason the Interval is invalid");const tr=e instanceof Invalid?e:new Invalid(e,M);if(Settings.throwOnInvalid)throw new InvalidIntervalError(tr);return new Interval({invalid:tr})}static fromDateTimes(e,M){const tr=friendlyDateTime(e),rr=friendlyDateTime(M),ir=validateStartEnd(tr,rr);return ir??new Interval({start:tr,end:rr})}static after(e,M){const tr=Duration.fromDurationLike(M),rr=friendlyDateTime(e);return Interval.fromDateTimes(rr,rr.plus(tr))}static before(e,M){const tr=Duration.fromDurationLike(M),rr=friendlyDateTime(e);return Interval.fromDateTimes(rr.minus(tr),rr)}static fromISO(e,M){const[tr,rr]=(e||"").split("/",2);if(tr&&rr){let ir,lr;try{ir=DateTime.fromISO(tr,M),lr=ir.isValid}catch{lr=!1}let dr,hr;try{dr=DateTime.fromISO(rr,M),hr=dr.isValid}catch{hr=!1}if(lr&&hr)return Interval.fromDateTimes(ir,dr);if(lr){const fr=Duration.fromISO(rr,M);if(fr.isValid)return Interval.after(ir,fr)}else if(hr){const fr=Duration.fromISO(tr,M);if(fr.isValid)return Interval.before(dr,fr)}}return Interval.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",M){if(!this.isValid)return NaN;const tr=this.start.startOf(e,M);let rr;return M?.useLocaleWeeks?rr=this.end.reconfigure({locale:tr.locale}):rr=this.end,rr=rr.startOf(e,M),Math.floor(rr.diff(tr,e).get(e))+(rr.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:M}={}){return this.isValid?Interval.fromDateTimes(e||this.s,M||this.e):this}splitAt(...e){if(!this.isValid)return[];const M=e.map(friendlyDateTime).filter(lr=>this.contains(lr)).sort((lr,dr)=>lr.toMillis()-dr.toMillis()),tr=[];let{s:rr}=this,ir=0;for(;rr<this.e;){const lr=M[ir]||this.e,dr=+lr>+this.e?this.e:lr;tr.push(Interval.fromDateTimes(rr,dr)),rr=dr,ir+=1}return tr}splitBy(e){const M=Duration.fromDurationLike(e);if(!this.isValid||!M.isValid||M.as("milliseconds")===0)return[];let{s:tr}=this,rr=1,ir;const lr=[];for(;tr<this.e;){const dr=this.start.plus(M.mapUnits(hr=>hr*rr));ir=+dr>+this.e?this.e:dr,lr.push(Interval.fromDateTimes(tr,ir)),tr=ir,rr+=1}return lr}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const M=this.s>e.s?this.s:e.s,tr=this.e<e.e?this.e:e.e;return M>=tr?null:Interval.fromDateTimes(M,tr)}union(e){if(!this.isValid)return this;const M=this.s<e.s?this.s:e.s,tr=this.e>e.e?this.e:e.e;return Interval.fromDateTimes(M,tr)}static merge(e){const[M,tr]=e.sort((rr,ir)=>rr.s-ir.s).reduce(([rr,ir],lr)=>ir?ir.overlaps(lr)||ir.abutsStart(lr)?[rr,ir.union(lr)]:[rr.concat([ir]),lr]:[rr,lr],[[],null]);return tr&&M.push(tr),M}static xor(e){let M=null,tr=0;const rr=[],ir=e.map(hr=>[{time:hr.s,type:"s"},{time:hr.e,type:"e"}]),lr=Array.prototype.concat(...ir),dr=lr.sort((hr,fr)=>hr.time-fr.time);for(const hr of dr)tr+=hr.type==="s"?1:-1,tr===1?M=hr.time:(M&&+M!=+hr.time&&rr.push(Interval.fromDateTimes(M,hr.time)),M=null);return Interval.merge(rr)}difference(...e){return Interval.xor([this].concat(e)).map(M=>this.intersection(M)).filter(M=>M&&!M.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:INVALID$1}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=DATE_SHORT,M={}){return this.isValid?Formatter.create(this.s.loc.clone(M),e).formatInterval(this):INVALID$1}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:INVALID$1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:INVALID$1}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:INVALID$1}toFormat(e,{separator:M=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${M}${this.e.toFormat(e)}`:INVALID$1}toDuration(e,M){return this.isValid?this.e.diff(this.s,e,M):Duration.invalid(this.invalidReason)}mapEndpoints(e){return Interval.fromDateTimes(e(this.s),e(this.e))}}class Info{static hasDST(e=Settings.defaultZone){const M=DateTime.now().setZone(e).set({month:12});return!e.isUniversal&&M.offset!==M.set({month:6}).offset}static isValidIANAZone(e){return IANAZone.isValidZone(e)}static normalizeZone(e){return normalizeZone(e,Settings.defaultZone)}static getStartOfWeek({locale:e=null,locObj:M=null}={}){return(M||Locale.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:M=null}={}){return(M||Locale.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:M=null}={}){return(M||Locale.create(e)).getWeekendDays().slice()}static months(e="long",{locale:M=null,numberingSystem:tr=null,locObj:rr=null,outputCalendar:ir="gregory"}={}){return(rr||Locale.create(M,tr,ir)).months(e)}static monthsFormat(e="long",{locale:M=null,numberingSystem:tr=null,locObj:rr=null,outputCalendar:ir="gregory"}={}){return(rr||Locale.create(M,tr,ir)).months(e,!0)}static weekdays(e="long",{locale:M=null,numberingSystem:tr=null,locObj:rr=null}={}){return(rr||Locale.create(M,tr,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:M=null,numberingSystem:tr=null,locObj:rr=null}={}){return(rr||Locale.create(M,tr,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return Locale.create(e).meridiems()}static eras(e="short",{locale:M=null}={}){return Locale.create(M,null,"gregory").eras(e)}static features(){return{relative:hasRelative(),localeWeek:hasLocaleWeekInfo()}}}function dayDiff(r,e){const M=rr=>rr.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),tr=M(e)-M(r);return Math.floor(Duration.fromMillis(tr).as("days"))}function highOrderDiffs(r,e,M){const tr=[["years",(hr,fr)=>fr.year-hr.year],["quarters",(hr,fr)=>fr.quarter-hr.quarter+(fr.year-hr.year)*4],["months",(hr,fr)=>fr.month-hr.month+(fr.year-hr.year)*12],["weeks",(hr,fr)=>{const mr=dayDiff(hr,fr);return(mr-mr%7)/7}],["days",dayDiff]],rr={},ir=r;let lr,dr;for(const[hr,fr]of tr)M.indexOf(hr)>=0&&(lr=hr,rr[hr]=fr(r,e),dr=ir.plus(rr),dr>e?(rr[hr]--,r=ir.plus(rr),r>e&&(dr=r,rr[hr]--,r=ir.plus(rr))):r=dr);return[r,rr,dr,lr]}function diff(r,e,M,tr){let[rr,ir,lr,dr]=highOrderDiffs(r,e,M);const hr=e-rr,fr=M.filter(_r=>["hours","minutes","seconds","milliseconds"].indexOf(_r)>=0);fr.length===0&&(lr<e&&(lr=rr.plus({[dr]:1})),lr!==rr&&(ir[dr]=(ir[dr]||0)+hr/(lr-rr)));const mr=Duration.fromObject(ir,tr);return fr.length>0?Duration.fromMillis(hr,tr).shiftTo(...fr).plus(mr):mr}const MISSING_FTP="missing Intl.DateTimeFormat.formatToParts support";function intUnit(r,e=M=>M){return{regex:r,deser:([M])=>e(parseDigits(M))}}const NBSP=" ",spaceOrNBSP=`[ ${NBSP}]`,spaceOrNBSPRegExp=new RegExp(spaceOrNBSP,"g");function fixListRegex(r){return r.replace(/\./g,"\\.?").replace(spaceOrNBSPRegExp,spaceOrNBSP)}function stripInsensitivities(r){return r.replace(/\./g,"").replace(spaceOrNBSPRegExp," ").toLowerCase()}function oneOf(r,e){return r===null?null:{regex:RegExp(r.map(fixListRegex).join("|")),deser:([M])=>r.findIndex(tr=>stripInsensitivities(M)===stripInsensitivities(tr))+e}}function offset(r,e){return{regex:r,deser:([,M,tr])=>signedOffset(M,tr),groups:e}}function simple(r){return{regex:r,deser:([e])=>e}}function escapeToken(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function unitForToken(r,e){const M=digitRegex(e),tr=digitRegex(e,"{2}"),rr=digitRegex(e,"{3}"),ir=digitRegex(e,"{4}"),lr=digitRegex(e,"{6}"),dr=digitRegex(e,"{1,2}"),hr=digitRegex(e,"{1,3}"),fr=digitRegex(e,"{1,6}"),mr=digitRegex(e,"{1,9}"),_r=digitRegex(e,"{2,4}"),gr=digitRegex(e,"{4,6}"),wr=Mr=>({regex:RegExp(escapeToken(Mr.val)),deser:([vr])=>vr,literal:!0}),br=(Mr=>{if(r.literal)return wr(Mr);switch(Mr.val){case"G":return oneOf(e.eras("short"),0);case"GG":return oneOf(e.eras("long"),0);case"y":return intUnit(fr);case"yy":return intUnit(_r,untruncateYear);case"yyyy":return intUnit(ir);case"yyyyy":return intUnit(gr);case"yyyyyy":return intUnit(lr);case"M":return intUnit(dr);case"MM":return intUnit(tr);case"MMM":return oneOf(e.months("short",!0),1);case"MMMM":return oneOf(e.months("long",!0),1);case"L":return intUnit(dr);case"LL":return intUnit(tr);case"LLL":return oneOf(e.months("short",!1),1);case"LLLL":return oneOf(e.months("long",!1),1);case"d":return intUnit(dr);case"dd":return intUnit(tr);case"o":return intUnit(hr);case"ooo":return intUnit(rr);case"HH":return intUnit(tr);case"H":return intUnit(dr);case"hh":return intUnit(tr);case"h":return intUnit(dr);case"mm":return intUnit(tr);case"m":return intUnit(dr);case"q":return intUnit(dr);case"qq":return intUnit(tr);case"s":return intUnit(dr);case"ss":return intUnit(tr);case"S":return intUnit(hr);case"SSS":return intUnit(rr);case"u":return simple(mr);case"uu":return simple(dr);case"uuu":return intUnit(M);case"a":return oneOf(e.meridiems(),0);case"kkkk":return intUnit(ir);case"kk":return intUnit(_r,untruncateYear);case"W":return intUnit(dr);case"WW":return intUnit(tr);case"E":case"c":return intUnit(M);case"EEE":return oneOf(e.weekdays("short",!1),1);case"EEEE":return oneOf(e.weekdays("long",!1),1);case"ccc":return oneOf(e.weekdays("short",!0),1);case"cccc":return oneOf(e.weekdays("long",!0),1);case"Z":case"ZZ":return offset(new RegExp(`([+-]${dr.source})(?::(${tr.source}))?`),2);case"ZZZ":return offset(new RegExp(`([+-]${dr.source})(${tr.source})?`),2);case"z":return simple(/[a-z_+-/]{1,256}?/i);case" ":return simple(/[^\S\n\r]/);default:return wr(Mr)}})(r)||{invalidReason:MISSING_FTP};return br.token=r,br}const partTypeStyleToTokenVal={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function tokenForPart(r,e,M){const{type:tr,value:rr}=r;if(tr==="literal"){const hr=/^\s+$/.test(rr);return{literal:!hr,val:hr?" ":rr}}const ir=e[tr];let lr=tr;tr==="hour"&&(e.hour12!=null?lr=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?lr="hour12":lr="hour24":lr=M.hour12?"hour12":"hour24");let dr=partTypeStyleToTokenVal[lr];if(typeof dr=="object"&&(dr=dr[ir]),dr)return{literal:!1,val:dr}}function buildRegex(r){return[`^${r.map(M=>M.regex).reduce((M,tr)=>`${M}(${tr.source})`,"")}$`,r]}function match(r,e,M){const tr=r.match(e);if(tr){const rr={};let ir=1;for(const lr in M)if(hasOwnProperty(M,lr)){const dr=M[lr],hr=dr.groups?dr.groups+1:1;!dr.literal&&dr.token&&(rr[dr.token.val[0]]=dr.deser(tr.slice(ir,ir+hr))),ir+=hr}return[tr,rr]}else return[tr,{}]}function dateTimeFromMatches(r){const e=ir=>{switch(ir){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let M=null,tr;return isUndefined(r.z)||(M=IANAZone.create(r.z)),isUndefined(r.Z)||(M||(M=new FixedOffsetZone(r.Z)),tr=r.Z),isUndefined(r.q)||(r.M=(r.q-1)*3+1),isUndefined(r.h)||(r.h<12&&r.a===1?r.h+=12:r.h===12&&r.a===0&&(r.h=0)),r.G===0&&r.y&&(r.y=-r.y),isUndefined(r.u)||(r.S=parseMillis(r.u)),[Object.keys(r).reduce((ir,lr)=>{const dr=e(lr);return dr&&(ir[dr]=r[lr]),ir},{}),M,tr]}let dummyDateTimeCache=null;function getDummyDateTime(){return dummyDateTimeCache||(dummyDateTimeCache=DateTime.fromMillis(1555555555555)),dummyDateTimeCache}function maybeExpandMacroToken(r,e){if(r.literal)return r;const M=Formatter.macroTokenToFormatOpts(r.val),tr=formatOptsToTokens(M,e);return tr==null||tr.includes(void 0)?r:tr}function expandMacroTokens(r,e){return Array.prototype.concat(...r.map(M=>maybeExpandMacroToken(M,e)))}class TokenParser{constructor(e,M){if(this.locale=e,this.format=M,this.tokens=expandMacroTokens(Formatter.parseFormat(M),e),this.units=this.tokens.map(tr=>unitForToken(tr,e)),this.disqualifyingUnit=this.units.find(tr=>tr.invalidReason),!this.disqualifyingUnit){const[tr,rr]=buildRegex(this.units);this.regex=RegExp(tr,"i"),this.handlers=rr}}explainFromTokens(e){if(this.isValid){const[M,tr]=match(e,this.regex,this.handlers),[rr,ir,lr]=tr?dateTimeFromMatches(tr):[null,null,void 0];if(hasOwnProperty(tr,"a")&&hasOwnProperty(tr,"H"))throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:M,matches:tr,result:rr,zone:ir,specificOffset:lr}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function explainFromTokens(r,e,M){return new TokenParser(r,M).explainFromTokens(e)}function parseFromTokens(r,e,M){const{result:tr,zone:rr,specificOffset:ir,invalidReason:lr}=explainFromTokens(r,e,M);return[tr,rr,ir,lr]}function formatOptsToTokens(r,e){if(!r)return null;const tr=Formatter.create(e,r).dtFormatter(getDummyDateTime()),rr=tr.formatToParts(),ir=tr.resolvedOptions();return rr.map(lr=>tokenForPart(lr,r,ir))}const INVALID="Invalid DateTime",MAX_DATE=864e13;function unsupportedZone(r){return new Invalid("unsupported zone",`the zone "${r.name}" is not supported`)}function possiblyCachedWeekData(r){return r.weekData===null&&(r.weekData=gregorianToWeek(r.c)),r.weekData}function possiblyCachedLocalWeekData(r){return r.localWeekData===null&&(r.localWeekData=gregorianToWeek(r.c,r.loc.getMinDaysInFirstWeek(),r.loc.getStartOfWeek())),r.localWeekData}function clone(r,e){const M={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new DateTime({...M,...e,old:M})}function fixOffset(r,e,M){let tr=r-e*60*1e3;const rr=M.offset(tr);if(e===rr)return[tr,e];tr-=(rr-e)*60*1e3;const ir=M.offset(tr);return rr===ir?[tr,rr]:[r-Math.min(rr,ir)*60*1e3,Math.max(rr,ir)]}function tsToObj(r,e){r+=e*60*1e3;const M=new Date(r);return{year:M.getUTCFullYear(),month:M.getUTCMonth()+1,day:M.getUTCDate(),hour:M.getUTCHours(),minute:M.getUTCMinutes(),second:M.getUTCSeconds(),millisecond:M.getUTCMilliseconds()}}function objToTS(r,e,M){return fixOffset(objToLocalTS(r),e,M)}function adjustTime(r,e){const M=r.o,tr=r.c.year+Math.trunc(e.years),rr=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,ir={...r.c,year:tr,month:rr,day:Math.min(r.c.day,daysInMonth(tr,rr))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},lr=Duration.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),dr=objToLocalTS(ir);let[hr,fr]=fixOffset(dr,M,r.zone);return lr!==0&&(hr+=lr,fr=r.zone.offset(hr)),{ts:hr,o:fr}}function parseDataToDateTime(r,e,M,tr,rr,ir){const{setZone:lr,zone:dr}=M;if(r&&Object.keys(r).length!==0||e){const hr=e||dr,fr=DateTime.fromObject(r,{...M,zone:hr,specificOffset:ir});return lr?fr:fr.setZone(dr)}else return DateTime.invalid(new Invalid("unparsable",`the input "${rr}" can't be parsed as ${tr}`))}function toTechFormat(r,e,M=!0){return r.isValid?Formatter.create(Locale.create("en-US"),{allowZ:M,forceSimple:!0}).formatDateTimeFromString(r,e):null}function toISODate(r,e,M){const tr=r.c.year>9999||r.c.year<0;let rr="";if(tr&&r.c.year>=0&&(rr+="+"),rr+=padStart(r.c.year,tr?6:4),M==="year")return rr;if(e){if(rr+="-",rr+=padStart(r.c.month),M==="month")return rr;rr+="-"}else if(rr+=padStart(r.c.month),M==="month")return rr;return rr+=padStart(r.c.day),rr}function toISOTime(r,e,M,tr,rr,ir,lr){let dr=!M||r.c.millisecond!==0||r.c.second!==0,hr="";switch(lr){case"day":case"month":case"year":break;default:if(hr+=padStart(r.c.hour),lr==="hour")break;if(e){if(hr+=":",hr+=padStart(r.c.minute),lr==="minute")break;dr&&(hr+=":",hr+=padStart(r.c.second))}else{if(hr+=padStart(r.c.minute),lr==="minute")break;dr&&(hr+=padStart(r.c.second))}if(lr==="second")break;dr&&(!tr||r.c.millisecond!==0)&&(hr+=".",hr+=padStart(r.c.millisecond,3))}return rr&&(r.isOffsetFixed&&r.offset===0&&!ir?hr+="Z":r.o<0?(hr+="-",hr+=padStart(Math.trunc(-r.o/60)),hr+=":",hr+=padStart(Math.trunc(-r.o%60))):(hr+="+",hr+=padStart(Math.trunc(r.o/60)),hr+=":",hr+=padStart(Math.trunc(r.o%60)))),ir&&(hr+="["+r.zone.ianaName+"]"),hr}const defaultUnitValues={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},defaultWeekUnitValues={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},defaultOrdinalUnitValues={ordinal:1,hour:0,minute:0,second:0,millisecond:0},orderedUnits=["year","month","day","hour","minute","second","millisecond"],orderedWeekUnits=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],orderedOrdinalUnits=["year","ordinal","hour","minute","second","millisecond"];function normalizeUnit(r){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[r.toLowerCase()];if(!e)throw new InvalidUnitError(r);return e}function normalizeUnitWithLocalWeeks(r){switch(r.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return normalizeUnit(r)}}function guessOffsetForZone(r){if(zoneOffsetTs===void 0&&(zoneOffsetTs=Settings.now()),r.type!=="iana")return r.offset(zoneOffsetTs);const e=r.name;let M=zoneOffsetGuessCache.get(e);return M===void 0&&(M=r.offset(zoneOffsetTs),zoneOffsetGuessCache.set(e,M)),M}function quickDT(r,e){const M=normalizeZone(e.zone,Settings.defaultZone);if(!M.isValid)return DateTime.invalid(unsupportedZone(M));const tr=Locale.fromObject(e);let rr,ir;if(isUndefined(r.year))rr=Settings.now();else{for(const hr of orderedUnits)isUndefined(r[hr])&&(r[hr]=defaultUnitValues[hr]);const lr=hasInvalidGregorianData(r)||hasInvalidTimeData(r);if(lr)return DateTime.invalid(lr);const dr=guessOffsetForZone(M);[rr,ir]=objToTS(r,dr,M)}return new DateTime({ts:rr,zone:M,loc:tr,o:ir})}function diffRelative(r,e,M){const tr=isUndefined(M.round)?!0:M.round,rr=isUndefined(M.rounding)?"trunc":M.rounding,ir=(dr,hr)=>(dr=roundTo(dr,tr||M.calendary?0:2,M.calendary?"round":rr),e.loc.clone(M).relFormatter(M).format(dr,hr)),lr=dr=>M.calendary?e.hasSame(r,dr)?0:e.startOf(dr).diff(r.startOf(dr),dr).get(dr):e.diff(r,dr).get(dr);if(M.unit)return ir(lr(M.unit),M.unit);for(const dr of M.units){const hr=lr(dr);if(Math.abs(hr)>=1)return ir(hr,dr)}return ir(r>e?-0:0,M.units[M.units.length-1])}function lastOpts(r){let e={},M;return r.length>0&&typeof r[r.length-1]=="object"?(e=r[r.length-1],M=Array.from(r).slice(0,r.length-1)):M=Array.from(r),[e,M]}let zoneOffsetTs;const zoneOffsetGuessCache=new Map;class DateTime{constructor(e){const M=e.zone||Settings.defaultZone;let tr=e.invalid||(Number.isNaN(e.ts)?new Invalid("invalid input"):null)||(M.isValid?null:unsupportedZone(M));this.ts=isUndefined(e.ts)?Settings.now():e.ts;let rr=null,ir=null;if(!tr)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(M))[rr,ir]=[e.old.c,e.old.o];else{const dr=isNumber(e.o)&&!e.old?e.o:M.offset(this.ts);rr=tsToObj(this.ts,dr),tr=Number.isNaN(rr.year)?new Invalid("invalid input"):null,rr=tr?null:rr,ir=tr?null:dr}this._zone=M,this.loc=e.loc||Locale.create(),this.invalid=tr,this.weekData=null,this.localWeekData=null,this.c=rr,this.o=ir,this.isLuxonDateTime=!0}static now(){return new DateTime({})}static local(){const[e,M]=lastOpts(arguments),[tr,rr,ir,lr,dr,hr,fr]=M;return quickDT({year:tr,month:rr,day:ir,hour:lr,minute:dr,second:hr,millisecond:fr},e)}static utc(){const[e,M]=lastOpts(arguments),[tr,rr,ir,lr,dr,hr,fr]=M;return e.zone=FixedOffsetZone.utcInstance,quickDT({year:tr,month:rr,day:ir,hour:lr,minute:dr,second:hr,millisecond:fr},e)}static fromJSDate(e,M={}){const tr=isDate(e)?e.valueOf():NaN;if(Number.isNaN(tr))return DateTime.invalid("invalid input");const rr=normalizeZone(M.zone,Settings.defaultZone);return rr.isValid?new DateTime({ts:tr,zone:rr,loc:Locale.fromObject(M)}):DateTime.invalid(unsupportedZone(rr))}static fromMillis(e,M={}){if(isNumber(e))return e<-MAX_DATE||e>MAX_DATE?DateTime.invalid("Timestamp out of range"):new DateTime({ts:e,zone:normalizeZone(M.zone,Settings.defaultZone),loc:Locale.fromObject(M)});throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,M={}){if(isNumber(e))return new DateTime({ts:e*1e3,zone:normalizeZone(M.zone,Settings.defaultZone),loc:Locale.fromObject(M)});throw new InvalidArgumentError("fromSeconds requires a numerical input")}static fromObject(e,M={}){e=e||{};const tr=normalizeZone(M.zone,Settings.defaultZone);if(!tr.isValid)return DateTime.invalid(unsupportedZone(tr));const rr=Locale.fromObject(M),ir=normalizeObject(e,normalizeUnitWithLocalWeeks),{minDaysInFirstWeek:lr,startOfWeek:dr}=usesLocalWeekValues(ir,rr),hr=Settings.now(),fr=isUndefined(M.specificOffset)?tr.offset(hr):M.specificOffset,mr=!isUndefined(ir.ordinal),_r=!isUndefined(ir.year),gr=!isUndefined(ir.month)||!isUndefined(ir.day),wr=_r||gr,yr=ir.weekYear||ir.weekNumber;if((wr||mr)&&yr)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(gr&&mr)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");const br=yr||ir.weekday&&!wr;let Mr,vr,Sr=tsToObj(hr,fr);br?(Mr=orderedWeekUnits,vr=defaultWeekUnitValues,Sr=gregorianToWeek(Sr,lr,dr)):mr?(Mr=orderedOrdinalUnits,vr=defaultOrdinalUnitValues,Sr=gregorianToOrdinal(Sr)):(Mr=orderedUnits,vr=defaultUnitValues);let xr=!1;for(const Jr of Mr){const $n=ir[Jr];isUndefined($n)?xr?ir[Jr]=vr[Jr]:ir[Jr]=Sr[Jr]:xr=!0}const Ar=br?hasInvalidWeekData(ir,lr,dr):mr?hasInvalidOrdinalData(ir):hasInvalidGregorianData(ir),Dr=Ar||hasInvalidTimeData(ir);if(Dr)return DateTime.invalid(Dr);const Ir=br?weekToGregorian(ir,lr,dr):mr?ordinalToGregorian(ir):ir,[kr,Or]=objToTS(Ir,fr,tr),Fr=new DateTime({ts:kr,zone:tr,o:Or,loc:rr});return ir.weekday&&wr&&e.weekday!==Fr.weekday?DateTime.invalid("mismatched weekday",`you can't specify both a weekday of ${ir.weekday} and a date of ${Fr.toISO()}`):Fr.isValid?Fr:DateTime.invalid(Fr.invalid)}static fromISO(e,M={}){const[tr,rr]=parseISODate(e);return parseDataToDateTime(tr,rr,M,"ISO 8601",e)}static fromRFC2822(e,M={}){const[tr,rr]=parseRFC2822Date(e);return parseDataToDateTime(tr,rr,M,"RFC 2822",e)}static fromHTTP(e,M={}){const[tr,rr]=parseHTTPDate(e);return parseDataToDateTime(tr,rr,M,"HTTP",M)}static fromFormat(e,M,tr={}){if(isUndefined(e)||isUndefined(M))throw new InvalidArgumentError("fromFormat requires an input string and a format");const{locale:rr=null,numberingSystem:ir=null}=tr,lr=Locale.fromOpts({locale:rr,numberingSystem:ir,defaultToEN:!0}),[dr,hr,fr,mr]=parseFromTokens(lr,e,M);return mr?DateTime.invalid(mr):parseDataToDateTime(dr,hr,tr,`format ${M}`,e,fr)}static fromString(e,M,tr={}){return DateTime.fromFormat(e,M,tr)}static fromSQL(e,M={}){const[tr,rr]=parseSQL(e);return parseDataToDateTime(tr,rr,M,"SQL",e)}static invalid(e,M=null){if(!e)throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");const tr=e instanceof Invalid?e:new Invalid(e,M);if(Settings.throwOnInvalid)throw new InvalidDateTimeError(tr);return new DateTime({invalid:tr})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,M={}){const tr=formatOptsToTokens(e,Locale.fromObject(M));return tr?tr.map(rr=>rr?rr.val:null).join(""):null}static expandFormat(e,M={}){return expandMacroTokens(Formatter.parseFormat(e),Locale.fromObject(M)).map(rr=>rr.val).join("")}static resetCache(){zoneOffsetTs=void 0,zoneOffsetGuessCache.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?possiblyCachedWeekData(this).weekYear:NaN}get weekNumber(){return this.isValid?possiblyCachedWeekData(this).weekNumber:NaN}get weekday(){return this.isValid?possiblyCachedWeekData(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?possiblyCachedLocalWeekData(this).weekday:NaN}get localWeekNumber(){return this.isValid?possiblyCachedLocalWeekData(this).weekNumber:NaN}get localWeekYear(){return this.isValid?possiblyCachedLocalWeekData(this).weekYear:NaN}get ordinal(){return this.isValid?gregorianToOrdinal(this.c).ordinal:NaN}get monthShort(){return this.isValid?Info.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Info.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Info.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Info.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,M=6e4,tr=objToLocalTS(this.c),rr=this.zone.offset(tr-e),ir=this.zone.offset(tr+e),lr=this.zone.offset(tr-rr*M),dr=this.zone.offset(tr-ir*M);if(lr===dr)return[this];const hr=tr-lr*M,fr=tr-dr*M,mr=tsToObj(hr,lr),_r=tsToObj(fr,dr);return mr.hour===_r.hour&&mr.minute===_r.minute&&mr.second===_r.second&&mr.millisecond===_r.millisecond?[clone(this,{ts:hr}),clone(this,{ts:fr})]:[this]}get isInLeapYear(){return isLeapYear(this.year)}get daysInMonth(){return daysInMonth(this.year,this.month)}get daysInYear(){return this.isValid?daysInYear(this.year):NaN}get weeksInWeekYear(){return this.isValid?weeksInWeekYear(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?weeksInWeekYear(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:M,numberingSystem:tr,calendar:rr}=Formatter.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:M,numberingSystem:tr,outputCalendar:rr}}toUTC(e=0,M={}){return this.setZone(FixedOffsetZone.instance(e),M)}toLocal(){return this.setZone(Settings.defaultZone)}setZone(e,{keepLocalTime:M=!1,keepCalendarTime:tr=!1}={}){if(e=normalizeZone(e,Settings.defaultZone),e.equals(this.zone))return this;if(e.isValid){let rr=this.ts;if(M||tr){const ir=e.offset(this.ts),lr=this.toObject();[rr]=objToTS(lr,ir,e)}return clone(this,{ts:rr,zone:e})}else return DateTime.invalid(unsupportedZone(e))}reconfigure({locale:e,numberingSystem:M,outputCalendar:tr}={}){const rr=this.loc.clone({locale:e,numberingSystem:M,outputCalendar:tr});return clone(this,{loc:rr})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const M=normalizeObject(e,normalizeUnitWithLocalWeeks),{minDaysInFirstWeek:tr,startOfWeek:rr}=usesLocalWeekValues(M,this.loc),ir=!isUndefined(M.weekYear)||!isUndefined(M.weekNumber)||!isUndefined(M.weekday),lr=!isUndefined(M.ordinal),dr=!isUndefined(M.year),hr=!isUndefined(M.month)||!isUndefined(M.day),fr=dr||hr,mr=M.weekYear||M.weekNumber;if((fr||lr)&&mr)throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(hr&&lr)throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");let _r;ir?_r=weekToGregorian({...gregorianToWeek(this.c,tr,rr),...M},tr,rr):isUndefined(M.ordinal)?(_r={...this.toObject(),...M},isUndefined(M.day)&&(_r.day=Math.min(daysInMonth(_r.year,_r.month),_r.day))):_r=ordinalToGregorian({...gregorianToOrdinal(this.c),...M});const[gr,wr]=objToTS(_r,this.o,this.zone);return clone(this,{ts:gr,o:wr})}plus(e){if(!this.isValid)return this;const M=Duration.fromDurationLike(e);return clone(this,adjustTime(this,M))}minus(e){if(!this.isValid)return this;const M=Duration.fromDurationLike(e).negate();return clone(this,adjustTime(this,M))}startOf(e,{useLocaleWeeks:M=!1}={}){if(!this.isValid)return this;const tr={},rr=Duration.normalizeUnit(e);switch(rr){case"years":tr.month=1;case"quarters":case"months":tr.day=1;case"weeks":case"days":tr.hour=0;case"hours":tr.minute=0;case"minutes":tr.second=0;case"seconds":tr.millisecond=0;break}if(rr==="weeks")if(M){const ir=this.loc.getStartOfWeek(),{weekday:lr}=this;lr<ir&&(tr.weekNumber=this.weekNumber-1),tr.weekday=ir}else tr.weekday=1;if(rr==="quarters"){const ir=Math.ceil(this.month/3);tr.month=(ir-1)*3+1}return this.set(tr)}endOf(e,M){return this.isValid?this.plus({[e]:1}).startOf(e,M).minus(1):this}toFormat(e,M={}){return this.isValid?Formatter.create(this.loc.redefaultToEN(M)).formatDateTimeFromString(this,e):INVALID}toLocaleString(e=DATE_SHORT,M={}){return this.isValid?Formatter.create(this.loc.clone(M),e).formatDateTime(this):INVALID}toLocaleParts(e={}){return this.isValid?Formatter.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:M=!1,suppressMilliseconds:tr=!1,includeOffset:rr=!0,extendedZone:ir=!1,precision:lr="milliseconds"}={}){if(!this.isValid)return null;lr=normalizeUnit(lr);const dr=e==="extended";let hr=toISODate(this,dr,lr);return orderedUnits.indexOf(lr)>=3&&(hr+="T"),hr+=toISOTime(this,dr,M,tr,rr,ir,lr),hr}toISODate({format:e="extended",precision:M="day"}={}){return this.isValid?toISODate(this,e==="extended",normalizeUnit(M)):null}toISOWeekDate(){return toTechFormat(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:M=!1,includeOffset:tr=!0,includePrefix:rr=!1,extendedZone:ir=!1,format:lr="extended",precision:dr="milliseconds"}={}){return this.isValid?(dr=normalizeUnit(dr),(rr&&orderedUnits.indexOf(dr)>=3?"T":"")+toISOTime(this,lr==="extended",M,e,tr,ir,dr)):null}toRFC2822(){return toTechFormat(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return toTechFormat(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?toISODate(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:M=!1,includeOffsetSpace:tr=!0}={}){let rr="HH:mm:ss.SSS";return(M||e)&&(tr&&(rr+=" "),M?rr+="z":e&&(rr+="ZZ")),toTechFormat(this,rr,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():INVALID}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const M={...this.c};return e.includeConfig&&(M.outputCalendar=this.outputCalendar,M.numberingSystem=this.loc.numberingSystem,M.locale=this.loc.locale),M}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,M="milliseconds",tr={}){if(!this.isValid||!e.isValid)return Duration.invalid("created by diffing an invalid DateTime");const rr={locale:this.locale,numberingSystem:this.numberingSystem,...tr},ir=maybeArray(M).map(Duration.normalizeUnit),lr=e.valueOf()>this.valueOf(),dr=lr?this:e,hr=lr?e:this,fr=diff(dr,hr,ir,rr);return lr?fr.negate():fr}diffNow(e="milliseconds",M={}){return this.diff(DateTime.now(),e,M)}until(e){return this.isValid?Interval.fromDateTimes(this,e):this}hasSame(e,M,tr){if(!this.isValid)return!1;const rr=e.valueOf(),ir=this.setZone(e.zone,{keepLocalTime:!0});return ir.startOf(M,tr)<=rr&&rr<=ir.endOf(M,tr)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const M=e.base||DateTime.fromObject({},{zone:this.zone}),tr=e.padding?this<M?-e.padding:e.padding:0;let rr=["years","months","days","hours","minutes","seconds"],ir=e.unit;return Array.isArray(e.unit)&&(rr=e.unit,ir=void 0),diffRelative(M,this.plus(tr),{...e,numeric:"always",units:rr,unit:ir})}toRelativeCalendar(e={}){return this.isValid?diffRelative(e.base||DateTime.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(DateTime.isDateTime))throw new InvalidArgumentError("min requires all arguments be DateTimes");return bestBy(e,M=>M.valueOf(),Math.min)}static max(...e){if(!e.every(DateTime.isDateTime))throw new InvalidArgumentError("max requires all arguments be DateTimes");return bestBy(e,M=>M.valueOf(),Math.max)}static fromFormatExplain(e,M,tr={}){const{locale:rr=null,numberingSystem:ir=null}=tr,lr=Locale.fromOpts({locale:rr,numberingSystem:ir,defaultToEN:!0});return explainFromTokens(lr,e,M)}static fromStringExplain(e,M,tr={}){return DateTime.fromFormatExplain(e,M,tr)}static buildFormatParser(e,M={}){const{locale:tr=null,numberingSystem:rr=null}=M,ir=Locale.fromOpts({locale:tr,numberingSystem:rr,defaultToEN:!0});return new TokenParser(ir,e)}static fromFormatParser(e,M,tr={}){if(isUndefined(e)||isUndefined(M))throw new InvalidArgumentError("fromFormatParser requires an input string and a format parser");const{locale:rr=null,numberingSystem:ir=null}=tr,lr=Locale.fromOpts({locale:rr,numberingSystem:ir,defaultToEN:!0});if(!lr.equals(M.locale))throw new InvalidArgumentError(`fromFormatParser called with a locale of ${lr}, but the format parser was created for ${M.locale}`);const{result:dr,zone:hr,specificOffset:fr,invalidReason:mr}=M.explainFromTokens(e);return mr?DateTime.invalid(mr):parseDataToDateTime(dr,hr,tr,`format ${M.format}`,e,fr)}static get DATE_SHORT(){return DATE_SHORT}static get DATE_MED(){return DATE_MED}static get DATE_MED_WITH_WEEKDAY(){return DATE_MED_WITH_WEEKDAY}static get DATE_FULL(){return DATE_FULL}static get DATE_HUGE(){return DATE_HUGE}static get TIME_SIMPLE(){return TIME_SIMPLE}static get TIME_WITH_SECONDS(){return TIME_WITH_SECONDS}static get TIME_WITH_SHORT_OFFSET(){return TIME_WITH_SHORT_OFFSET}static get TIME_WITH_LONG_OFFSET(){return TIME_WITH_LONG_OFFSET}static get TIME_24_SIMPLE(){return TIME_24_SIMPLE}static get TIME_24_WITH_SECONDS(){return TIME_24_WITH_SECONDS}static get TIME_24_WITH_SHORT_OFFSET(){return TIME_24_WITH_SHORT_OFFSET}static get TIME_24_WITH_LONG_OFFSET(){return TIME_24_WITH_LONG_OFFSET}static get DATETIME_SHORT(){return DATETIME_SHORT}static get DATETIME_SHORT_WITH_SECONDS(){return DATETIME_SHORT_WITH_SECONDS}static get DATETIME_MED(){return DATETIME_MED}static get DATETIME_MED_WITH_SECONDS(){return DATETIME_MED_WITH_SECONDS}static get DATETIME_MED_WITH_WEEKDAY(){return DATETIME_MED_WITH_WEEKDAY}static get DATETIME_FULL(){return DATETIME_FULL}static get DATETIME_FULL_WITH_SECONDS(){return DATETIME_FULL_WITH_SECONDS}static get DATETIME_HUGE(){return DATETIME_HUGE}static get DATETIME_HUGE_WITH_SECONDS(){return DATETIME_HUGE_WITH_SECONDS}}function friendlyDateTime(r){if(DateTime.isDateTime(r))return r;if(r&&r.valueOf&&isNumber(r.valueOf()))return DateTime.fromJSDate(r);if(r&&typeof r=="object")return DateTime.fromObject(r);throw new InvalidArgumentError(`Unknown datetime argument: ${r}, of type ${typeof r}`)}const getPeriodSeriesArray=r=>{const e=[],M=getPeriodSeries(r);let tr=M.next();for(;tr;)e.push(tr),tr=M.next();return e},getPeriodSeries=r=>({...r,next:_createFactoryFn(r)}),_createFactoryFn=r=>{let e=r.start;return()=>{if(e==null)return null;let M=null;switch(r.granularity){case AnalyticsGranularity.Total:M=_nextTotalPeriod(e,r.end);break;case AnalyticsGranularity.Annual:M=_nextAnnualPeriod(e,r.end);break;case AnalyticsGranularity.SemiAnnual:M=_nextSemiAnnualPeriod(e,r.end);break;case AnalyticsGranularity.Quarterly:M=_nextQuarterlyPeriod(e,r.end);break;case AnalyticsGranularity.Monthly:M=_nextMonthlyPeriod(e,r.end);break;case AnalyticsGranularity.Weekly:M=_nextWeeklyPeriod(e,r.end);break;case AnalyticsGranularity.Daily:M=_nextDailyPeriod(e,r.end);break;case AnalyticsGranularity.Hourly:M=_nextHourlyPeriod(e,r.end)}return M===null?e=null:e=M.end.plus({milliseconds:1}),M}},_nextTotalPeriod=(r,e)=>e<=r?null:{period:"total",start:r,end:e},_nextAnnualPeriod=(r,e)=>{if(e<=r)return null;const M=r.toUTC(),tr=DateTime.utc(M.year,M.month,M.day).plus({years:1});return{period:"annual",start:r,end:tr}},_nextSemiAnnualPeriod=(r,e)=>{if(e<=r)return null;const M=DateTime.utc(r.year,7,1),tr=DateTime.utc(r.year,12,31,23,59,59,999);let rr;return M>r?rr=M:rr=tr,rr>e&&(rr=e),{period:"semiAnnual",start:r,end:rr}},_nextQuarterlyPeriod=(r,e)=>{if(e<=r)return null;let M;const tr=r.toUTC(),rr=tr.month;return rr<3?M=DateTime.utc(tr.year,4,1):rr<6?M=DateTime.utc(tr.year,7,1):rr<9?M=DateTime.utc(tr.year,10,1):M=DateTime.utc(tr.year,12,31,23,59,59,999),M>e&&(M=e),{period:"quarterly",start:r,end:M}},_nextMonthlyPeriod=(r,e)=>{if(e<=r)return null;const M=r.toUTC();let tr=DateTime.utc(M.year,M.month,M.day).plus({months:1}).startOf("month");return tr>e&&(r.hasSame(e,"month")||(tr=e)),{period:"monthly",start:r,end:tr}},_nextWeeklyPeriod=(r,e)=>{if(e<=r)return null;const M=r.toUTC(),tr=DateTime.utc(M.year,M.month,M.day).plus({weeks:1}).startOf("week");return tr>e&&!tr.hasSame(e,"day")?{period:"weekly",start:r,end:e}:{period:"weekly",start:r,end:tr}},_nextDailyPeriod=(r,e)=>{if(e<=r)return null;let tr=r.toUTC().plus({days:1}).startOf("day");return(tr>e||tr.hasSame(e,"day"))&&(tr=e),{period:"daily",start:r,end:tr}},_nextHourlyPeriod=(r,e)=>{if(e<=r)return null;let tr=r.toUTC().plus({hours:1});return tr>e&&r.hour!==e.hour&&(tr=e.toUTC()),{period:"hourly",start:r,end:tr}},getQuarter=r=>Math.floor((r.month-1)/3)+1;class AnalyticsDiscretizer{static discretize(e,M,tr,rr,ir){const lr=this._buildIndex(e,M),dr=getPeriodSeriesArray(this._calculateRange(tr,rr,ir,e)),hr=this._discretizeNode(lr,{},M,dr);return this._groupResultsByPeriod(dr,hr)}static _calculateRange(e,M,tr,rr){let ir=e||null,lr=M||null;if(ir==null||lr==null)for(const dr of rr){ir==null&&(ir=dr.start);const hr=dr.end||dr.start;(lr==null||lr<hr)&&(lr=hr)}if(ir==null||lr==null)throw new Error("Cannot determine query start and/or end.");return{start:ir,end:lr,granularity:tr}}static _groupResultsByPeriod(e,M){const tr={};for(const rr of e){const ir=rr.start.toISO()+"-"+rr.period,lr=AnalyticsDiscretizer._getPeriodString(rr);tr[ir]={period:lr,start:rr.start,end:rr.end,rows:[]}}for(const rr of M)for(const ir of Object.keys(rr.series))tr[ir].rows.push({dimensions:rr.dimensions,metric:rr.metric,unit:rr.unit=="__NULL__"?null:rr.unit,value:rr.series[ir].inc,sum:rr.series[ir].sum});return Object.values(tr)}static _getPeriodString(e){switch(e.period){case"annual":return e.start.year.toString();case"semiAnnual":return`${e.start.year}/${e.start.month<7?"H1":"H2"}`;case"quarterly":return`${e.start.year}/Q${getQuarter(e.start)}`;case"monthly":const M=e.start.toUTC().month,tr=M<10?`0${M}`:`${M}`;return`${e.start.year}/${tr}`;case"weekly":return`${e.start.weekYear}/W${e.start.weekNumber}`;case"daily":const rr=e.start.month,ir=e.start.day,lr=rr<10?`0${rr}`:`${rr}`,dr=ir<10?`0${ir}`:`${ir}`;return`${e.start.year}/${lr}/${dr}`;case"hourly":const hr=e.start.month,fr=e.start.day,mr=e.start.hour,_r=hr<10?`0${hr}`:`${hr}`,gr=fr<10?`0${fr}`:`${fr}`,wr=mr<10?`0${mr}`:`${mr}`;return`${e.start.year}/${_r}/${gr}/${wr}`;default:return e.period}}static _discretizeNode(e,M,tr,rr){const ir=[];if(tr.length>0){const lr=tr[0];Object.keys(e).forEach((dr,hr,fr)=>{const mr={...M};mr[lr]=dr,ir.push(...this._discretizeNode(e[dr],mr,tr.slice(1),rr))})}else Object.keys(e).forEach(lr=>{ir.push(...this._discretizeLeaf(e[lr],rr,lr,M))});return ir}static _discretizeLeaf(e,M,tr,rr){const ir=[];return Object.keys(e).forEach(lr=>{const dr={};Object.keys(rr).forEach(hr=>{dr[hr]={path:e[lr][0].dimensions[hr],icon:e[lr][0].dimensions.icon,label:e[lr][0].dimensions.label,description:e[lr][0].dimensions.description}}),ir.push({unit:lr,metric:tr,dimensions:dr,series:this._discretizeSeries(e[lr],M)})}),ir}static _discretizeSeries(e,M){const tr={};for(const rr of e){let ir=this._getValue(rr,M[0].start);for(const lr of M){const dr=this._getValue(rr,lr.end),hr=`${lr.start.toISO()}-${lr.period}`;tr[hr]?(tr[hr].inc+=dr-ir,tr[hr].sum+=dr):tr[hr]={inc:dr-ir,sum:dr},ir=dr}}return tr}static _getValue(e,M){switch(e.fn){case"Single":return this._getSingleValue(e,M);case"DssVest":return this._getVestValue(e,M);default:return 0}}static _getSingleValue(e,M){return M>=e.start?e.value:0}static _getVestValue(e,M){const tr=M,rr=e.start,ir=e.end,lr=e.params?.cliff?DateTime.fromISO(e.params.cliff):null;if(tr<rr||lr&&tr<lr)return 0;if(ir&&tr>=ir)return e.value;const dr=Interval.fromDateTimes(rr,tr),hr=Interval.fromDateTimes(rr,ir||tr);return dr.length()/hr.length()*e.value}static _buildIndex(e,M){const tr={},rr={},ir=M[0]||"";for(const lr of e){const dr=lr.dimensions[ir];rr[dr]===void 0&&(rr[dr]=[]),rr[dr].push(lr)}if(M.length>1){const lr=M.slice(1);Object.keys(rr).forEach(dr=>{tr[dr]=this._buildIndex(rr[dr],lr)})}else Object.keys(rr).forEach(lr=>{tr[lr]=this._buildMetricsIndex(rr[lr])});return tr}static _buildMetricsIndex(e){const M={},tr={};for(const rr of e){const ir=rr.metric;tr[ir]===void 0&&(tr[ir]=[]),tr[ir].push(rr)}return Object.keys(tr).forEach(rr=>M[rr]=this._buildUnitIndex(tr[rr])),M}static _buildUnitIndex(e){const M={};for(const tr of e){const rr=tr.unit||"__NULL__";M[rr]===void 0&&(M[rr]=[]),M[rr].push(tr)}return M}}class AnalyticsQueryEngine{_analyticsStore;_profiler;constructor(e,M){this._analyticsStore=e,this._profiler=M??new PassthroughAnalyticsProfiler}async executeCompound(e){let M;const tr={start:e.start,end:e.end,granularity:e.granularity,lod:e.lod,select:e.select,metrics:e.expression.inputs.metrics,currency:e.expression.inputs.currency},rr={start:e.start,end:e.end,granularity:e.granularity,lod:{priceData:1},select:{priceData:[AnalyticsPath.fromString("atlas")]},metrics:[e.expression.operand.metric],currency:e.expression.operand.currency},ir=await this.execute(tr),lr=await this.execute(rr);return[CompoundOperator.VectorAdd,CompoundOperator.VectorSubtract].includes(e.expression.operator)?M=await this._profiler.record("ApplyVectorOperator",async()=>await this._applyVectorOperator(ir,lr,e.expression.operator,e.expression.resultCurrency)):M=await this._profiler.record("ApplyScalarOperator",async()=>await this._applyScalarOperator(ir,lr,e.expression.operator,e.expression.operand.useSum,e.expression.resultCurrency)),M}async execute(e){const M=await this._executeSeriesQuery(e),tr=this._profiler.recordSync("ApplyLODs",()=>this._applyLods(M,e.lod)),rr=Object.keys(e.select);return this._profiler.recordSync("Discretize",()=>tr.length<1?[]:AnalyticsDiscretizer.discretize(tr,rr,e.start,e.end,e.granularity))}async executeMultiCurrency(e,M){const tr={...e,currency:M.targetCurrency??e.currency};let rr=await this.execute(tr);for(const ir of M.conversions){const lr={start:e.start,end:e.end,granularity:e.granularity,lod:e.lod,select:e.select,expression:{inputs:{metrics:tr.metrics,currency:ir.currency},operator:CompoundOperator.ScalarMultiply,operand:{metric:ir.metric,currency:M.targetCurrency,useSum:!0},resultCurrency:M.targetCurrency}},dr=await this.executeCompound(lr);rr=await this._applyVectorOperator(rr,dr,CompoundOperator.VectorAdd,M.targetCurrency)}return rr}async _applyVectorOperator(e,M,tr,rr){if([CompoundOperator.ScalarMultiply,CompoundOperator.ScalarDivide].includes(tr))throw new Error("Invalid operator for vector operation");return M}async _applyScalarOperator(e,M,tr,rr,ir){if([CompoundOperator.VectorAdd,CompoundOperator.VectorSubtract].includes(tr))throw new Error("Invalid operator for scalar operation");const lr=[],dr={},hr=rr?"sum":"value";for(const fr of M)fr.rows.length>0&&(dr[fr.period]=fr.rows[0][hr]);for(const fr of e){const mr={period:fr.period,start:fr.start,end:fr.end,rows:fr.rows.map(_r=>({dimensions:_r.dimensions,metric:_r.metric,unit:ir?ir.toString():_r.unit,value:this._calculateOutputValue(_r.value,tr,dr[fr.period]),sum:-1}))};lr.push(mr)}return lr}_calculateOutputValue(e,M,tr){switch(M){case CompoundOperator.VectorAdd:return e+tr;case CompoundOperator.VectorSubtract:return e-tr;case CompoundOperator.ScalarMultiply:return e*tr;case CompoundOperator.ScalarDivide:return e/tr}}async _executeSeriesQuery(e){const M={start:e.start,end:e.end,select:e.select,metrics:e.metrics,currency:e.currency};return await this._analyticsStore.getMatchingSeries(M)}_applyLods(e,M){return e.map(tr=>({...tr,dimensions:this._applyDimensionsLods(tr.dimensions,M)}))}_applyDimensionsLods(e,M){const tr={};for(const[rr,ir]of Object.entries(M))ir!==null&&e[rr]&&(tr[rr]=e[rr].path.applyLod(ir).toString(),tr.icon=e[rr].icon.toString(),tr.label=e[rr].label.toString(),tr.description=e[rr].description.toString());return tr}async getDimensions(){return await this._analyticsStore.getDimensions()}}class NotificationError extends Error{innerErrors;constructor(e){super(e.map(M=>M.message).join(`
96
+ `)),this.name="NotificationError",this.innerErrors=e}}class AnalyticsSubscriptionManager{_subscriptions=new Map;subscribeToPath(e,M){const tr=this.normalizePath(e.toString("/"));return this._subscriptions.has(tr)||this._subscriptions.set(tr,new Set),this._subscriptions.get(tr).add(M),()=>{const rr=this._subscriptions.get(tr);rr&&(rr.delete(M),rr.size===0&&this._subscriptions.delete(tr))}}notifySubscribers(e){if(e.length===0||this._subscriptions.size===0)return;const M=[];for(const tr of e){const rr=this.normalizePath(tr.toString("/")),ir=this.getPathPrefixes(rr),lr=[];ir.filter(dr=>this._subscriptions.has(dr)).forEach(dr=>{lr.push({prefix:dr,callbacks:this._subscriptions.get(dr)})});for(const[dr,hr]of this._subscriptions.entries())ir.includes(dr)||this.pathMatchesWildcardPattern(rr,dr)&&lr.push({prefix:dr,callbacks:hr});if(lr.length!==0)for(const{callbacks:dr}of lr)for(const hr of dr)try{hr(tr)}catch(fr){M.push(fr)}}if(M.length>0)throw new NotificationError(M)}normalizePath(e){return"/"+e.split("/").filter(rr=>rr.length>0).join("/")}pathMatchesWildcardPattern(e,M){if(M.includes("*")){const tr=e.split("/").filter(ir=>ir.length>0),rr=M.split("/").filter(ir=>ir.length>0);if(rr.length>tr.length)return!1;for(let ir=0;ir<rr.length;ir++){const lr=rr[ir],dr=tr[ir];if(!(lr==="*"||lr.startsWith("*:"))&&lr!==dr)return!1}return!0}return e===M||e.startsWith(M+"/")}getPathPrefixes(e){const M=e.split("/").filter(ir=>ir.length>0),tr=[];let rr="";for(const ir of M)rr=rr?`${rr}/${ir}`:`/${ir}`,tr.push(rr);return tr.length===0&&e==="/"&&tr.push("/"),tr}}const index=Object.freeze(Object.defineProperty({__proto__:null,get AnalyticsGranularity(){return AnalyticsGranularity},AnalyticsPath,AnalyticsPathSegment,AnalyticsQueryEngine,get AnalyticsSerializerTypes(){return AnalyticsSerializerTypes},AnalyticsSubscriptionManager,NotificationError,PassthroughAnalyticsProfiler},Symbol.toStringTag,{value:"Module"}));function useDispatch(r){function e(M,tr,rr){dispatchActions(M,r,tr,rr).catch(logger$1.error)}return[r,e]}function addPromiseState(r){if("status"in r)return r;const e=r;return e.status="pending",e.then(M=>{e.status="fulfilled",e.value=M},M=>{throw e.status="rejected",e.reason=M,M}),e}function readPromiseState(r){return"status"in r?r:{status:"pending"}}function makePHEventFunctions(r){const e=`ph:set${capitalCase(r)}`,M=`ph:${r}Updated`;function tr(mr){const _r=new CustomEvent(e,{detail:{[r]:mr}});window.dispatchEvent(_r)}function rr(){const mr=new CustomEvent(M);window.dispatchEvent(mr)}function ir(mr){const _r=mr.detail[r];if(!window.ph)throw new Error("ph global store is not defined");window.ph[r]=_r,rr()}function lr(){window.addEventListener(e,ir)}function dr(mr){return window.addEventListener(M,mr),()=>{window.removeEventListener(M,mr)}}function hr(){if(!window.ph)throw new Error("ph global store is not defined");return window.ph[r]}function fr(){return reactExports.useSyncExternalStore(dr,hr)}return{useValue:fr,setValue:tr,addEventHandler:lr}}const documentEventFunctions=makePHEventFunctions("documentCache"),useDocumentCache=documentEventFunctions.useValue,setDocumentCache=documentEventFunctions.setValue,addDocumentCacheEventHandler=documentEventFunctions.addEventHandler;function useDocument(r){const e=useDocumentCache(),M=reactExports.useSyncExternalStore(tr=>r&&e?e.subscribe(r,tr):()=>{},()=>r?e?.get(r):void 0);return M?reactExports.use(M):void 0}function useDocumentById(r){const e=useDocument(r),[,M]=useDispatch(e);return[e,M]}const DEFAULT_DRIVE_EDITOR_ID="powerhouse/generic-drive-explorer",COMMON_PACKAGE_ID="powerhouse/common",isExternalControlsEnabledEventFunctions=makePHEventFunctions("isExternalControlsEnabled"),setIsExternalControlsEnabled=isExternalControlsEnabledEventFunctions.setValue,addIsExternalControlsEnabledEventHandler=isExternalControlsEnabledEventFunctions.addEventHandler,isDragAndDropEnabledEventFunctions=makePHEventFunctions("isDragAndDropEnabled"),setIsDragAndDropEnabled=isDragAndDropEnabledEventFunctions.setValue,useIsDragAndDropEnabled=isDragAndDropEnabledEventFunctions.useValue,addIsDragAndDropEnabledEventHandler=isDragAndDropEnabledEventFunctions.addEventHandler,allowedDocumentTypesEventFunctions=makePHEventFunctions("allowedDocumentTypes"),setAllowedDocumentTypes=allowedDocumentTypesEventFunctions.setValue;function useAllowedDocumentTypes(){return allowedDocumentTypesEventFunctions.useValue()}const addAllowedDocumentTypesEventHandler=allowedDocumentTypesEventFunctions.addEventHandler,phDriveEditorConfigSetters={allowedDocumentTypes:setAllowedDocumentTypes,isDragAndDropEnabled:setIsDragAndDropEnabled},phDocumentEditorConfigSetters={isExternalControlsEnabled:setIsExternalControlsEnabled},vetraPackageEventFunctions=makePHEventFunctions("vetraPackages"),useVetraPackages=vetraPackageEventFunctions.useValue,addVetraPackagesEventHandler=vetraPackageEventFunctions.addEventHandler;function setVetraPackages(r=[]){vetraPackageEventFunctions.setValue(r);const e=r.flatMap(M=>M.modules.documentModelModules).filter(M=>M!==void 0);if(e.length>0)try{window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry.registerModules(...e)}catch(M){if(DuplicateModuleError.isError(M))return;throw M}}function useDocumentModelModules(){return useVetraPackages()?.flatMap(e=>e.modules.documentModelModules||[])}function useDocumentModelModuleById(r){return useDocumentModelModules()?.find(M=>M.id===r)}function sortNodesByName(r){return r.toSorted((e,M)=>e.name.localeCompare(M.name))}function isFileNodeKind(r){return r?r.kind.toUpperCase()==="FILE":!1}function isFolderNodeKind(r){return r?r.kind.toUpperCase()==="FOLDER":!1}let base64$4;typeof window<"u"?window.btoa?base64$4=function(r){return btoa(unescape(encodeURIComponent(r)))}:base64$4=function(r){const e=unescape(encodeURIComponent(r+""));let M="";for(let tr,rr,ir=0,lr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.charAt(ir|0)||(lr="=",ir%1);M+=lr.charAt(63&tr>>8-ir%1*8)){if(rr=e.charCodeAt(ir+=3/4),rr>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");tr=tr<<8|rr}return M}:base64$4=function(r){return Buffer.from(r).toString("base64")};function slug(r,e){let M=slugify(r,e);return(e&&e.fallback!==void 0?e.fallback:slug.defaults.fallback)===!0&&M===""&&(M=slugify(base64$4(r),e)),M}const locales={bg:{Й:"Y",й:"y",X:"H",x:"h",Ц:"Ts",ц:"ts",Щ:"Sht",щ:"sht",Ъ:"A",ъ:"a",Ь:"Y",ь:"y"},de:{Ä:"AE",ä:"ae",Ö:"OE",ö:"oe",Ü:"UE",ü:"ue"},sr:{đ:"dj",Đ:"DJ"},uk:{И:"Y",и:"y",Й:"Y",й:"y",Ц:"Ts",ц:"ts",Х:"Kh",х:"kh",Щ:"Shch",щ:"shch",Г:"H",г:"h"}};let defaultLocale={};function slugify(r,e){if(typeof r!="string")throw new Error("slug() requires a string argument, received "+typeof r);if(!r.isWellFormed())throw new Error("slug() received a malformed string with lone surrogates");typeof e=="string"&&(e={replacement:e}),e=e?Object.assign({},e):{},e.mode=e.mode||slug.defaults.mode;const M=slug.defaults.modes[e.mode],tr=["replacement","multicharmap","charmap","remove","lower","trim"];for(let hr,fr=0,mr=tr.length;fr<mr;fr++)hr=tr[fr],e[hr]=hr in e?e[hr]:M[hr];const rr=locales[e.locale]||defaultLocale;let ir=[];for(const hr in e.multicharmap){if(!Object.prototype.hasOwnProperty.call(e.multicharmap,hr))continue;const fr=hr.length;ir.indexOf(fr)===-1&&ir.push(fr)}ir=ir.sort(function(hr,fr){return fr-hr});const lr=e.mode==="rfc3986"?/[^\w\s\-.~]/:/[^A-Za-z0-9\s]/;let dr="";for(let hr,fr=0,mr=r.length;fr<mr;fr++){hr=r[fr];let _r=!1;for(let gr=0;gr<ir.length;gr++){const wr=ir[gr],yr=r.substr(fr,wr);if(e.multicharmap[yr]){fr+=wr-1,hr=e.multicharmap[yr],_r=!0;break}}_r||(rr[hr]?hr=rr[hr]:e.charmap[hr]?hr=e.charmap[hr].replace(e.replacement," "):hr.includes(e.replacement)?hr=hr.replace(e.replacement," "):hr=hr.replace(lr,"")),dr+=hr}return e.remove&&(dr=dr.replace(e.remove,"")),e.trim&&(dr=dr.trim()),dr=dr.replace(/\s+/g,e.replacement),e.lower&&(dr=dr.toLowerCase()),dr}const initialMulticharmap={फ़:"Fi",ग़:"Ghi",ख़:"Khi",क़:"Qi",ड़:"ugDha",ढ़:"ugDhha",य़:"Yi",ज़:"Za",בִי:"i",בֵ:"e",בֵי:"e",בֶ:"e",בַ:"a",בָ:"a",בֹ:"o",וֹ:"o",בֻ:"u",וּ:"u",בּ:"b",כּ:"k",ךּ:"k",פּ:"p",שׁ:"sh",שׂ:"s",בְ:"e",חֱ:"e",חֲ:"a",חֳ:"o",בִ:"i"},initialCharmap={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",Æ:"AE",Ç:"C",È:"E",É:"E",Ê:"E",Ë:"E",Ì:"I",Í:"I",Î:"I",Ï:"I",Ð:"D",Ñ:"N",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ő:"O",Ø:"O",Ō:"O",Ù:"U",Ú:"U",Û:"U",Ü:"U",Ű:"U",Ý:"Y",Þ:"TH",ß:"ss",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",æ:"ae",ç:"c",è:"e",é:"e",ê:"e",ë:"e",ì:"i",í:"i",î:"i",ï:"i",ð:"d",ñ:"n",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ő:"o",ø:"o",ō:"o",Œ:"OE",œ:"oe",ù:"u",ú:"u",û:"u",ü:"u",ű:"u",ý:"y",þ:"th",ÿ:"y","ẞ":"SS",α:"a",β:"b",γ:"g",δ:"d",ε:"e",ζ:"z",η:"h",θ:"th",ι:"i",κ:"k",λ:"l",μ:"m",ν:"n",ξ:"3",ο:"o",π:"p",ρ:"r",σ:"s",τ:"t",υ:"y",φ:"f",χ:"x",ψ:"ps",ω:"w",ά:"a",έ:"e",ί:"i",ό:"o",ύ:"y",ή:"h",ώ:"w",ς:"s",ϊ:"i",ΰ:"y",ϋ:"y",ΐ:"i",Α:"A",Β:"B",Γ:"G",Δ:"D",Ε:"E",Ζ:"Z",Η:"H",Θ:"Th",Ι:"I",Κ:"K",Λ:"L",Μ:"M",Ν:"N",Ξ:"3",Ο:"O",Π:"P",Ρ:"R",Σ:"S",Τ:"T",Υ:"Y",Φ:"F",Χ:"X",Ψ:"PS",Ω:"W",Ά:"A",Έ:"E",Ί:"I",Ό:"O",Ύ:"Y",Ή:"H",Ώ:"W",Ϊ:"I",Ϋ:"Y",ş:"s",Ş:"S",ı:"i",İ:"I",ğ:"g",Ğ:"G",а:"a",б:"b",в:"v",г:"g",д:"d",е:"e",ё:"yo",ж:"zh",з:"z",и:"i",й:"j",к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ф:"f",х:"h",ц:"c",ч:"ch",ш:"sh",щ:"sh",ъ:"u",ы:"y",ь:"",э:"e",ю:"yu",я:"ya",А:"A",Б:"B",В:"V",Г:"G",Д:"D",Е:"E",Ё:"Yo",Ж:"Zh",З:"Z",И:"I",Й:"J",К:"K",Л:"L",М:"M",Н:"N",О:"O",П:"P",Р:"R",С:"S",Т:"T",У:"U",Ф:"F",Х:"H",Ц:"C",Ч:"Ch",Ш:"Sh",Щ:"Sh",Ъ:"U",Ы:"Y",Ь:"",Э:"E",Ю:"Yu",Я:"Ya",Є:"Ye",І:"I",Ї:"Yi",Ґ:"G",є:"ye",і:"i",ї:"yi",ґ:"g",č:"c",ď:"d",ě:"e",ň:"n",ř:"r",š:"s",ť:"t",ů:"u",ž:"z",Č:"C",Ď:"D",Ě:"E",Ň:"N",Ř:"R",Š:"S",Ť:"T",Ů:"U",Ž:"Z",ľ:"l",ĺ:"l",ŕ:"r",Ľ:"L",Ĺ:"L",Ŕ:"R",ą:"a",ć:"c",ę:"e",ł:"l",ń:"n",ś:"s",ź:"z",ż:"z",Ą:"A",Ć:"C",Ę:"E",Ł:"L",Ń:"N",Ś:"S",Ź:"Z",Ż:"Z",ā:"a",ē:"e",ģ:"g",ī:"i",ķ:"k",ļ:"l",ņ:"n",ū:"u",Ā:"A",Ē:"E",Ģ:"G",Ī:"I",Ķ:"K",Ļ:"L",Ņ:"N",Ū:"U",أ:"a",إ:"i",ب:"b",ت:"t",ث:"th",ج:"g",ح:"h",خ:"kh",د:"d",ذ:"th",ر:"r",ز:"z",س:"s",ش:"sh",ص:"s",ض:"d",ط:"t",ظ:"th",ع:"aa",غ:"gh",ف:"f",ق:"k",ك:"k",ل:"l",م:"m",ن:"n",ه:"h",و:"o",ي:"y",ء:"aa",ة:"a",آ:"a",ا:"a",پ:"p",ژ:"zh",گ:"g",چ:"ch",ک:"k",ی:"i",ė:"e",į:"i",ų:"u",Ė:"E",Į:"I",Ų:"U",ț:"t",Ț:"T",ţ:"t",Ţ:"T",ș:"s",Ș:"S",ă:"a",Ă:"A",Ạ:"A",Ả:"A",Ầ:"A",Ấ:"A",Ậ:"A",Ẩ:"A",Ẫ:"A",Ằ:"A",Ắ:"A",Ặ:"A",Ẳ:"A",Ẵ:"A",Ẹ:"E",Ẻ:"E",Ẽ:"E",Ề:"E",Ế:"E",Ệ:"E",Ể:"E",Ễ:"E",Ị:"I",Ỉ:"I",Ĩ:"I",Ọ:"O",Ỏ:"O",Ồ:"O",Ố:"O",Ộ:"O",Ổ:"O",Ỗ:"O",Ơ:"O",Ờ:"O",Ớ:"O",Ợ:"O",Ở:"O",Ỡ:"O",Ụ:"U",Ủ:"U",Ũ:"U",Ư:"U",Ừ:"U",Ứ:"U",Ự:"U",Ử:"U",Ữ:"U",Ỳ:"Y",Ỵ:"Y",Ỷ:"Y",Ỹ:"Y",Đ:"D",ạ:"a",ả:"a",ầ:"a",ấ:"a",ậ:"a",ẩ:"a",ẫ:"a",ằ:"a",ắ:"a",ặ:"a",ẳ:"a",ẵ:"a",ẹ:"e",ẻ:"e",ẽ:"e",ề:"e",ế:"e",ệ:"e",ể:"e",ễ:"e",ị:"i",ỉ:"i",ĩ:"i",ọ:"o",ỏ:"o",ồ:"o",ố:"o",ộ:"o",ổ:"o",ỗ:"o",ơ:"o",ờ:"o",ớ:"o",ợ:"o",ở:"o",ỡ:"o",ụ:"u",ủ:"u",ũ:"u",ư:"u",ừ:"u",ứ:"u",ự:"u",ử:"u",ữ:"u",ỳ:"y",ỵ:"y",ỷ:"y",ỹ:"y",đ:"d",Ә:"AE",ә:"ae",Ғ:"GH",ғ:"gh",Қ:"KH",қ:"kh",Ң:"NG",ң:"ng",Ү:"UE",ү:"ue",Ұ:"U",ұ:"u",Һ:"H",һ:"h",Ө:"OE",ө:"oe",ђ:"dj",ј:"j",љ:"lj",њ:"nj",ћ:"c",џ:"dz",Ђ:"Dj",Ј:"j",Љ:"Lj",Њ:"Nj",Ћ:"C",Џ:"Dz",nj:"nj",lj:"lj",Nj:"NJ",Lj:"LJ",अ:"a",आ:"aa",ए:"e",ई:"ii",ऍ:"ei",ऎ:"ae",ऐ:"ai",इ:"i",ओ:"o",ऑ:"oi",ऒ:"oii",ऊ:"uu",औ:"ou",उ:"u",ब:"B",भ:"Bha",च:"Ca",छ:"Chha",ड:"Da",ढ:"Dha",फ:"Fa",ग:"Ga",घ:"Gha",ग़:"Ghi",ह:"Ha",ज:"Ja",झ:"Jha",क:"Ka",ख:"Kha",ख़:"Khi",ल:"L",ळ:"Li",ऌ:"Li",ऴ:"Lii",ॡ:"Lii",म:"Ma",न:"Na",ङ:"Na",ञ:"Nia",ण:"Nae",ऩ:"Ni",ॐ:"oms",प:"Pa",क़:"Qi",र:"Ra",ऋ:"Ri",ॠ:"Ri",ऱ:"Ri",स:"Sa",श:"Sha",ष:"Shha",ट:"Ta",त:"Ta",ठ:"Tha",द:"Tha",थ:"Tha",ध:"Thha",ड़:"ugDha",ढ़:"ugDhha",व:"Va",य:"Ya",य़:"Yi",ज़:"Za",ə:"e",Ə:"E",ა:"a",ბ:"b",გ:"g",დ:"d",ე:"e",ვ:"v",ზ:"z",თ:"t",ი:"i",კ:"k",ლ:"l",მ:"m",ნ:"n",ო:"o",პ:"p",ჟ:"zh",რ:"r",ს:"s",ტ:"t",უ:"u",ფ:"p",ქ:"k",ღ:"gh",ყ:"q",შ:"sh",ჩ:"ch",ც:"ts",ძ:"dz",წ:"ts",ჭ:"ch",ხ:"kh",ჯ:"j",ჰ:"h",ב:"v",גּ:"g",ג:"g",ד:"d",דּ:"d",ה:"h",ו:"v",ז:"z",ח:"h",ט:"t",י:"y",כ:"kh",ך:"kh",ל:"l",מ:"m",ם:"m",נ:"n",ן:"n",ס:"s",פ:"f",ף:"f",ץ:"ts",צ:"ts",ק:"k",ר:"r",תּ:"t",ת:"t"};slug.charmap=Object.assign({},initialCharmap);slug.multicharmap=Object.assign({},initialMulticharmap);slug.defaults={charmap:slug.charmap,mode:"pretty",modes:{rfc3986:{replacement:"-",remove:null,lower:!0,charmap:slug.charmap,multicharmap:slug.multicharmap,trim:!0},pretty:{replacement:"-",remove:null,lower:!0,charmap:slug.charmap,multicharmap:slug.multicharmap,trim:!0}},multicharmap:slug.multicharmap,fallback:!0};slug.reset=function(){slug.defaults.modes.rfc3986.charmap=slug.defaults.modes.pretty.charmap=slug.charmap=slug.defaults.charmap=Object.assign({},initialCharmap),slug.defaults.modes.rfc3986.multicharmap=slug.defaults.modes.pretty.multicharmap=slug.multicharmap=slug.defaults.multicharmap=Object.assign({},initialMulticharmap),defaultLocale=""};slug.extend=function(r){const e=Object.keys(r),M={},tr={};for(let rr=0;rr<e.length;rr++)e[rr].length>1?M[e[rr]]=r[e[rr]]:tr[e[rr]]=r[e[rr]];Object.assign(slug.charmap,tr),Object.assign(slug.multicharmap,M)};slug.setLocale=function(r){defaultLocale=locales[r]||{}};function resolveUrlPathname(r){return new URL(r.replace(/^\/+/,""),window.location.origin+(window.ph?.basePath??"/")).pathname}function getPathWithoutBase(r){const e=window.ph?.basePath??"/";return r.replace(e,e.endsWith("/")?"/":"")}function makeNodeSlug(r){if(!r)return"";const e=r.name;return slug(e?`${e}-${r.id}`:r.id)}function extractNodeSlugFromPath(r){const e=getPathWithoutBase(r);return/^\/d\/[^/]+\/([^/]+)$/.exec(e)?.[1]}function findUuid(r){return r?/\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(r)?.[0]:void 0}function extractNodeIdFromSlug(r){return findUuid(r)}function extractDriveSlugFromPath(r){const e=getPathWithoutBase(r);return/^\/d\/([^/]+)/.exec(e)?.[1]??""}function extractDriveIdFromSlug(r){return findUuid(r)}function extractDriveIdFromPath(r){const e=extractDriveSlugFromPath(r);return extractDriveIdFromSlug(e)}function createUrlWithPreservedParams(r){const e=window.location.search;return e?`${r}${e}`:r}const drivesEventFunctions=makePHEventFunctions("drives"),useDrives=drivesEventFunctions.useValue,setDrives=drivesEventFunctions.setValue,addDrivesEventHandler=drivesEventFunctions.addEventHandler,selectedDriveIdEventFunctions=makePHEventFunctions("selectedDriveId"),useSelectedDriveId=selectedDriveIdEventFunctions.useValue,setSelectedDriveId=selectedDriveIdEventFunctions.setValue,addSelectedDriveIdEventHandler=selectedDriveIdEventFunctions.addEventHandler;function useSelectedDrive(){const r=useSelectedDriveSafe();if(!r[0])throw new Error("There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?");return r}function useSelectedDriveSafe(){const r=useSelectedDriveId(),M=useDrives()?.find(ir=>ir.header.id===r),[tr,rr]=useDispatch(M);return M?[tr,rr]:[void 0,void 0]}function setSelectedDrive(r){const e=typeof r=="string"?r:r?.header.slug,tr=window.ph?.drives?.find(ir=>ir.header.slug===e)?.header.id;if(setSelectedDriveId(tr),!tr){const ir=resolveUrlPathname("/");if(ir===window.location.pathname)return;window.history.pushState(null,"",createUrlWithPreservedParams(ir));return}const rr=resolveUrlPathname(`/d/${e}`);rr!==window.location.pathname&&window.history.pushState(null,"",createUrlWithPreservedParams(rr))}function addSetSelectedDriveOnPopStateEventHandler(){window.addEventListener("popstate",()=>{const r=window.location.pathname,e=extractDriveIdFromPath(r),M=window.ph?.selectedDriveId;e!==M&&setSelectedDrive(e)})}function useNodesInSelectedDrive(){const[r]=useSelectedDriveSafe();return r?.state.global.nodes}function useFolderNodesInSelectedDrive(){return useNodesInSelectedDrive()?.filter(e=>isFolderNodeKind(e))}const selectedNodeIdEventFunctions=makePHEventFunctions("selectedNodeId"),useSelectedNodeId=selectedNodeIdEventFunctions.useValue,setSelectedNodeId=selectedNodeIdEventFunctions.setValue,addSelectedNodeIdEventHandler=selectedNodeIdEventFunctions.addEventHandler;function useSelectedNode(){const r=useSelectedNodeId();return useNodesInSelectedDrive()?.find(M=>M.id===r)}function setSelectedNode(r){const e=typeof r=="string"?r:makeNodeSlug(r),M=extractNodeIdFromSlug(e);setSelectedNodeId(M);const tr=extractDriveSlugFromPath(window.location.pathname);if(!tr)return;if(!e){const ir=resolveUrlPathname(`/d/${tr}`);if(ir===window.location.pathname)return;window.history.pushState(null,"",createUrlWithPreservedParams(ir));return}const rr=resolveUrlPathname(`/d/${tr}/${e}`);rr!==window.location.pathname&&window.history.pushState(null,"",createUrlWithPreservedParams(rr))}function addResetSelectedNodeEventHandler(){window.addEventListener("ph:selectedDriveIdUpdated",()=>{setSelectedNodeId(void 0)})}function addSetSelectedNodeOnPopStateEventHandler(){window.addEventListener("popstate",()=>{const r=window.location.pathname,e=extractNodeSlugFromPath(r),M=window.ph?.selectedNodeId;e!==M&&setSelectedNode(e)})}function useSelectedFolder(){const r=useSelectedNode();if(isFolderNodeKind(r))return r}function useNodesInSelectedDriveOrFolder(){const r=useNodesInSelectedDrive(),M=useSelectedFolder()?.id;return r?sortNodesByName(M?r.filter(tr=>tr.parentFolder===M):r.filter(tr=>!tr.parentFolder)):[]}const{setValue:setRouterBasename,addEventHandler:addRouterBasenameEventHandler}=makePHEventFunctions("routerBasename"),{setValue:setVersion,addEventHandler:addVersionEventHandler}=makePHEventFunctions("version"),{setValue:setRequiresHardRefresh,addEventHandler:addRequiresHardRefreshEventHandler}=makePHEventFunctions("requiresHardRefresh"),{setValue:setWarnOutdatedApp,addEventHandler:addWarnOutdatedAppEventHandler}=makePHEventFunctions("warnOutdatedApp"),{setValue:setStudioMode,addEventHandler:addStudioModeEventHandler}=makePHEventFunctions("studioMode"),{setValue:setBasePath,addEventHandler:addBasePathEventHandler}=makePHEventFunctions("basePath"),{setValue:setVersionCheckInterval,addEventHandler:addVersionCheckIntervalEventHandler}=makePHEventFunctions("versionCheckInterval"),{setValue:setCliVersion,addEventHandler:addCliVersionEventHandler}=makePHEventFunctions("cliVersion"),{setValue:setFileUploadOperationsChunkSize,addEventHandler:addFileUploadOperationsChunkSizeEventHandler}=makePHEventFunctions("fileUploadOperationsChunkSize"),{setValue:setIsDocumentModelSelectionSettingsEnabled,addEventHandler:addIsDocumentModelSelectionSettingsEnabledEventHandler}=makePHEventFunctions("isDocumentModelSelectionSettingsEnabled"),{setValue:setGaTrackingId,addEventHandler:addGaTrackingIdEventHandler}=makePHEventFunctions("gaTrackingId"),{setValue:setDefaultDrivesUrl,addEventHandler:addDefaultDrivesUrlEventHandler}=makePHEventFunctions("defaultDrivesUrl"),{setValue:setDrivesPreserveStrategy,addEventHandler:addDrivesPreserveStrategyEventHandler}=makePHEventFunctions("drivesPreserveStrategy"),{setValue:setIsLocalDrivesEnabled,addEventHandler:addIsLocalDrivesEnabledEventHandler}=makePHEventFunctions("isLocalDrivesEnabled"),{setValue:setIsAddDriveEnabled,addEventHandler:addIsAddDriveEnabledEventHandler}=makePHEventFunctions("isAddDriveEnabled"),{setValue:setIsPublicDrivesEnabled,addEventHandler:addIsPublicDrivesEnabledEventHandler}=makePHEventFunctions("isPublicDrivesEnabled"),{setValue:setIsAddPublicDrivesEnabled,addEventHandler:addIsAddPublicDrivesEnabledEventHandler}=makePHEventFunctions("isAddPublicDrivesEnabled"),{setValue:setIsDeletePublicDrivesEnabled,addEventHandler:addIsDeletePublicDrivesEnabledEventHandler}=makePHEventFunctions("isDeletePublicDrivesEnabled"),{setValue:setIsCloudDrivesEnabled,addEventHandler:addIsCloudDrivesEnabledEventHandler}=makePHEventFunctions("isCloudDrivesEnabled"),{setValue:setIsAddCloudDrivesEnabled,addEventHandler:addIsAddCloudDrivesEnabledEventHandler}=makePHEventFunctions("isAddCloudDrivesEnabled"),{setValue:setIsDeleteCloudDrivesEnabled,addEventHandler:addIsDeleteCloudDrivesEnabledEventHandler}=makePHEventFunctions("isDeleteCloudDrivesEnabled");makePHEventFunctions("isLocalDrivesEnabled");const{setValue:setIsAddLocalDrivesEnabled,addEventHandler:addIsAddLocalDrivesEnabledEventHandler}=makePHEventFunctions("isAddLocalDrivesEnabled"),{setValue:setIsDeleteLocalDrivesEnabled,addEventHandler:addIsDeleteLocalDrivesEnabledEventHandler}=makePHEventFunctions("isDeleteLocalDrivesEnabled"),{setValue:setIsEditorDebugModeEnabled,addEventHandler:addIsEditorDebugModeEnabledEventHandler}=makePHEventFunctions("isEditorDebugModeEnabled"),{setValue:setIsEditorReadModeEnabled,addEventHandler:addIsEditorReadModeEnabledEventHandler}=makePHEventFunctions("isEditorReadModeEnabled"),{setValue:setIsAnalyticsDatabaseWorkerEnabled,addEventHandler:addIsAnalyticsDatabaseWorkerEnabledEventHandler}=makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled"),{setValue:setIsDiffAnalyticsEnabled,addEventHandler:addIsDiffAnalyticsEnabledEventHandler}=makePHEventFunctions("isDiffAnalyticsEnabled"),{setValue:setIsDriveAnalyticsEnabled,addEventHandler:addIsDriveAnalyticsEnabledEventHandler}=makePHEventFunctions("isDriveAnalyticsEnabled"),{setValue:setRenownUrl,addEventHandler:addRenownUrlEventHandler}=makePHEventFunctions("renownUrl"),{setValue:setRenownNetworkId,addEventHandler:addRenownNetworkIdEventHandler}=makePHEventFunctions("renownNetworkId"),{setValue:setRenownChainId,addEventHandler:addRenownChainIdEventHandler}=makePHEventFunctions("renownChainId"),{setValue:setSentryRelease,addEventHandler:addSentryReleaseEventHandler}=makePHEventFunctions("sentryRelease"),{setValue:setSentryDsn,addEventHandler:addSentryDsnEventHandler}=makePHEventFunctions("sentryDsn"),{setValue:setSentryEnv,addEventHandler:addSentryEnvEventHandler}=makePHEventFunctions("sentryEnv"),{setValue:setIsSentryTracingEnabled,addEventHandler:addIsSentryTracingEnabledEventHandler}=makePHEventFunctions("isSentryTracingEnabled"),{setValue:setIsExternalProcessorsEnabled,addEventHandler:addIsExternalProcessorsEnabledEventHandler}=makePHEventFunctions("isExternalProcessorsEnabled"),{setValue:setIsExternalPackagesEnabled,addEventHandler:addIsExternalPackagesEnabledEventHandler}=makePHEventFunctions("isExternalPackagesEnabled"),enabledEditorsEventFunctions=makePHEventFunctions("enabledEditors"),setEnabledEditors=enabledEditorsEventFunctions.setValue,addEnabledEditorsEventHandler=enabledEditorsEventFunctions.addEventHandler,disabledEditorsEventFunctions=makePHEventFunctions("disabledEditors"),setDisabledEditors=disabledEditorsEventFunctions.setValue,addDisabledEditorsEventHandler=disabledEditorsEventFunctions.addEventHandler,isRelationalProcessorsEnabled=makePHEventFunctions("isRelationalProcessorsEnabled"),setIsRelationalProcessorsEnabled=isRelationalProcessorsEnabled.setValue,addIsRelationalProcessorsEnabledEventHandler=isRelationalProcessorsEnabled.addEventHandler,isExternalRelationalProcessorsEnabled=makePHEventFunctions("isExternalRelationalProcessorsEnabled"),setIsExternalRelationalProcessorsEnabled=isExternalRelationalProcessorsEnabled.setValue,addIsExternalRelationalProcessorsEnabledEventHandler=isExternalRelationalProcessorsEnabled.addEventHandler,isAnalyticsEnabledEventFunctions=makePHEventFunctions("isAnalyticsEnabled"),setIsAnalyticsEnabled=isAnalyticsEnabledEventFunctions.setValue,addIsAnalyticsEnabledEventHandler=isAnalyticsEnabledEventFunctions.addEventHandler,isAnalyticsExternalProcessorsEnabled=makePHEventFunctions("isAnalyticsExternalProcessorsEnabled"),setIsAnalyticsExternalProcessorsEnabled=isAnalyticsExternalProcessorsEnabled.setValue,addIsAnalyticsExternalProcessorsEnabledEventHandler=isAnalyticsExternalProcessorsEnabled.addEventHandler,analyticsDatabaseNameEventFunctions=makePHEventFunctions("analyticsDatabaseName"),setAnalyticsDatabaseName=analyticsDatabaseNameEventFunctions.setValue,addAnalyticsDatabaseNameEventHandler=analyticsDatabaseNameEventFunctions.addEventHandler,logLevelEventFunctions=makePHEventFunctions("logLevel"),setLogLevel=logLevelEventFunctions.setValue,addLogLevelEventHandler=logLevelEventFunctions.addEventHandler,allowListEventFunctions=makePHEventFunctions("allowList"),setAllowList=allowListEventFunctions.setValue,useAllowList=allowListEventFunctions.useValue,addAllowListEventHandler=allowListEventFunctions.addEventHandler,nonUserConfigSetters={routerBasename:setRouterBasename,version:setVersion,requiresHardRefresh:setRequiresHardRefresh,warnOutdatedApp:setWarnOutdatedApp,studioMode:setStudioMode,basePath:setBasePath,versionCheckInterval:setVersionCheckInterval,cliVersion:setCliVersion,fileUploadOperationsChunkSize:setFileUploadOperationsChunkSize,isDocumentModelSelectionSettingsEnabled:setIsDocumentModelSelectionSettingsEnabled,gaTrackingId:setGaTrackingId,defaultDrivesUrl:setDefaultDrivesUrl,drivesPreserveStrategy:setDrivesPreserveStrategy,isLocalDrivesEnabled:setIsLocalDrivesEnabled,isAddDriveEnabled:setIsAddDriveEnabled,isPublicDrivesEnabled:setIsPublicDrivesEnabled,isAddPublicDrivesEnabled:setIsAddPublicDrivesEnabled,isDeletePublicDrivesEnabled:setIsDeletePublicDrivesEnabled,isCloudDrivesEnabled:setIsCloudDrivesEnabled,isAddCloudDrivesEnabled:setIsAddCloudDrivesEnabled,isDeleteCloudDrivesEnabled:setIsDeleteCloudDrivesEnabled,isAddLocalDrivesEnabled:setIsAddLocalDrivesEnabled,isDeleteLocalDrivesEnabled:setIsDeleteLocalDrivesEnabled,isEditorDebugModeEnabled:setIsEditorDebugModeEnabled,isEditorReadModeEnabled:setIsEditorReadModeEnabled,isRelationalProcessorsEnabled:setIsRelationalProcessorsEnabled,isExternalRelationalProcessorsEnabled:setIsExternalRelationalProcessorsEnabled,isAnalyticsEnabled:setIsAnalyticsEnabled,analyticsDatabaseName:setAnalyticsDatabaseName,isAnalyticsExternalProcessorsEnabled:setIsAnalyticsExternalProcessorsEnabled,isAnalyticsDatabaseWorkerEnabled:setIsAnalyticsDatabaseWorkerEnabled,isDiffAnalyticsEnabled:setIsDiffAnalyticsEnabled,isDriveAnalyticsEnabled:setIsDriveAnalyticsEnabled,renownUrl:setRenownUrl,renownNetworkId:setRenownNetworkId,renownChainId:setRenownChainId,sentryRelease:setSentryRelease,sentryDsn:setSentryDsn,sentryEnv:setSentryEnv,isSentryTracingEnabled:setIsSentryTracingEnabled,isExternalProcessorsEnabled:setIsExternalProcessorsEnabled,isExternalPackagesEnabled:setIsExternalPackagesEnabled,allowList:setAllowList,logLevel:setLogLevel,disabledEditors:setDisabledEditors,enabledEditors:setEnabledEditors},phGlobalConfigSetters={...phDriveEditorConfigSetters,...phDocumentEditorConfigSetters,...nonUserConfigSetters};function callGlobalSetterForKey(r,e){const M=phGlobalConfigSetters[r];M(e)}function setDefaultPHGlobalConfig(r){for(const e of Object.keys(r))callGlobalSetterForKey(e,r[e])}function setPHDriveEditorConfig(r){for(const e of Object.keys(r))callGlobalSetterForKey(e,r[e])}function setPHDocumentEditorConfig(r){for(const e of Object.keys(r))callGlobalSetterForKey(e,r[e])}function useSetPHDriveEditorConfig(r){const[e,M]=reactExports.useState(!1);reactExports.useEffect(()=>{e||(setPHDriveEditorConfig(r),M(!0))},[r,e])}function useSetPHDocumentEditorConfig(r){const[e,M]=reactExports.useState(!1);reactExports.useEffect(()=>{e||(setPHDocumentEditorConfig(r),M(!0))},[r,e])}function useDocumentOfType(r,e){const[M,tr]=useDocumentById(r),rr=useDocumentModelModuleById(e);if(!r||!e)return[];if(!M)throw new DocumentNotFoundError(r);if(!rr)throw new DocumentModelNotFoundError(e);if(M.header.documentType!==e)throw new DocumentTypeMismatchError(r,e,M.header.documentType);return[M,tr]}const reactorClientModuleEventFunctions=makePHEventFunctions("reactorClientModule"),reactorClientEventFunctions=makePHEventFunctions("reactorClient"),useReactorClientModule=reactorClientModuleEventFunctions.useValue,setReactorClientModule=reactorClientModuleEventFunctions.setValue,addReactorClientModuleEventHandler=reactorClientModuleEventFunctions.addEventHandler,useReactorClient=reactorClientEventFunctions.useValue,setReactorClient=reactorClientEventFunctions.setValue,addReactorClientEventHandler=reactorClientEventFunctions.addEventHandler,useSync=()=>useReactorClientModule()?.reactorModule?.syncModule?.syncManager,useSyncList=()=>useSync()?.list()??[],useDatabase=()=>useReactorClientModule()?.reactorModule?.database,usePGlite=()=>useReactorClientModule()?.pg;function useDocumentOperations(r){const e=useReactorClient(),M=reactExports.useRef(!1),[tr,rr]=reactExports.useState(()=>({globalOperations:[],localOperations:[],isLoading:!!r,error:void 0})),ir=reactExports.useCallback(async(dr=0)=>{if(!r||!e){rr({globalOperations:[],localOperations:[],isLoading:!1,error:void 0});return}rr(wr=>({...wr,isLoading:!0,error:void 0}));let mr=[],_r=[],gr;try{mr=(await e.getOperations(r,{scopes:["global"]})).results}catch(wr){gr=wr instanceof Error?wr:new Error(String(wr))}if(!gr)try{_r=(await e.getOperations(r,{scopes:["local"]})).results}catch(wr){gr=wr instanceof Error?wr:new Error(String(wr))}if(!gr&&mr.length===0&&_r.length===0&&dr<5)return await new Promise(wr=>setTimeout(wr,500)),ir(dr+1);rr({globalOperations:mr,localOperations:_r,isLoading:!1,error:gr}),M.current=!0},[r,e]);reactExports.useEffect(()=>{r&&e?ir():r||(rr({globalOperations:[],localOperations:[],isLoading:!1,error:void 0}),M.current=!1)},[r,e,ir]);const lr=reactExports.useCallback(()=>{ir(0)},[ir]);return{...tr,refetch:lr}}function useSupportedDocumentTypesInReactor(){return useDocumentModelModules()?.map(e=>e.documentModel.global.id)}function useDocumentTypes(){const r=useAllowedDocumentTypes(),e=useSupportedDocumentTypesInReactor();return r??e}function useDriveById(r){const M=useDrives()?.find(ir=>ir.header.id===r),[tr,rr]=useDispatch(M);if(!M)throw new Error(`Drive with id ${r} not found`);return[tr,rr]}function useEditorModules(){return useVetraPackages()?.flatMap(e=>e.modules.editorModules||[]).filter(e=>!e.documentTypes.includes("powerhouse/document-drive"))}function useDriveEditorModules(){return useVetraPackages()?.flatMap(e=>e.modules.editorModules||[]).filter(e=>e.documentTypes.includes("powerhouse/document-drive"))}function useFallbackEditorModule(r){const e=useEditorModules();return!r||e?.length===0?void 0:e?.filter(tr=>tr.documentTypes.includes(r))?.[0]}function useDriveEditorModuleById(r){return useDriveEditorModules()?.find(M=>M.id===r)}function useDefaultDriveEditorModule(){return useDriveEditorModuleById(DEFAULT_DRIVE_EDITOR_ID)}function useEditorModuleById(r){return useEditorModules()?.find(M=>M.id===r)}const featuresEventFunctions=makePHEventFunctions("features"),useFeatures=featuresEventFunctions.useValue,setFeatures=featuresEventFunctions.setValue,addFeaturesEventHandler=featuresEventFunctions.addEventHandler;function useFolderById(r){return useFolderNodesInSelectedDrive()?.find(M=>M.id===r)}const modalEventFunctions=makePHEventFunctions("modal"),usePHModal=modalEventFunctions.useValue,setPHModal=modalEventFunctions.setValue,addModalEventHandler=modalEventFunctions.addEventHandler;function showPHModal(r){setPHModal(r)}function closePHModal(){setPHModal(void 0)}function showCreateDocumentModal(r){setPHModal({type:"createDocument",documentType:r})}function showDeleteNodeModal(r){const e=typeof r=="string"?r:r.id;setPHModal({type:"deleteItem",id:e})}function resolveNode(r,e){return e?.id!==r?e:void 0}function useNodeActions(){const[r]=useSelectedDriveSafe(),e=useSelectedFolder(),M=useSelectedNode(),tr=useFolderById(M?.parentFolder),rr=r?.header.id,ir=useDrives();async function lr(yr,br){if(!rr)return;const Mr=yr.name.replace(/\..+/gim,"");return addFile(yr,rr,Mr,resolveNode(rr,br)?.id)}async function dr(yr,br){if(rr)return addFolder(rr,yr,resolveNode(rr,br)?.id)}async function hr(yr,br){if(!rr)return;if(!resolveNode(rr,br)){console.error(`Node ${br.id} not found`);return}return await renameNode(rr,br.id,yr)}async function fr(yr,br){if(!rr)return;const Mr=resolveNode(rr,yr);if(!Mr){console.error(`Node ${yr.id} not found`);return}const vr=resolveNode(rr,br);await copyNode(rr,Mr,vr)}async function mr(yr,br){if(!rr)return;const Mr=resolveNode(rr,yr);if(!Mr){console.error(`Node ${yr.id} not found`);return}const vr=resolveNode(rr,br);!vr?.id&&!yr.parentFolder||vr?.id===yr.parentFolder||await moveNode(rr,Mr,vr)}async function _r(yr){if(!rr)return;const br=resolveNode(rr,yr);if(!br){console.error(`Node ${yr.id} not found`);return}const Mr=resolveNode(rr,e??tr);await copyNode(rr,br,Mr)}async function gr(yr){if(!yr||!rr)return;const br=resolveNode(rr,e??tr);if(!br)return;const Mr=await dr(yr,br);Mr&&setSelectedNode(Mr)}async function wr(yr,br){if(!ir)return;const Mr=ir.filter(vr=>vr.state.global.nodes.some(Sr=>Sr.id===br));await Promise.all(Mr.map(vr=>renameDriveNode(vr.header.id,br,yr)))}return{onAddFile:lr,onAddFolder:dr,onRenameNode:hr,onCopyNode:fr,onMoveNode:mr,onDuplicateNode:_r,onAddAndSelectNewFolder:gr,onRenameDriveNodes:wr}}function useNodeById(r){return useNodesInSelectedDrive()?.find(M=>M.id===r)}function useNodePathById(r){const e=useNodesInSelectedDrive();if(!e)return[];const M=[];let tr=e.find(rr=>rr.id===r);for(;tr&&(M.push(tr),!!tr.parentFolder);)tr=e.find(rr=>rr.id===tr?.parentFolder);return M.reverse()}function useSelectedNodePath(){const r=useSelectedNode();return useNodePathById(r?.id)}function useNodeParentFolderById(r){const e=useNodeById(r);return useFolderById(e?.parentFolder)}function useParentFolderForSelectedNode(){const r=useSelectedNode();return useNodeParentFolderById(r?.id)}const revisionHistoryEventFunctions=makePHEventFunctions("revisionHistoryVisible"),useRevisionHistoryVisible=revisionHistoryEventFunctions.useValue,setRevisionHistoryVisible=revisionHistoryEventFunctions.setValue,addRevisionHistoryVisibleEventHandler=revisionHistoryEventFunctions.addEventHandler;function showRevisionHistory(){setRevisionHistoryVisible(!0)}function useSelectedDocumentId(){const r=useSelectedNode();return r&&isFileNode(r)?r.id:void 0}function useSelectedDocument(){const r=useSelectedDocumentId(),[e,M]=useDocumentById(r);if(!e)throw new NoSelectedDocumentError;return[e,M]}function useSelectedDocumentSafe(){const r=useSelectedDocumentId();return useDocumentById(r)}function useSelectedDocumentOfType(r){const e=useSelectedDocumentId();if(!e)throw new NoSelectedDocumentError;return useDocumentOfType(e,r)}const selectedTimelineItemEventFunctions=makePHEventFunctions("selectedTimelineItem"),useSelectedTimelineItem=selectedTimelineItemEventFunctions.useValue,setSelectedTimelineItem=selectedTimelineItemEventFunctions.setValue,addSelectedTimelineItemEventHandler=selectedTimelineItemEventFunctions.addEventHandler,selectedTimelineRevisionEventFunctions=makePHEventFunctions("selectedTimelineRevision"),addSelectedTimelineRevisionEventHandler=selectedTimelineRevisionEventFunctions.addEventHandler,toastEventFunctions=makePHEventFunctions("toast"),usePHToast=toastEventFunctions.useValue,setPHToast=toastEventFunctions.setValue,addToastEventHandler=toastEventFunctions.addEventHandler,FEATURE_INSPECTOR_ENABLED="FEATURE_INSPECTOR_ENABLED",FEATURE_INSPECTOR_ENABLED_DEFAULT=!1;function useInspectorEnabled(){return useFeatures()?.get(FEATURE_INSPECTOR_ENABLED)??FEATURE_INSPECTOR_ENABLED_DEFAULT}const syncStatusToUI={[SyncStatus.Synced]:"SUCCESS",[SyncStatus.Outgoing]:"SYNCING",[SyncStatus.Incoming]:"SYNCING",[SyncStatus.OutgoingAndIncoming]:"SYNCING",[SyncStatus.Error]:"ERROR"};async function getDrives(r){return(await r.find({type:"powerhouse/document-drive"})).results}function getSyncStatusSync(r,e){if(e==="LOCAL")return;const M=window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;if(!M)return;const tr=M.getSyncStatus(r);if(tr!==void 0)return syncStatusToUI[tr]}const validateDocument=r=>{const e=[];if(r.header.documentType!=="powerhouse/document-model")return e;const M=r,tr=M.state.global.specifications[0],rr=Object.keys(tr.state).reduce((dr,hr)=>{const fr=hr;return[...dr,...validateInitialState(tr.state[fr].initialValue,fr!=="global").map(mr=>({...mr,message:`${mr.message}. Scope: ${fr}`,details:{...mr.details,scope:fr}}))]},[]),ir=Object.keys(tr.state).reduce((dr,hr)=>{const fr=hr,mr=fr==="global";return[...dr,...validateStateSchemaName(tr.state[fr].schema,M.state.global?.name||M.header.name||"",mr?"":fr,!mr).map(_r=>({..._r,message:`${_r.message}. Scope: ${fr}`,details:{..._r.details,scope:fr}}))]},[]),lr=validateModules(tr.modules);return[...rr,...ir,...lr]},exportDocument=r=>{if(!r)return;if(validateDocument(r).length)showPHModal({type:"exportDocumentWithErrors",documentId:r.header.id});else return exportFile(r)},getRevisionFromDate=(r,e,M=[])=>{if(!r||!e)return 0;const tr=M.find(rr=>{const ir=new Date(rr.timestampUtcMs);return ir>=r&&ir<=e});return tr?tr.index:0};var lzString={exports:{}},hasRequiredLzString;function requireLzString(){return hasRequiredLzString||(hasRequiredLzString=1,(function(r){var e=(function(){var M=String.fromCharCode,tr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",rr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",ir={};function lr(hr,fr){if(!ir[hr]){ir[hr]={};for(var mr=0;mr<hr.length;mr++)ir[hr][hr.charAt(mr)]=mr}return ir[hr][fr]}var dr={compressToBase64:function(hr){if(hr==null)return"";var fr=dr._compress(hr,6,function(mr){return tr.charAt(mr)});switch(fr.length%4){default:case 0:return fr;case 1:return fr+"===";case 2:return fr+"==";case 3:return fr+"="}},decompressFromBase64:function(hr){return hr==null?"":hr==""?null:dr._decompress(hr.length,32,function(fr){return lr(tr,hr.charAt(fr))})},compressToUTF16:function(hr){return hr==null?"":dr._compress(hr,15,function(fr){return M(fr+32)})+" "},decompressFromUTF16:function(hr){return hr==null?"":hr==""?null:dr._decompress(hr.length,16384,function(fr){return hr.charCodeAt(fr)-32})},compressToUint8Array:function(hr){for(var fr=dr.compress(hr),mr=new Uint8Array(fr.length*2),_r=0,gr=fr.length;_r<gr;_r++){var wr=fr.charCodeAt(_r);mr[_r*2]=wr>>>8,mr[_r*2+1]=wr%256}return mr},decompressFromUint8Array:function(hr){if(hr==null)return dr.decompress(hr);for(var fr=new Array(hr.length/2),mr=0,_r=fr.length;mr<_r;mr++)fr[mr]=hr[mr*2]*256+hr[mr*2+1];var gr=[];return fr.forEach(function(wr){gr.push(M(wr))}),dr.decompress(gr.join(""))},compressToEncodedURIComponent:function(hr){return hr==null?"":dr._compress(hr,6,function(fr){return rr.charAt(fr)})},decompressFromEncodedURIComponent:function(hr){return hr==null?"":hr==""?null:(hr=hr.replace(/ /g,"+"),dr._decompress(hr.length,32,function(fr){return lr(rr,hr.charAt(fr))}))},compress:function(hr){return dr._compress(hr,16,function(fr){return M(fr)})},_compress:function(hr,fr,mr){if(hr==null)return"";var _r,gr,wr={},yr={},br="",Mr="",vr="",Sr=2,xr=3,Ar=2,Dr=[],Ir=0,kr=0,Or;for(Or=0;Or<hr.length;Or+=1)if(br=hr.charAt(Or),Object.prototype.hasOwnProperty.call(wr,br)||(wr[br]=xr++,yr[br]=!0),Mr=vr+br,Object.prototype.hasOwnProperty.call(wr,Mr))vr=Mr;else{if(Object.prototype.hasOwnProperty.call(yr,vr)){if(vr.charCodeAt(0)<256){for(_r=0;_r<Ar;_r++)Ir=Ir<<1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++;for(gr=vr.charCodeAt(0),_r=0;_r<8;_r++)Ir=Ir<<1|gr&1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=gr>>1}else{for(gr=1,_r=0;_r<Ar;_r++)Ir=Ir<<1|gr,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=0;for(gr=vr.charCodeAt(0),_r=0;_r<16;_r++)Ir=Ir<<1|gr&1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=gr>>1}Sr--,Sr==0&&(Sr=Math.pow(2,Ar),Ar++),delete yr[vr]}else for(gr=wr[vr],_r=0;_r<Ar;_r++)Ir=Ir<<1|gr&1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=gr>>1;Sr--,Sr==0&&(Sr=Math.pow(2,Ar),Ar++),wr[Mr]=xr++,vr=String(br)}if(vr!==""){if(Object.prototype.hasOwnProperty.call(yr,vr)){if(vr.charCodeAt(0)<256){for(_r=0;_r<Ar;_r++)Ir=Ir<<1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++;for(gr=vr.charCodeAt(0),_r=0;_r<8;_r++)Ir=Ir<<1|gr&1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=gr>>1}else{for(gr=1,_r=0;_r<Ar;_r++)Ir=Ir<<1|gr,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=0;for(gr=vr.charCodeAt(0),_r=0;_r<16;_r++)Ir=Ir<<1|gr&1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=gr>>1}Sr--,Sr==0&&(Sr=Math.pow(2,Ar),Ar++),delete yr[vr]}else for(gr=wr[vr],_r=0;_r<Ar;_r++)Ir=Ir<<1|gr&1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=gr>>1;Sr--,Sr==0&&(Sr=Math.pow(2,Ar),Ar++)}for(gr=2,_r=0;_r<Ar;_r++)Ir=Ir<<1|gr&1,kr==fr-1?(kr=0,Dr.push(mr(Ir)),Ir=0):kr++,gr=gr>>1;for(;;)if(Ir=Ir<<1,kr==fr-1){Dr.push(mr(Ir));break}else kr++;return Dr.join("")},decompress:function(hr){return hr==null?"":hr==""?null:dr._decompress(hr.length,32768,function(fr){return hr.charCodeAt(fr)})},_decompress:function(hr,fr,mr){var _r=[],gr=4,wr=4,yr=3,br="",Mr=[],vr,Sr,xr,Ar,Dr,Ir,kr,Or={val:mr(0),position:fr,index:1};for(vr=0;vr<3;vr+=1)_r[vr]=vr;for(xr=0,Dr=Math.pow(2,2),Ir=1;Ir!=Dr;)Ar=Or.val&Or.position,Or.position>>=1,Or.position==0&&(Or.position=fr,Or.val=mr(Or.index++)),xr|=(Ar>0?1:0)*Ir,Ir<<=1;switch(xr){case 0:for(xr=0,Dr=Math.pow(2,8),Ir=1;Ir!=Dr;)Ar=Or.val&Or.position,Or.position>>=1,Or.position==0&&(Or.position=fr,Or.val=mr(Or.index++)),xr|=(Ar>0?1:0)*Ir,Ir<<=1;kr=M(xr);break;case 1:for(xr=0,Dr=Math.pow(2,16),Ir=1;Ir!=Dr;)Ar=Or.val&Or.position,Or.position>>=1,Or.position==0&&(Or.position=fr,Or.val=mr(Or.index++)),xr|=(Ar>0?1:0)*Ir,Ir<<=1;kr=M(xr);break;case 2:return""}for(_r[3]=kr,Sr=kr,Mr.push(kr);;){if(Or.index>hr)return"";for(xr=0,Dr=Math.pow(2,yr),Ir=1;Ir!=Dr;)Ar=Or.val&Or.position,Or.position>>=1,Or.position==0&&(Or.position=fr,Or.val=mr(Or.index++)),xr|=(Ar>0?1:0)*Ir,Ir<<=1;switch(kr=xr){case 0:for(xr=0,Dr=Math.pow(2,8),Ir=1;Ir!=Dr;)Ar=Or.val&Or.position,Or.position>>=1,Or.position==0&&(Or.position=fr,Or.val=mr(Or.index++)),xr|=(Ar>0?1:0)*Ir,Ir<<=1;_r[wr++]=M(xr),kr=wr-1,gr--;break;case 1:for(xr=0,Dr=Math.pow(2,16),Ir=1;Ir!=Dr;)Ar=Or.val&Or.position,Or.position>>=1,Or.position==0&&(Or.position=fr,Or.val=mr(Or.index++)),xr|=(Ar>0?1:0)*Ir,Ir<<=1;_r[wr++]=M(xr),kr=wr-1,gr--;break;case 2:return Mr.join("")}if(gr==0&&(gr=Math.pow(2,yr),yr++),_r[kr])br=_r[kr];else if(kr===wr)br=Sr+Sr.charAt(0);else return null;Mr.push(br),_r[wr++]=Sr+br.charAt(0),gr--,Sr=br,gr==0&&(gr=Math.pow(2,yr),yr++)}}};return dr})();r!=null?r.exports=e:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return e})})(lzString)),lzString.exports}var lzStringExports=requireLzString();function getSlugFromDriveUrl(r){return r.split("/").pop()}function getDocumentGraphqlQuery(){return`query getDocument($documentId: String!) {
97
+ document(id: $documentId) {
98
+ id
99
+ documentType
100
+ createdAtUtcIso
101
+ lastModifiedAtUtcIso
102
+ name
103
+ revision
104
+ stateJSON
105
+ }
106
+ }`}function buildDocumentSubgraphQuery(r,e,M){const tr=getSlugFromDriveUrl(r),rr=getDocumentGraphqlQuery(),ir={documentId:e,driveId:tr},lr=M?{Authorization:`Bearer ${M}`}:void 0,dr={document:rr.trim(),variables:JSON.stringify(ir,null,2)};return lr&&(dr.headers=JSON.stringify(lr)),lzStringExports.compressToEncodedURIComponent(JSON.stringify(dr))}function buildDocumentSubgraphUrl(r,e,M){const tr=buildDocumentSubgraphQuery(r,e,M);return`${r}?explorerURLState=${tr}`}function convertLegacyLibToVetraPackage(r){return{id:generateId(),name:r.manifest.name,description:r.manifest.description,category:r.manifest.category,author:{name:"Powerhouse",website:"https://powerhousedao.com"},modules:{documentModelModules:r.documentModels.map(convertLegacyDocumentModelModuleToVetraDocumentModelModule),editorModules:r.editors.map(tr=>convertLegacyEditorModuleToVetraEditorModule(tr,r.manifest))},upgradeManifests:r.upgradeManifests,processorFactory:r.processorFactory}}function convertLegacyDocumentModelModuleToVetraDocumentModelModule(r){const e=r.documentModel.global,M=e.name,tr=e.id,rr=tr,ir=e.extension,lr=e.specifications,dr=r.reducer,hr=r.actions,fr=r.utils;return{id:rr,name:M,documentType:tr,extension:ir,documentModel:createState(defaultBaseState(),e),specifications:lr,reducer:dr,actions:hr,utils:fr,version:r.version}}function convertLegacyEditorModuleToVetraEditorModule(r,e){const M=e?.apps?.find(fr=>fr.driveEditor===r.config.id)?.name,tr=r.config.id,rr=tr.split("-").map(fr=>fr.charAt(0).toUpperCase()+fr.slice(1)).join(" "),ir=M||r.config.name||rr,lr=r.documentTypes,dr=r.Component;return{id:tr,name:ir,documentTypes:lr,Component:dr}}function makeVetraPackageManifest(r){const{id:e,name:M,description:tr,category:rr,author:ir,modules:lr}=r;return{id:e,name:M,description:tr,category:rr,author:ir,modules:makeVetraPackageManifestModulesEntry(lr)}}function makeVetraPackageManifestModulesEntry(r){return Object.entries(r).reduce((e,[M,tr])=>(e[M]=tr.map(rr=>({id:rr.id,name:rr.name})),e),{})}const connectCryptoEventFunctions=makePHEventFunctions("connectCrypto"),setConnectCrypto=connectCryptoEventFunctions.setValue,addConnectCryptoEventHandler=connectCryptoEventFunctions.addEventHandler,{setValue:setDid,addEventHandler:addDidEventHandler}=makePHEventFunctions("did"),{addEventHandler:addLoadingEventHandler}=makePHEventFunctions("loading"),{setValue:setLoginStatus,addEventHandler:addLoginStatusEventHandler}=makePHEventFunctions("loginStatus"),renownEventFunctions=makePHEventFunctions("renown"),useRenown=renownEventFunctions.useValue,setRenown=renownEventFunctions.setValue,addRenownEventHandler=renownEventFunctions.addEventHandler,userEventFunctions=makePHEventFunctions("user"),useUser=userEventFunctions.useValue,setUser=userEventFunctions.setValue,addUserEventHandler=userEventFunctions.addEventHandler,phGlobalEventHandlerRegisterFunctions={loading:addLoadingEventHandler,reactorClientModule:addReactorClientModuleEventHandler,reactorClient:addReactorClientEventHandler,features:addFeaturesEventHandler,modal:addModalEventHandler,connectCrypto:addConnectCryptoEventHandler,did:addDidEventHandler,renown:addRenownEventHandler,loginStatus:addLoginStatusEventHandler,user:addUserEventHandler,drives:addDrivesEventHandler,documentCache:addDocumentCacheEventHandler,selectedDriveId:()=>{addSelectedDriveIdEventHandler(),addSetSelectedDriveOnPopStateEventHandler(),addResetSelectedNodeEventHandler()},selectedNodeId:()=>{addSelectedNodeIdEventHandler(),addSetSelectedNodeOnPopStateEventHandler()},vetraPackages:addVetraPackagesEventHandler,selectedTimelineRevision:addSelectedTimelineRevisionEventHandler,revisionHistoryVisible:addRevisionHistoryVisibleEventHandler,selectedTimelineItem:addSelectedTimelineItemEventHandler,routerBasename:addRouterBasenameEventHandler,version:addVersionEventHandler,logLevel:addLogLevelEventHandler,requiresHardRefresh:addRequiresHardRefreshEventHandler,warnOutdatedApp:addWarnOutdatedAppEventHandler,studioMode:addStudioModeEventHandler,basePath:addBasePathEventHandler,versionCheckInterval:addVersionCheckIntervalEventHandler,cliVersion:addCliVersionEventHandler,fileUploadOperationsChunkSize:addFileUploadOperationsChunkSizeEventHandler,isDocumentModelSelectionSettingsEnabled:addIsDocumentModelSelectionSettingsEnabledEventHandler,gaTrackingId:addGaTrackingIdEventHandler,allowList:addAllowListEventHandler,defaultDrivesUrl:addDefaultDrivesUrlEventHandler,drivesPreserveStrategy:addDrivesPreserveStrategyEventHandler,allowedDocumentTypes:addAllowedDocumentTypesEventHandler,enabledEditors:addEnabledEditorsEventHandler,disabledEditors:addDisabledEditorsEventHandler,isAddDriveEnabled:addIsAddDriveEnabledEventHandler,isLocalDrivesEnabled:addIsLocalDrivesEnabledEventHandler,isPublicDrivesEnabled:addIsPublicDrivesEnabledEventHandler,isAddPublicDrivesEnabled:addIsAddPublicDrivesEnabledEventHandler,isDeletePublicDrivesEnabled:addIsDeletePublicDrivesEnabledEventHandler,isCloudDrivesEnabled:addIsCloudDrivesEnabledEventHandler,isAddCloudDrivesEnabled:addIsAddCloudDrivesEnabledEventHandler,isDeleteCloudDrivesEnabled:addIsDeleteCloudDrivesEnabledEventHandler,isAddLocalDrivesEnabled:addIsAddLocalDrivesEnabledEventHandler,isDeleteLocalDrivesEnabled:addIsDeleteLocalDrivesEnabledEventHandler,isDragAndDropEnabled:addIsDragAndDropEnabledEventHandler,isExternalControlsEnabled:addIsExternalControlsEnabledEventHandler,isEditorDebugModeEnabled:addIsEditorDebugModeEnabledEventHandler,isEditorReadModeEnabled:addIsEditorReadModeEnabledEventHandler,isRelationalProcessorsEnabled:addIsRelationalProcessorsEnabledEventHandler,isExternalRelationalProcessorsEnabled:addIsExternalRelationalProcessorsEnabledEventHandler,isAnalyticsEnabled:addIsAnalyticsEnabledEventHandler,isAnalyticsExternalProcessorsEnabled:addIsAnalyticsExternalProcessorsEnabledEventHandler,analyticsDatabaseName:addAnalyticsDatabaseNameEventHandler,isAnalyticsDatabaseWorkerEnabled:addIsAnalyticsDatabaseWorkerEnabledEventHandler,isDiffAnalyticsEnabled:addIsDiffAnalyticsEnabledEventHandler,isDriveAnalyticsEnabled:addIsDriveAnalyticsEnabledEventHandler,renownUrl:addRenownUrlEventHandler,renownNetworkId:addRenownNetworkIdEventHandler,renownChainId:addRenownChainIdEventHandler,sentryRelease:addSentryReleaseEventHandler,sentryDsn:addSentryDsnEventHandler,sentryEnv:addSentryEnvEventHandler,isSentryTracingEnabled:addIsSentryTracingEnabledEventHandler,isExternalProcessorsEnabled:addIsExternalProcessorsEnabledEventHandler,isExternalPackagesEnabled:addIsExternalPackagesEnabledEventHandler,toast:addToastEventHandler};function addPHEventHandlers(){for(const r of Object.values(phGlobalEventHandlerRegisterFunctions))r()}const RENOWN_URL="https://www.renown.id",RENOWN_NETWORK_ID$1="eip155",RENOWN_CHAIN_ID$1="1";function openRenown(){const r=new URL(RENOWN_URL);r.searchParams.set("connect",window.ph?.did??""),r.searchParams.set("network",RENOWN_NETWORK_ID$1),r.searchParams.set("chain",RENOWN_CHAIN_ID$1);const e=new URL(window.location.pathname,window.location.origin);r.searchParams.set("returnUrl",e.toJSON()),window.open(r,"_self")?.focus()}async function login(r,e){if(e)try{setLoginStatus("checking");const M=e.user;if(M?.did&&(M.did===r||!r))return setLoginStatus("authorized"),setUser(M),M;if(!r){setLoginStatus("not-authorized");return}const tr=await e.login(r);return setLoginStatus("authorized"),setUser(tr),tr}catch(M){setLoginStatus("not-authorized"),logger$1.error("@error",M)}}async function logout(){setLoginStatus("initial"),setUser(void 0),await window.ph?.renown?.logout();const e=new URL(window.location.href);e.searchParams.has("user")&&(e.searchParams.delete("user"),window.history.replaceState(null,"",e.toString()))}function useGetSwitchboardLink(r){const[e]=useSelectedDrive(),M=useSyncList(),tr=reactExports.useMemo(()=>M.some(dr=>dr.collectionId===driveCollectionId("main",e.header.id)),[M,e]),rr=reactExports.useMemo(()=>{const dr=M.find(hr=>hr.collectionId===driveCollectionId("main",e.header.id));return dr?.channel instanceof GqlRequestChannel?dr.channel.config.url:null},[M,e]),ir=useRenown(),lr=useUser();return reactExports.useMemo(()=>!tr||!r?.header.id||!rr?null:async()=>{const dr=lr?.address?await ir?.getBearerToken({expiresIn:600,aud:rr}):void 0;return buildDocumentSubgraphUrl(rr,r.header.id,dr)},[tr,rr,r,lr,ir])}const useOnDropFile=r=>{const e=useSelectedDriveId(),M=useSelectedFolder(),tr=useDocumentTypes();return async(ir,lr,dr)=>{if(!e){console.warn("No selected drive - upload skipped");return}const hr=ir.name.replace(/\..+/gim,""),fr=M?.id;return await addFileWithProgress(ir,e,hr,fr,lr,tr,dr)}};function useUserPermissions(){const r=useUser(),e=useAllowList();return e?{isAllowedToCreateDocuments:e.includes(r?.address??""),isAllowedToEditDocuments:e.includes(r?.address??"")}:{isAllowedToCreateDocuments:!0,isAllowedToEditDocuments:!0}}async function dropTablesInSchema(r,e){await r.exec(`
107
+ DO $$
108
+ DECLARE
109
+ _schemaname text := '${e}';
110
+ _tablename text;
111
+ BEGIN
112
+ FOR _tablename IN SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = _schemaname LOOP
113
+ RAISE INFO 'Dropping table %.%', _schemaname, _tablename;
114
+ EXECUTE format('DROP TABLE %I.%I CASCADE;', _schemaname, _tablename);
115
+ END LOOP;
116
+ IF NOT FOUND THEN
117
+ RAISE WARNING 'Schema % does not exist', _schemaname;
118
+ END IF;
119
+ END $$;
120
+ `)}async function dropAllReactorStorage(r){await dropTablesInSchema(r,REACTOR_SCHEMA),await dropTablesInSchema(r,"public")}class ReactorClientDocumentCache{client;documents=new Map;batchPromises=new Map;listeners=new Map;unsubscribe=null;constructor(e){this.client=e,this.unsubscribe=e.subscribe({},M=>{this.handleDocumentChange(M)})}handleDocumentChange(e){if(e.type===DocumentChangeType.Deleted){const M=e.context?.childId;M&&this.handleDocumentDeleted(M)}else if(e.type===DocumentChangeType.Updated)for(const M of e.documents)this.handleDocumentUpdated(M.header.id).catch(console.warn)}handleDocumentDeleted(e){const M=this.listeners.get(e);this.documents.delete(e),this.invalidateBatchesContaining(e),M&&M.forEach(tr=>tr()),this.listeners.delete(e)}async handleDocumentUpdated(e){if(this.documents.has(e)){await this.get(e,!0);const M=this.listeners.get(e);M&&M.forEach(tr=>tr())}}invalidateBatchesContaining(e){for(const M of this.batchPromises.keys())M.split(",").includes(e)&&this.batchPromises.delete(M)}get(e,M){const tr=this.documents.get(e);if(tr&&(tr.status==="pending"||!M))return tr;const rr=this.client.get(e);return this.documents.set(e,addPromiseState(rr)),rr}getBatch(e){const M=e.join(","),tr=this.batchPromises.get(M),rr=e.some(fr=>!this.documents.has(fr)),ir=e.map(fr=>this.get(fr));if(rr){const fr=Promise.all(ir);return this.batchPromises.set(M,{promises:ir,promise:fr}),fr}if(tr&&ir.every((mr,_r)=>mr===tr.promises[_r]))return tr.promise;const lr=ir.map(fr=>readPromiseState(fr));if(lr.every(fr=>fr.status==="fulfilled")){const fr=lr.map(_r=>_r.value),mr=Promise.resolve(fr);return mr.status="fulfilled",mr.value=fr,this.batchPromises.set(M,{promises:ir,promise:mr}),mr}if(tr)return tr.promise;const hr=Promise.all(ir);return this.batchPromises.set(M,{promises:ir,promise:hr}),hr}subscribe(e,M){const tr=Array.isArray(e)?e:[e];for(const rr of tr){const ir=this.listeners.get(rr)??[];this.listeners.set(rr,[...ir,M])}return()=>{for(const rr of tr){const ir=this.listeners.get(rr)??[];this.listeners.set(rr,ir.filter(lr=>lr!==M))}}}dispose(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)}}const DEFAULT_RENOWN_URL="https://www.renown.id";function asUint8Array$1(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function allocUnsafe$1(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?asUint8Array$1(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function concat$1(r,e){e||(e=r.reduce((rr,ir)=>rr+ir.length,0));const M=allocUnsafe$1(e);let tr=0;for(const rr of r)M.set(rr,tr),tr+=rr.length;return asUint8Array$1(M)}const concat$2=Object.freeze(Object.defineProperty({__proto__:null,concat:concat$1},Symbol.toStringTag,{value:"Module"}));function base$2(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var M=new Uint8Array(256),tr=0;tr<M.length;tr++)M[tr]=255;for(var rr=0;rr<r.length;rr++){var ir=r.charAt(rr),lr=ir.charCodeAt(0);if(M[lr]!==255)throw new TypeError(ir+" is ambiguous");M[lr]=rr}var dr=r.length,hr=r.charAt(0),fr=Math.log(dr)/Math.log(256),mr=Math.log(256)/Math.log(dr);function _r(yr){if(yr instanceof Uint8Array||(ArrayBuffer.isView(yr)?yr=new Uint8Array(yr.buffer,yr.byteOffset,yr.byteLength):Array.isArray(yr)&&(yr=Uint8Array.from(yr))),!(yr instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(yr.length===0)return"";for(var br=0,Mr=0,vr=0,Sr=yr.length;vr!==Sr&&yr[vr]===0;)vr++,br++;for(var xr=(Sr-vr)*mr+1>>>0,Ar=new Uint8Array(xr);vr!==Sr;){for(var Dr=yr[vr],Ir=0,kr=xr-1;(Dr!==0||Ir<Mr)&&kr!==-1;kr--,Ir++)Dr+=256*Ar[kr]>>>0,Ar[kr]=Dr%dr>>>0,Dr=Dr/dr>>>0;if(Dr!==0)throw new Error("Non-zero carry");Mr=Ir,vr++}for(var Or=xr-Mr;Or!==xr&&Ar[Or]===0;)Or++;for(var Fr=hr.repeat(br);Or<xr;++Or)Fr+=r.charAt(Ar[Or]);return Fr}function gr(yr){if(typeof yr!="string")throw new TypeError("Expected String");if(yr.length===0)return new Uint8Array;var br=0;if(yr[br]!==" "){for(var Mr=0,vr=0;yr[br]===hr;)Mr++,br++;for(var Sr=(yr.length-br)*fr+1>>>0,xr=new Uint8Array(Sr);yr[br];){var Ar=M[yr.charCodeAt(br)];if(Ar===255)return;for(var Dr=0,Ir=Sr-1;(Ar!==0||Dr<vr)&&Ir!==-1;Ir--,Dr++)Ar+=dr*xr[Ir]>>>0,xr[Ir]=Ar%256>>>0,Ar=Ar/256>>>0;if(Ar!==0)throw new Error("Non-zero carry");vr=Dr,br++}if(yr[br]!==" "){for(var kr=Sr-vr;kr!==Sr&&xr[kr]===0;)kr++;for(var Or=new Uint8Array(Mr+(Sr-kr)),Fr=Mr;kr!==Sr;)Or[Fr++]=xr[kr++];return Or}}}function wr(yr){var br=gr(yr);if(br)return br;throw new Error(`Non-${e} character`)}return{encode:_r,decodeUnsafe:gr,decode:wr}}var src$4=base$2,_brrp__multiformats_scope_baseX$1=src$4;const empty=new Uint8Array(0),toHex=r=>r.reduce((e,M)=>e+M.toString(16).padStart(2,"0"),""),fromHex=r=>{const e=r.match(/../g);return e?new Uint8Array(e.map(M=>parseInt(M,16))):empty},equals$1=(r,e)=>{if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let M=0;M<r.byteLength;M++)if(r[M]!==e[M])return!1;return!0},coerce$1=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},isBinary=r=>r instanceof ArrayBuffer||ArrayBuffer.isView(r),fromString$4=r=>new TextEncoder().encode(r),toString$4=r=>new TextDecoder().decode(r),bytes=Object.freeze(Object.defineProperty({__proto__:null,coerce:coerce$1,empty,equals:equals$1,fromHex,fromString:fromString$4,isBinary,toHex,toString:toString$4},Symbol.toStringTag,{value:"Module"}));let Encoder$1=class{constructor(e,M,tr){this.name=e,this.prefix=M,this.baseEncode=tr}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Decoder$1=class{constructor(e,M,tr){if(this.name=e,this.prefix=M,M.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=M.codePointAt(0),this.baseDecode=tr}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return or$1(this,e)}},ComposedDecoder$1=class{constructor(e){this.decoders=e}or(e){return or$1(this,e)}decode(e){const M=e[0],tr=this.decoders[M];if(tr)return tr.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const or$1=(r,e)=>new ComposedDecoder$1({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});let Codec$1=class{constructor(e,M,tr,rr){this.name=e,this.prefix=M,this.baseEncode=tr,this.baseDecode=rr,this.encoder=new Encoder$1(e,M,tr),this.decoder=new Decoder$1(e,M,rr)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const from$2=({name:r,prefix:e,encode:M,decode:tr})=>new Codec$1(r,e,M,tr),baseX$1=({prefix:r,name:e,alphabet:M})=>{const{encode:tr,decode:rr}=_brrp__multiformats_scope_baseX$1(M,e);return from$2({prefix:r,name:e,encode:tr,decode:ir=>coerce$1(rr(ir))})},decode$9=(r,e,M,tr)=>{const rr={};for(let mr=0;mr<e.length;++mr)rr[e[mr]]=mr;let ir=r.length;for(;r[ir-1]==="=";)--ir;const lr=new Uint8Array(ir*M/8|0);let dr=0,hr=0,fr=0;for(let mr=0;mr<ir;++mr){const _r=rr[r[mr]];if(_r===void 0)throw new SyntaxError(`Non-${tr} character`);hr=hr<<M|_r,dr+=M,dr>=8&&(dr-=8,lr[fr++]=255&hr>>dr)}if(dr>=M||255&hr<<8-dr)throw new SyntaxError("Unexpected end of data");return lr},encode$7=(r,e,M)=>{const tr=e[e.length-1]==="=",rr=(1<<M)-1;let ir="",lr=0,dr=0;for(let hr=0;hr<r.length;++hr)for(dr=dr<<8|r[hr],lr+=8;lr>M;)lr-=M,ir+=e[rr&dr>>lr];if(lr&&(ir+=e[rr&dr<<M-lr]),tr)for(;ir.length*M&7;)ir+="=";return ir},rfc4648$1=({name:r,prefix:e,bitsPerChar:M,alphabet:tr})=>from$2({prefix:e,name:r,encode(rr){return encode$7(rr,tr,M)},decode(rr){return decode$9(rr,tr,M,r)}}),identity$3=from$2({prefix:"\0",name:"identity",encode:r=>toString$4(r),decode:r=>fromString$4(r)}),identityBase$1=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$3},Symbol.toStringTag,{value:"Module"})),base2$2=rfc4648$1({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$3=Object.freeze(Object.defineProperty({__proto__:null,base2:base2$2},Symbol.toStringTag,{value:"Module"})),base8$2=rfc4648$1({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$3=Object.freeze(Object.defineProperty({__proto__:null,base8:base8$2},Symbol.toStringTag,{value:"Module"})),base10$2=baseX$1({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$3=Object.freeze(Object.defineProperty({__proto__:null,base10:base10$2},Symbol.toStringTag,{value:"Module"})),base16$2=rfc4648$1({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper$1=rfc4648$1({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$3=Object.freeze(Object.defineProperty({__proto__:null,base16:base16$2,base16upper:base16upper$1},Symbol.toStringTag,{value:"Module"})),base32$2=rfc4648$1({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper$1=rfc4648$1({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad$1=rfc4648$1({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper$1=rfc4648$1({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex$1=rfc4648$1({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper$1=rfc4648$1({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad$1=rfc4648$1({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper$1=rfc4648$1({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z$1=rfc4648$1({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$3=Object.freeze(Object.defineProperty({__proto__:null,base32:base32$2,base32hex:base32hex$1,base32hexpad:base32hexpad$1,base32hexpadupper:base32hexpadupper$1,base32hexupper:base32hexupper$1,base32pad:base32pad$1,base32padupper:base32padupper$1,base32upper:base32upper$1,base32z:base32z$1},Symbol.toStringTag,{value:"Module"})),base36$2=baseX$1({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper$1=baseX$1({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$3=Object.freeze(Object.defineProperty({__proto__:null,base36:base36$2,base36upper:base36upper$1},Symbol.toStringTag,{value:"Module"})),base58btc$1=baseX$1({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr$1=baseX$1({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58$1=Object.freeze(Object.defineProperty({__proto__:null,base58btc:base58btc$1,base58flickr:base58flickr$1},Symbol.toStringTag,{value:"Module"})),base64$2=rfc4648$1({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad$1=rfc4648$1({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url$1=rfc4648$1({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad$1=rfc4648$1({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$3=Object.freeze(Object.defineProperty({__proto__:null,base64:base64$2,base64pad:base64pad$1,base64url:base64url$1,base64urlpad:base64urlpad$1},Symbol.toStringTag,{value:"Module"})),alphabet$2=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),alphabetBytesToChars$1=alphabet$2.reduce((r,e,M)=>(r[M]=e,r),[]),alphabetCharsToBytes$1=alphabet$2.reduce((r,e,M)=>(r[e.codePointAt(0)]=M,r),[]);function encode$6(r){return r.reduce((e,M)=>(e+=alphabetBytesToChars$1[M],e),"")}function decode$8(r){const e=[];for(const M of r){const tr=alphabetCharsToBytes$1[M.codePointAt(0)];if(tr===void 0)throw new Error(`Non-base256emoji character: ${M}`);e.push(tr)}return new Uint8Array(e)}const base256emoji$2=from$2({prefix:"🚀",name:"base256emoji",encode:encode$6,decode:decode$8}),base256emoji$3=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:base256emoji$2},Symbol.toStringTag,{value:"Module"}));var encode_1$1=encode$5,MSB=128,MSBALL=-128,INT=Math.pow(2,31);function encode$5(r,e,M){e=e||[],M=M||0;for(var tr=M;r>=INT;)e[M++]=r&255|MSB,r/=128;for(;r&MSBALL;)e[M++]=r&255|MSB,r>>>=7;return e[M]=r|0,encode$5.bytes=M-tr+1,e}var decode$7=read,MSB$1=128,REST$1=127;function read(r,tr){var M=0,tr=tr||0,rr=0,ir=tr,lr,dr=r.length;do{if(ir>=dr)throw read.bytes=0,new RangeError("Could not decode varint");lr=r[ir++],M+=rr<28?(lr&REST$1)<<rr:(lr&REST$1)*Math.pow(2,rr),rr+=7}while(lr>=MSB$1);return read.bytes=ir-tr,M}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length$1=function(r){return r<N1?1:r<N2?2:r<N3?3:r<N4?4:r<N5?5:r<N6?6:r<N7?7:r<N8?8:r<N9?9:10},varint$3={encode:encode_1$1,decode:decode$7,encodingLength:length$1},_brrp_varint=varint$3;const decode$6=(r,e=0)=>[_brrp_varint.decode(r,e),_brrp_varint.decode.bytes],encodeTo=(r,e,M=0)=>(_brrp_varint.encode(r,e,M),e),encodingLength=r=>_brrp_varint.encodingLength(r),varint$2=Object.freeze(Object.defineProperty({__proto__:null,decode:decode$6,encodeTo,encodingLength},Symbol.toStringTag,{value:"Module"})),create=(r,e)=>{const M=e.byteLength,tr=encodingLength(r),rr=tr+encodingLength(M),ir=new Uint8Array(rr+M);return encodeTo(r,ir,0),encodeTo(M,ir,tr),ir.set(e,rr),new Digest(r,M,e,ir)},decode$5=r=>{const e=coerce$1(r),[M,tr]=decode$6(e),[rr,ir]=decode$6(e.subarray(tr)),lr=e.subarray(tr+ir);if(lr.byteLength!==rr)throw new Error("Incorrect length");return new Digest(M,rr,lr,e)},equals=(r,e)=>r===e?!0:r.code===e.code&&r.size===e.size&&equals$1(r.bytes,e.bytes);class Digest{constructor(e,M,tr,rr){this.code=e,this.size=M,this.digest=tr,this.bytes=rr}}const digest$1=Object.freeze(Object.defineProperty({__proto__:null,Digest,create,decode:decode$5,equals},Symbol.toStringTag,{value:"Module"})),from$1=({name:r,code:e,encode:M})=>new Hasher(r,e,M);class Hasher{constructor(e,M,tr){this.name=e,this.code=M,this.encode=tr}digest(e){if(e instanceof Uint8Array){const M=this.encode(e);return M instanceof Uint8Array?create(this.code,M):M.then(tr=>create(this.code,tr))}else throw Error("Unknown type, must be binary type")}}const hasher=Object.freeze(Object.defineProperty({__proto__:null,Hasher,from:from$1},Symbol.toStringTag,{value:"Module"})),sha=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),sha256$3=from$1({name:"sha2-256",code:18,encode:sha("SHA-256")}),sha512$1=from$1({name:"sha2-512",code:19,encode:sha("SHA-512")}),sha2=Object.freeze(Object.defineProperty({__proto__:null,sha256:sha256$3,sha512:sha512$1},Symbol.toStringTag,{value:"Module"})),code$2=0,name$2="identity",encode$4=coerce$1,digest=r=>create(code$2,encode$4(r)),identity$1={code:code$2,name:name$2,encode:encode$4,digest},identity$2=Object.freeze(Object.defineProperty({__proto__:null,identity:identity$1},Symbol.toStringTag,{value:"Module"})),name$1="raw",code$1=85,encode$3=r=>coerce$1(r),decode$4=r=>coerce$1(r),raw=Object.freeze(Object.defineProperty({__proto__:null,code:code$1,decode:decode$4,encode:encode$3,name:name$1},Symbol.toStringTag,{value:"Module"})),textEncoder=new TextEncoder,textDecoder=new TextDecoder,name="json",code=512,encode$2=r=>textEncoder.encode(JSON.stringify(r)),decode$3=r=>JSON.parse(textDecoder.decode(r)),json=Object.freeze(Object.defineProperty({__proto__:null,code,decode:decode$3,encode:encode$2,name},Symbol.toStringTag,{value:"Module"}));class CID{constructor(e,M,tr,rr){this.code=M,this.version=e,this.multihash=tr,this.bytes=rr,this.byteOffset=rr.byteOffset,this.byteLength=rr.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:hidden,byteLength:hidden,code:readonly,version:readonly,multihash:readonly,bytes:readonly,_baseCache:hidden,asCID:hidden})}toV0(){switch(this.version){case 0:return this;default:{const{code:e,multihash:M}=this;if(e!==DAG_PB_CODE)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(M.code!==SHA_256_CODE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return CID.createV0(M)}}}toV1(){switch(this.version){case 0:{const{code:e,digest:M}=this.multihash,tr=create(e,M);return CID.createV1(this.code,tr)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&equals(this.multihash,e.multihash)}toString(e){const{bytes:M,version:tr,_baseCache:rr}=this;return tr===0?toStringV0(M,rr,e||base58btc$1.encoder):toStringV1(M,rr,e||base32$2.encoder)}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return deprecate(/^0\.0/,IS_CID_DEPRECATION),!!(e&&(e[cidSymbol]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof CID)return e;if(e!=null&&e.asCID===e){const{version:M,code:tr,multihash:rr,bytes:ir}=e;return new CID(M,tr,rr,ir||encodeCID(M,tr,rr.bytes))}else if(e!=null&&e[cidSymbol]===!0){const{version:M,multihash:tr,code:rr}=e,ir=decode$5(tr);return CID.create(M,rr,ir)}else return null}static create(e,M,tr){if(typeof M!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(M!==DAG_PB_CODE)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);return new CID(e,M,tr,tr.bytes)}case 1:{const rr=encodeCID(e,M,tr.bytes);return new CID(e,M,tr,rr)}default:throw new Error("Invalid version")}}static createV0(e){return CID.create(0,DAG_PB_CODE,e)}static createV1(e,M){return CID.create(1,e,M)}static decode(e){const[M,tr]=CID.decodeFirst(e);if(tr.length)throw new Error("Incorrect length");return M}static decodeFirst(e){const M=CID.inspectBytes(e),tr=M.size-M.multihashSize,rr=coerce$1(e.subarray(tr,tr+M.multihashSize));if(rr.byteLength!==M.multihashSize)throw new Error("Incorrect length");const ir=rr.subarray(M.multihashSize-M.digestSize),lr=new Digest(M.multihashCode,M.digestSize,ir,rr);return[M.version===0?CID.createV0(lr):CID.createV1(M.codec,lr),e.subarray(M.size)]}static inspectBytes(e){let M=0;const tr=()=>{const[_r,gr]=decode$6(e.subarray(M));return M+=gr,_r};let rr=tr(),ir=DAG_PB_CODE;if(rr===18?(rr=0,M=0):rr===1&&(ir=tr()),rr!==0&&rr!==1)throw new RangeError(`Invalid CID version ${rr}`);const lr=M,dr=tr(),hr=tr(),fr=M+hr,mr=fr-lr;return{version:rr,codec:ir,multihashCode:dr,digestSize:hr,multihashSize:mr,size:fr}}static parse(e,M){const[tr,rr]=parseCIDtoBytes(e,M),ir=CID.decode(rr);return ir._baseCache.set(tr,e),ir}}const parseCIDtoBytes=(r,e)=>{switch(r[0]){case"Q":{const M=e||base58btc$1;return[base58btc$1.prefix,M.decode(`${base58btc$1.prefix}${r}`)]}case base58btc$1.prefix:{const M=e||base58btc$1;return[base58btc$1.prefix,M.decode(r)]}case base32$2.prefix:{const M=e||base32$2;return[base32$2.prefix,M.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},toStringV0=(r,e,M)=>{const{prefix:tr}=M;if(tr!==base58btc$1.prefix)throw Error(`Cannot string encode V0 in ${M.name} encoding`);const rr=e.get(tr);if(rr==null){const ir=M.encode(r).slice(1);return e.set(tr,ir),ir}else return rr},toStringV1=(r,e,M)=>{const{prefix:tr}=M,rr=e.get(tr);if(rr==null){const ir=M.encode(r);return e.set(tr,ir),ir}else return rr},DAG_PB_CODE=112,SHA_256_CODE=18,encodeCID=(r,e,M)=>{const tr=encodingLength(r),rr=tr+encodingLength(e),ir=new Uint8Array(rr+M.byteLength);return encodeTo(r,ir,0),encodeTo(e,ir,tr),ir.set(M,rr),ir},cidSymbol=Symbol.for("@ipld/js-cid/CID"),readonly={writable:!1,configurable:!1,enumerable:!0},hidden={writable:!1,enumerable:!1,configurable:!1},version="0.0.0-dev",deprecate=(r,e)=>{if(r.test(version))console.warn(e);else throw new Error(e)},IS_CID_DEPRECATION=`CID.isCID(v) is deprecated and will be removed in the next major release.
121
+ Following code pattern:
122
+
123
+ if (CID.isCID(value)) {
124
+ doSomethingWithCID(value)
125
+ }
126
+
127
+ Is replaced with:
128
+
129
+ const cid = CID.asCID(value)
130
+ if (cid) {
131
+ // Make sure to use cid instead of value
132
+ doSomethingWithCID(cid)
133
+ }
134
+ `,bases$1={...identityBase$1,...base2$3,...base8$3,...base10$3,...base16$3,...base32$3,...base36$3,...base58$1,...base64$3,...base256emoji$3},hashes={...sha2,...identity$2},codecs={raw,json},basics=Object.freeze(Object.defineProperty({__proto__:null,CID,bases:bases$1,bytes,codecs,digest:digest$1,hasher,hashes,varint:varint$2},Symbol.toStringTag,{value:"Module"}));function createCodec$1(r,e,M,tr){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:M},decoder:{decode:tr}}}const string$1=createCodec$1("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ascii$1=createCodec$1("ascii","a",r=>{let e="a";for(let M=0;M<r.length;M++)e+=String.fromCharCode(r[M]);return e},r=>{r=r.substring(1);const e=allocUnsafe$1(r.length);for(let M=0;M<r.length;M++)e[M]=r.charCodeAt(M);return e}),BASES$1={utf8:string$1,"utf-8":string$1,hex:bases$1.base16,latin1:ascii$1,ascii:ascii$1,binary:ascii$1,...bases$1};function fromString$2(r,e="utf8"){const M=BASES$1[e];if(!M)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?asUint8Array$1(globalThis.Buffer.from(r,"utf-8")):M.decoder.decode(`${M.prefix}${r}`)}const fromString$3=Object.freeze(Object.defineProperty({__proto__:null,fromString:fromString$2},Symbol.toStringTag,{value:"Module"}));function toString$2(r,e="utf8"){const M=BASES$1[e];if(!M)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):M.encoder.encode(r).substring(1)}const toString$3=Object.freeze(Object.defineProperty({__proto__:null,toString:toString$2},Symbol.toStringTag,{value:"Module"})),crypto$1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function isBytes$1(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function anumber$1(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function abytes(r,...e){if(!isBytes$1(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function ahash(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");anumber$1(r.outputLen),anumber$1(r.blockLen)}function aexists(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function aoutput(r,e){abytes(r);const M=e.outputLen;if(r.length<M)throw new Error("digestInto() expects output buffer of length at least "+M)}function u32(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function clean(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function createView(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function rotr(r,e){return r<<32-e|r>>>e}function rotl(r,e){return r<<e|r>>>32-e>>>0}const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function byteSwap(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function byteSwap32(r){for(let e=0;e<r.length;e++)r[e]=byteSwap(r[e]);return r}const swap32IfBE=isLE?r=>r:byteSwap32,hasHexBuiltin=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hexes=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$1(r){if(abytes(r),hasHexBuiltin)return r.toHex();let e="";for(let M=0;M<r.length;M++)e+=hexes[r[M]];return e}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(r){if(r>=asciis._0&&r<=asciis._9)return r-asciis._0;if(r>=asciis.A&&r<=asciis.F)return r-(asciis.A-10);if(r>=asciis.a&&r<=asciis.f)return r-(asciis.a-10)}function hexToBytes$1(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(hasHexBuiltin)return Uint8Array.fromHex(r);const e=r.length,M=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const tr=new Uint8Array(M);for(let rr=0,ir=0;rr<M;rr++,ir+=2){const lr=asciiToBase16(r.charCodeAt(ir)),dr=asciiToBase16(r.charCodeAt(ir+1));if(lr===void 0||dr===void 0){const hr=r[ir]+r[ir+1];throw new Error('hex string expected, got non-hex character "'+hr+'" at index '+ir)}tr[rr]=lr*16+dr}return tr}function utf8ToBytes(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function toBytes(r){return typeof r=="string"&&(r=utf8ToBytes(r)),abytes(r),r}function concatBytes(...r){let e=0;for(let tr=0;tr<r.length;tr++){const rr=r[tr];abytes(rr),e+=rr.length}const M=new Uint8Array(e);for(let tr=0,rr=0;tr<r.length;tr++){const ir=r[tr];M.set(ir,rr),rr+=ir.length}return M}class Hash{}function createHasher(r){const e=tr=>r().update(toBytes(tr)).digest(),M=r();return e.outputLen=M.outputLen,e.blockLen=M.blockLen,e.create=()=>r(),e}function randomBytes(r=32){if(crypto$1&&typeof crypto$1.getRandomValues=="function")return crypto$1.getRandomValues(new Uint8Array(r));if(crypto$1&&typeof crypto$1.randomBytes=="function")return Uint8Array.from(crypto$1.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(r,e,M,tr){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,M,tr);const rr=BigInt(32),ir=BigInt(4294967295),lr=Number(M>>rr&ir),dr=Number(M&ir),hr=tr?4:0,fr=tr?0:4;r.setUint32(e+hr,lr,tr),r.setUint32(e+fr,dr,tr)}function Chi(r,e,M){return r&e^~r&M}function Maj(r,e,M){return r&e^r&M^e&M}class HashMD extends Hash{constructor(e,M,tr,rr){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=M,this.padOffset=tr,this.isLE=rr,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this),e=toBytes(e),abytes(e);const{view:M,buffer:tr,blockLen:rr}=this,ir=e.length;for(let lr=0;lr<ir;){const dr=Math.min(rr-this.pos,ir-lr);if(dr===rr){const hr=createView(e);for(;rr<=ir-lr;lr+=rr)this.process(hr,lr);continue}tr.set(e.subarray(lr,lr+dr),this.pos),this.pos+=dr,lr+=dr,this.pos===rr&&(this.process(M,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){aexists(this),aoutput(e,this),this.finished=!0;const{buffer:M,view:tr,blockLen:rr,isLE:ir}=this;let{pos:lr}=this;M[lr++]=128,clean(this.buffer.subarray(lr)),this.padOffset>rr-lr&&(this.process(tr,0),lr=0);for(let _r=lr;_r<rr;_r++)M[_r]=0;setBigUint64(tr,rr-8,BigInt(this.length*8),ir),this.process(tr,0);const dr=createView(e),hr=this.outputLen;if(hr%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const fr=hr/4,mr=this.get();if(fr>mr.length)throw new Error("_sha2: outputLen bigger than state");for(let _r=0;_r<fr;_r++)dr.setUint32(4*_r,mr[_r],ir)}digest(){const{buffer:e,outputLen:M}=this;this.digestInto(e);const tr=e.slice(0,M);return this.destroy(),tr}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:M,buffer:tr,length:rr,finished:ir,destroyed:lr,pos:dr}=this;return e.destroyed=lr,e.finished=ir,e.length=rr,e.pos=dr,rr%M&&e.buffer.set(tr),e}clone(){return this._cloneInto()}}const SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(r,e=!1){return e?{h:Number(r&U32_MASK64),l:Number(r>>_32n&U32_MASK64)}:{h:Number(r>>_32n&U32_MASK64)|0,l:Number(r&U32_MASK64)|0}}function split(r,e=!1){const M=r.length;let tr=new Uint32Array(M),rr=new Uint32Array(M);for(let ir=0;ir<M;ir++){const{h:lr,l:dr}=fromBig(r[ir],e);[tr[ir],rr[ir]]=[lr,dr]}return[tr,rr]}const shrSH=(r,e,M)=>r>>>M,shrSL=(r,e,M)=>r<<32-M|e>>>M,rotrSH=(r,e,M)=>r>>>M|e<<32-M,rotrSL=(r,e,M)=>r<<32-M|e>>>M,rotrBH=(r,e,M)=>r<<64-M|e>>>M-32,rotrBL=(r,e,M)=>r>>>M-32|e<<64-M,rotlSH=(r,e,M)=>r<<M|e>>>32-M,rotlSL=(r,e,M)=>e<<M|r>>>32-M,rotlBH=(r,e,M)=>e<<M-32|r>>>64-M,rotlBL=(r,e,M)=>r<<M-32|e>>>64-M;function add(r,e,M,tr){const rr=(e>>>0)+(tr>>>0);return{h:r+M+(rr/2**32|0)|0,l:rr|0}}const add3L=(r,e,M)=>(r>>>0)+(e>>>0)+(M>>>0),add3H=(r,e,M,tr)=>e+M+tr+(r/2**32|0)|0,add4L=(r,e,M,tr)=>(r>>>0)+(e>>>0)+(M>>>0)+(tr>>>0),add4H=(r,e,M,tr,rr)=>e+M+tr+rr+(r/2**32|0)|0,add5L=(r,e,M,tr,rr)=>(r>>>0)+(e>>>0)+(M>>>0)+(tr>>>0)+(rr>>>0),add5H=(r,e,M,tr,rr,ir)=>e+M+tr+rr+ir+(r/2**32|0)|0,SHA256_K=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(e=32){super(64,e,8,!1),this.A=SHA256_IV[0]|0,this.B=SHA256_IV[1]|0,this.C=SHA256_IV[2]|0,this.D=SHA256_IV[3]|0,this.E=SHA256_IV[4]|0,this.F=SHA256_IV[5]|0,this.G=SHA256_IV[6]|0,this.H=SHA256_IV[7]|0}get(){const{A:e,B:M,C:tr,D:rr,E:ir,F:lr,G:dr,H:hr}=this;return[e,M,tr,rr,ir,lr,dr,hr]}set(e,M,tr,rr,ir,lr,dr,hr){this.A=e|0,this.B=M|0,this.C=tr|0,this.D=rr|0,this.E=ir|0,this.F=lr|0,this.G=dr|0,this.H=hr|0}process(e,M){for(let _r=0;_r<16;_r++,M+=4)SHA256_W[_r]=e.getUint32(M,!1);for(let _r=16;_r<64;_r++){const gr=SHA256_W[_r-15],wr=SHA256_W[_r-2],yr=rotr(gr,7)^rotr(gr,18)^gr>>>3,br=rotr(wr,17)^rotr(wr,19)^wr>>>10;SHA256_W[_r]=br+SHA256_W[_r-7]+yr+SHA256_W[_r-16]|0}let{A:tr,B:rr,C:ir,D:lr,E:dr,F:hr,G:fr,H:mr}=this;for(let _r=0;_r<64;_r++){const gr=rotr(dr,6)^rotr(dr,11)^rotr(dr,25),wr=mr+gr+Chi(dr,hr,fr)+SHA256_K[_r]+SHA256_W[_r]|0,br=(rotr(tr,2)^rotr(tr,13)^rotr(tr,22))+Maj(tr,rr,ir)|0;mr=fr,fr=hr,hr=dr,dr=lr+wr|0,lr=ir,ir=rr,rr=tr,tr=wr+br|0}tr=tr+this.A|0,rr=rr+this.B|0,ir=ir+this.C|0,lr=lr+this.D|0,dr=dr+this.E|0,hr=hr+this.F|0,fr=fr+this.G|0,mr=mr+this.H|0,this.set(tr,rr,ir,lr,dr,hr,fr,mr)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}const K512=split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),SHA512_Kh=K512[0],SHA512_Kl=K512[1],SHA512_W_H=new Uint32Array(80),SHA512_W_L=new Uint32Array(80);class SHA512 extends HashMD{constructor(e=64){super(128,e,16,!1),this.Ah=SHA512_IV[0]|0,this.Al=SHA512_IV[1]|0,this.Bh=SHA512_IV[2]|0,this.Bl=SHA512_IV[3]|0,this.Ch=SHA512_IV[4]|0,this.Cl=SHA512_IV[5]|0,this.Dh=SHA512_IV[6]|0,this.Dl=SHA512_IV[7]|0,this.Eh=SHA512_IV[8]|0,this.El=SHA512_IV[9]|0,this.Fh=SHA512_IV[10]|0,this.Fl=SHA512_IV[11]|0,this.Gh=SHA512_IV[12]|0,this.Gl=SHA512_IV[13]|0,this.Hh=SHA512_IV[14]|0,this.Hl=SHA512_IV[15]|0}get(){const{Ah:e,Al:M,Bh:tr,Bl:rr,Ch:ir,Cl:lr,Dh:dr,Dl:hr,Eh:fr,El:mr,Fh:_r,Fl:gr,Gh:wr,Gl:yr,Hh:br,Hl:Mr}=this;return[e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr,wr,yr,br,Mr]}set(e,M,tr,rr,ir,lr,dr,hr,fr,mr,_r,gr,wr,yr,br,Mr){this.Ah=e|0,this.Al=M|0,this.Bh=tr|0,this.Bl=rr|0,this.Ch=ir|0,this.Cl=lr|0,this.Dh=dr|0,this.Dl=hr|0,this.Eh=fr|0,this.El=mr|0,this.Fh=_r|0,this.Fl=gr|0,this.Gh=wr|0,this.Gl=yr|0,this.Hh=br|0,this.Hl=Mr|0}process(e,M){for(let xr=0;xr<16;xr++,M+=4)SHA512_W_H[xr]=e.getUint32(M),SHA512_W_L[xr]=e.getUint32(M+=4);for(let xr=16;xr<80;xr++){const Ar=SHA512_W_H[xr-15]|0,Dr=SHA512_W_L[xr-15]|0,Ir=rotrSH(Ar,Dr,1)^rotrSH(Ar,Dr,8)^shrSH(Ar,Dr,7),kr=rotrSL(Ar,Dr,1)^rotrSL(Ar,Dr,8)^shrSL(Ar,Dr,7),Or=SHA512_W_H[xr-2]|0,Fr=SHA512_W_L[xr-2]|0,Jr=rotrSH(Or,Fr,19)^rotrBH(Or,Fr,61)^shrSH(Or,Fr,6),$n=rotrSL(Or,Fr,19)^rotrBL(Or,Fr,61)^shrSL(Or,Fr,6),Gr=add4L(kr,$n,SHA512_W_L[xr-7],SHA512_W_L[xr-16]),Lr=add4H(Gr,Ir,Jr,SHA512_W_H[xr-7],SHA512_W_H[xr-16]);SHA512_W_H[xr]=Lr|0,SHA512_W_L[xr]=Gr|0}let{Ah:tr,Al:rr,Bh:ir,Bl:lr,Ch:dr,Cl:hr,Dh:fr,Dl:mr,Eh:_r,El:gr,Fh:wr,Fl:yr,Gh:br,Gl:Mr,Hh:vr,Hl:Sr}=this;for(let xr=0;xr<80;xr++){const Ar=rotrSH(_r,gr,14)^rotrSH(_r,gr,18)^rotrBH(_r,gr,41),Dr=rotrSL(_r,gr,14)^rotrSL(_r,gr,18)^rotrBL(_r,gr,41),Ir=_r&wr^~_r&br,kr=gr&yr^~gr&Mr,Or=add5L(Sr,Dr,kr,SHA512_Kl[xr],SHA512_W_L[xr]),Fr=add5H(Or,vr,Ar,Ir,SHA512_Kh[xr],SHA512_W_H[xr]),Jr=Or|0,$n=rotrSH(tr,rr,28)^rotrBH(tr,rr,34)^rotrBH(tr,rr,39),Gr=rotrSL(tr,rr,28)^rotrBL(tr,rr,34)^rotrBL(tr,rr,39),Lr=tr&ir^tr&dr^ir&dr,$r=rr&lr^rr&hr^lr&hr;vr=br|0,Sr=Mr|0,br=wr|0,Mr=yr|0,wr=_r|0,yr=gr|0,{h:_r,l:gr}=add(fr|0,mr|0,Fr|0,Jr|0),fr=dr|0,mr=hr|0,dr=ir|0,hr=lr|0,ir=tr|0,lr=rr|0;const zr=add3L(Jr,Gr,$r);tr=add3H(zr,Fr,$n,Lr),rr=zr|0}({h:tr,l:rr}=add(this.Ah|0,this.Al|0,tr|0,rr|0)),{h:ir,l:lr}=add(this.Bh|0,this.Bl|0,ir|0,lr|0),{h:dr,l:hr}=add(this.Ch|0,this.Cl|0,dr|0,hr|0),{h:fr,l:mr}=add(this.Dh|0,this.Dl|0,fr|0,mr|0),{h:_r,l:gr}=add(this.Eh|0,this.El|0,_r|0,gr|0),{h:wr,l:yr}=add(this.Fh|0,this.Fl|0,wr|0,yr|0),{h:br,l:Mr}=add(this.Gh|0,this.Gl|0,br|0,Mr|0),{h:vr,l:Sr}=add(this.Hh|0,this.Hl|0,vr|0,Sr|0),this.set(tr,rr,ir,lr,dr,hr,fr,mr,_r,gr,wr,yr,br,Mr,vr,Sr)}roundClean(){clean(SHA512_W_H,SHA512_W_L)}destroy(){clean(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class SHA384 extends SHA512{constructor(){super(48),this.Ah=SHA384_IV[0]|0,this.Al=SHA384_IV[1]|0,this.Bh=SHA384_IV[2]|0,this.Bl=SHA384_IV[3]|0,this.Ch=SHA384_IV[4]|0,this.Cl=SHA384_IV[5]|0,this.Dh=SHA384_IV[6]|0,this.Dl=SHA384_IV[7]|0,this.Eh=SHA384_IV[8]|0,this.El=SHA384_IV[9]|0,this.Fh=SHA384_IV[10]|0,this.Fl=SHA384_IV[11]|0,this.Gh=SHA384_IV[12]|0,this.Gl=SHA384_IV[13]|0,this.Hh=SHA384_IV[14]|0,this.Hl=SHA384_IV[15]|0}}const sha256$2=createHasher(()=>new SHA256),sha512=createHasher(()=>new SHA512),sha384=createHasher(()=>new SHA384);const _0n$5=BigInt(0),_1n$6=BigInt(1);function _abool2(r,e=""){if(typeof r!="boolean"){const M=e&&`"${e}"`;throw new Error(M+"expected boolean, got type="+typeof r)}return r}function _abytes2(r,e,M=""){const tr=isBytes$1(r),rr=r?.length,ir=e!==void 0;if(!tr||ir&&rr!==e){const lr=M&&`"${M}" `,dr=ir?` of length ${e}`:"",hr=tr?`length=${rr}`:`type=${typeof r}`;throw new Error(lr+"expected Uint8Array"+dr+", got "+hr)}return r}function numberToHexUnpadded(r){const e=r.toString(16);return e.length&1?"0"+e:e}function hexToNumber(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?_0n$5:BigInt("0x"+r)}function bytesToNumberBE(r){return hexToNumber(bytesToHex$1(r))}function bytesToNumberLE(r){return abytes(r),hexToNumber(bytesToHex$1(Uint8Array.from(r).reverse()))}function numberToBytesBE(r,e){return hexToBytes$1(r.toString(16).padStart(e*2,"0"))}function numberToBytesLE(r,e){return numberToBytesBE(r,e).reverse()}function numberToVarBytesBE$1(r){return hexToBytes$1(numberToHexUnpadded(r))}function ensureBytes(r,e,M){let tr;if(typeof e=="string")try{tr=hexToBytes$1(e)}catch(ir){throw new Error(r+" must be hex string or Uint8Array, cause: "+ir)}else if(isBytes$1(e))tr=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");const rr=tr.length;if(typeof M=="number"&&rr!==M)throw new Error(r+" of length "+M+" expected, got "+rr);return tr}function copyBytes(r){return Uint8Array.from(r)}const isPosBig=r=>typeof r=="bigint"&&_0n$5<=r;function inRange(r,e,M){return isPosBig(r)&&isPosBig(e)&&isPosBig(M)&&e<=r&&r<M}function aInRange(r,e,M,tr){if(!inRange(e,M,tr))throw new Error("expected valid "+r+": "+M+" <= n < "+tr+", got "+e)}function bitLen(r){let e;for(e=0;r>_0n$5;r>>=_1n$6,e+=1);return e}const bitMask=r=>(_1n$6<<BigInt(r))-_1n$6;function createHmacDrbg(r,e,M){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof M!="function")throw new Error("hmacFn must be a function");const tr=wr=>new Uint8Array(wr),rr=wr=>Uint8Array.of(wr);let ir=tr(r),lr=tr(r),dr=0;const hr=()=>{ir.fill(1),lr.fill(0),dr=0},fr=(...wr)=>M(lr,ir,...wr),mr=(wr=tr(0))=>{lr=fr(rr(0),wr),ir=fr(),wr.length!==0&&(lr=fr(rr(1),wr),ir=fr())},_r=()=>{if(dr++>=1e3)throw new Error("drbg: tried 1000 values");let wr=0;const yr=[];for(;wr<e;){ir=fr();const br=ir.slice();yr.push(br),wr+=ir.length}return concatBytes(...yr)};return(wr,yr)=>{hr(),mr(wr);let br;for(;!(br=yr(_r()));)mr();return hr(),br}}function _validateObject(r,e,M={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function tr(rr,ir,lr){const dr=r[rr];if(lr&&dr===void 0)return;const hr=typeof dr;if(hr!==ir||dr===null)throw new Error(`param "${rr}" is invalid: expected ${ir}, got ${hr}`)}Object.entries(e).forEach(([rr,ir])=>tr(rr,ir,!1)),Object.entries(M).forEach(([rr,ir])=>tr(rr,ir,!0))}function memoized(r){const e=new WeakMap;return(M,...tr)=>{const rr=e.get(M);if(rr!==void 0)return rr;const ir=r(M,...tr);return e.set(M,ir),ir}}const _0n$4=BigInt(0),_1n$5=BigInt(1),_2n$5=BigInt(2),_3n$1=BigInt(3),_4n$1=BigInt(4),_5n$1=BigInt(5),_7n$1=BigInt(7),_8n$2=BigInt(8),_9n=BigInt(9),_16n=BigInt(16);function mod(r,e){const M=r%e;return M>=_0n$4?M:e+M}function pow2(r,e,M){let tr=r;for(;e-- >_0n$4;)tr*=tr,tr%=M;return tr}function invert(r,e){if(r===_0n$4)throw new Error("invert: expected non-zero number");if(e<=_0n$4)throw new Error("invert: expected positive modulus, got "+e);let M=mod(r,e),tr=e,rr=_0n$4,ir=_1n$5;for(;M!==_0n$4;){const dr=tr/M,hr=tr%M,fr=rr-ir*dr;tr=M,M=hr,rr=ir,ir=fr}if(tr!==_1n$5)throw new Error("invert: does not exist");return mod(rr,e)}function assertIsSquare(r,e,M){if(!r.eql(r.sqr(e),M))throw new Error("Cannot find square root")}function sqrt3mod4(r,e){const M=(r.ORDER+_1n$5)/_4n$1,tr=r.pow(e,M);return assertIsSquare(r,tr,e),tr}function sqrt5mod8(r,e){const M=(r.ORDER-_5n$1)/_8n$2,tr=r.mul(e,_2n$5),rr=r.pow(tr,M),ir=r.mul(e,rr),lr=r.mul(r.mul(ir,_2n$5),rr),dr=r.mul(ir,r.sub(lr,r.ONE));return assertIsSquare(r,dr,e),dr}function sqrt9mod16(r){const e=Field(r),M=tonelliShanks(r),tr=M(e,e.neg(e.ONE)),rr=M(e,tr),ir=M(e,e.neg(tr)),lr=(r+_7n$1)/_16n;return(dr,hr)=>{let fr=dr.pow(hr,lr),mr=dr.mul(fr,tr);const _r=dr.mul(fr,rr),gr=dr.mul(fr,ir),wr=dr.eql(dr.sqr(mr),hr),yr=dr.eql(dr.sqr(_r),hr);fr=dr.cmov(fr,mr,wr),mr=dr.cmov(gr,_r,yr);const br=dr.eql(dr.sqr(mr),hr),Mr=dr.cmov(fr,mr,br);return assertIsSquare(dr,Mr,hr),Mr}}function tonelliShanks(r){if(r<_3n$1)throw new Error("sqrt is not defined for small field");let e=r-_1n$5,M=0;for(;e%_2n$5===_0n$4;)e/=_2n$5,M++;let tr=_2n$5;const rr=Field(r);for(;FpLegendre(rr,tr)===1;)if(tr++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(M===1)return sqrt3mod4;let ir=rr.pow(tr,e);const lr=(e+_1n$5)/_2n$5;return function(hr,fr){if(hr.is0(fr))return fr;if(FpLegendre(hr,fr)!==1)throw new Error("Cannot find square root");let mr=M,_r=hr.mul(hr.ONE,ir),gr=hr.pow(fr,e),wr=hr.pow(fr,lr);for(;!hr.eql(gr,hr.ONE);){if(hr.is0(gr))return hr.ZERO;let yr=1,br=hr.sqr(gr);for(;!hr.eql(br,hr.ONE);)if(yr++,br=hr.sqr(br),yr===mr)throw new Error("Cannot find square root");const Mr=_1n$5<<BigInt(mr-yr-1),vr=hr.pow(_r,Mr);mr=yr,_r=hr.sqr(vr),gr=hr.mul(gr,_r),wr=hr.mul(wr,vr)}return wr}}function FpSqrt(r){return r%_4n$1===_3n$1?sqrt3mod4:r%_8n$2===_5n$1?sqrt5mod8:r%_16n===_9n?sqrt9mod16(r):tonelliShanks(r)}const isNegativeLE=(r,e)=>(mod(r,e)&_1n$5)===_1n$5,FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(r){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},M=FIELD_FIELDS.reduce((tr,rr)=>(tr[rr]="function",tr),e);return _validateObject(r,M),r}function FpPow(r,e,M){if(M<_0n$4)throw new Error("invalid exponent, negatives unsupported");if(M===_0n$4)return r.ONE;if(M===_1n$5)return e;let tr=r.ONE,rr=e;for(;M>_0n$4;)M&_1n$5&&(tr=r.mul(tr,rr)),rr=r.sqr(rr),M>>=_1n$5;return tr}function FpInvertBatch(r,e,M=!1){const tr=new Array(e.length).fill(M?r.ZERO:void 0),rr=e.reduce((lr,dr,hr)=>r.is0(dr)?lr:(tr[hr]=lr,r.mul(lr,dr)),r.ONE),ir=r.inv(rr);return e.reduceRight((lr,dr,hr)=>r.is0(dr)?lr:(tr[hr]=r.mul(lr,tr[hr]),r.mul(lr,dr)),ir),tr}function FpLegendre(r,e){const M=(r.ORDER-_1n$5)/_2n$5,tr=r.pow(e,M),rr=r.eql(tr,r.ONE),ir=r.eql(tr,r.ZERO),lr=r.eql(tr,r.neg(r.ONE));if(!rr&&!ir&&!lr)throw new Error("invalid Legendre symbol result");return rr?1:ir?0:-1}function nLength(r,e){e!==void 0&&anumber$1(e);const M=e!==void 0?e:r.toString(2).length,tr=Math.ceil(M/8);return{nBitLength:M,nByteLength:tr}}function Field(r,e,M=!1,tr={}){if(r<=_0n$4)throw new Error("invalid field: expected ORDER > 0, got "+r);let rr,ir,lr=!1,dr;if(typeof e=="object"&&e!=null){if(tr.sqrt||M)throw new Error("cannot specify opts in two arguments");const gr=e;gr.BITS&&(rr=gr.BITS),gr.sqrt&&(ir=gr.sqrt),typeof gr.isLE=="boolean"&&(M=gr.isLE),typeof gr.modFromBytes=="boolean"&&(lr=gr.modFromBytes),dr=gr.allowedLengths}else typeof e=="number"&&(rr=e),tr.sqrt&&(ir=tr.sqrt);const{nBitLength:hr,nByteLength:fr}=nLength(r,rr);if(fr>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let mr;const _r=Object.freeze({ORDER:r,isLE:M,BITS:hr,BYTES:fr,MASK:bitMask(hr),ZERO:_0n$4,ONE:_1n$5,allowedLengths:dr,create:gr=>mod(gr,r),isValid:gr=>{if(typeof gr!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof gr);return _0n$4<=gr&&gr<r},is0:gr=>gr===_0n$4,isValidNot0:gr=>!_r.is0(gr)&&_r.isValid(gr),isOdd:gr=>(gr&_1n$5)===_1n$5,neg:gr=>mod(-gr,r),eql:(gr,wr)=>gr===wr,sqr:gr=>mod(gr*gr,r),add:(gr,wr)=>mod(gr+wr,r),sub:(gr,wr)=>mod(gr-wr,r),mul:(gr,wr)=>mod(gr*wr,r),pow:(gr,wr)=>FpPow(_r,gr,wr),div:(gr,wr)=>mod(gr*invert(wr,r),r),sqrN:gr=>gr*gr,addN:(gr,wr)=>gr+wr,subN:(gr,wr)=>gr-wr,mulN:(gr,wr)=>gr*wr,inv:gr=>invert(gr,r),sqrt:ir||(gr=>(mr||(mr=FpSqrt(r)),mr(_r,gr))),toBytes:gr=>M?numberToBytesLE(gr,fr):numberToBytesBE(gr,fr),fromBytes:(gr,wr=!0)=>{if(dr){if(!dr.includes(gr.length)||gr.length>fr)throw new Error("Field.fromBytes: expected "+dr+" bytes, got "+gr.length);const br=new Uint8Array(fr);br.set(gr,M?0:br.length-gr.length),gr=br}if(gr.length!==fr)throw new Error("Field.fromBytes: expected "+fr+" bytes, got "+gr.length);let yr=M?bytesToNumberLE(gr):bytesToNumberBE(gr);if(lr&&(yr=mod(yr,r)),!wr&&!_r.isValid(yr))throw new Error("invalid field element: outside of range 0..ORDER");return yr},invertBatch:gr=>FpInvertBatch(_r,gr),cmov:(gr,wr,yr)=>yr?wr:gr});return Object.freeze(_r)}function getFieldBytesLength(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function getMinHashLength(r){const e=getFieldBytesLength(r);return e+Math.ceil(e/2)}function mapHashToField(r,e,M=!1){const tr=r.length,rr=getFieldBytesLength(e),ir=getMinHashLength(e);if(tr<16||tr<ir||tr>1024)throw new Error("expected "+ir+"-1024 bytes of input, got "+tr);const lr=M?bytesToNumberLE(r):bytesToNumberBE(r),dr=mod(lr,e-_1n$5)+_1n$5;return M?numberToBytesLE(dr,rr):numberToBytesBE(dr,rr)}const _0n$3=BigInt(0),_1n$4=BigInt(1);function negateCt(r,e){const M=e.negate();return r?M:e}function normalizeZ(r,e){const M=FpInvertBatch(r.Fp,e.map(tr=>tr.Z));return e.map((tr,rr)=>r.fromAffine(tr.toAffine(M[rr])))}function validateW(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function calcWOpts(r,e){validateW(r,e);const M=Math.ceil(e/r)+1,tr=2**(r-1),rr=2**r,ir=bitMask(r),lr=BigInt(r);return{windows:M,windowSize:tr,mask:ir,maxNumber:rr,shiftBy:lr}}function calcOffsets(r,e,M){const{windowSize:tr,mask:rr,maxNumber:ir,shiftBy:lr}=M;let dr=Number(r&rr),hr=r>>lr;dr>tr&&(dr-=ir,hr+=_1n$4);const fr=e*tr,mr=fr+Math.abs(dr)-1,_r=dr===0,gr=dr<0,wr=e%2!==0;return{nextN:hr,offset:mr,isZero:_r,isNeg:gr,isNegF:wr,offsetF:fr}}function validateMSMPoints(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((M,tr)=>{if(!(M instanceof e))throw new Error("invalid point at index "+tr)})}function validateMSMScalars(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((M,tr)=>{if(!e.isValid(M))throw new Error("invalid scalar at index "+tr)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(r){return pointWindowSizes.get(r)||1}function assert0(r){if(r!==_0n$3)throw new Error("invalid wNAF")}class wNAF{constructor(e,M){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=M}_unsafeLadder(e,M,tr=this.ZERO){let rr=e;for(;M>_0n$3;)M&_1n$4&&(tr=tr.add(rr)),rr=rr.double(),M>>=_1n$4;return tr}precomputeWindow(e,M){const{windows:tr,windowSize:rr}=calcWOpts(M,this.bits),ir=[];let lr=e,dr=lr;for(let hr=0;hr<tr;hr++){dr=lr,ir.push(dr);for(let fr=1;fr<rr;fr++)dr=dr.add(lr),ir.push(dr);lr=dr.double()}return ir}wNAF(e,M,tr){if(!this.Fn.isValid(tr))throw new Error("invalid scalar");let rr=this.ZERO,ir=this.BASE;const lr=calcWOpts(e,this.bits);for(let dr=0;dr<lr.windows;dr++){const{nextN:hr,offset:fr,isZero:mr,isNeg:_r,isNegF:gr,offsetF:wr}=calcOffsets(tr,dr,lr);tr=hr,mr?ir=ir.add(negateCt(gr,M[wr])):rr=rr.add(negateCt(_r,M[fr]))}return assert0(tr),{p:rr,f:ir}}wNAFUnsafe(e,M,tr,rr=this.ZERO){const ir=calcWOpts(e,this.bits);for(let lr=0;lr<ir.windows&&tr!==_0n$3;lr++){const{nextN:dr,offset:hr,isZero:fr,isNeg:mr}=calcOffsets(tr,lr,ir);if(tr=dr,!fr){const _r=M[hr];rr=rr.add(mr?_r.negate():_r)}}return assert0(tr),rr}getPrecomputes(e,M,tr){let rr=pointPrecomputes.get(M);return rr||(rr=this.precomputeWindow(M,e),e!==1&&(typeof tr=="function"&&(rr=tr(rr)),pointPrecomputes.set(M,rr))),rr}cached(e,M,tr){const rr=getW(e);return this.wNAF(rr,this.getPrecomputes(rr,e,tr),M)}unsafe(e,M,tr,rr){const ir=getW(e);return ir===1?this._unsafeLadder(e,M,rr):this.wNAFUnsafe(ir,this.getPrecomputes(ir,e,tr),M,rr)}createCache(e,M){validateW(M,this.bits),pointWindowSizes.set(e,M),pointPrecomputes.delete(e)}hasCache(e){return getW(e)!==1}}function mulEndoUnsafe(r,e,M,tr){let rr=e,ir=r.ZERO,lr=r.ZERO;for(;M>_0n$3||tr>_0n$3;)M&_1n$4&&(ir=ir.add(rr)),tr&_1n$4&&(lr=lr.add(rr)),rr=rr.double(),M>>=_1n$4,tr>>=_1n$4;return{p1:ir,p2:lr}}function pippenger(r,e,M,tr){validateMSMPoints(M,r),validateMSMScalars(tr,e);const rr=M.length,ir=tr.length;if(rr!==ir)throw new Error("arrays of points and scalars must have equal length");const lr=r.ZERO,dr=bitLen(BigInt(rr));let hr=1;dr>12?hr=dr-3:dr>4?hr=dr-2:dr>0&&(hr=2);const fr=bitMask(hr),mr=new Array(Number(fr)+1).fill(lr),_r=Math.floor((e.BITS-1)/hr)*hr;let gr=lr;for(let wr=_r;wr>=0;wr-=hr){mr.fill(lr);for(let br=0;br<ir;br++){const Mr=tr[br],vr=Number(Mr>>BigInt(wr)&fr);mr[vr]=mr[vr].add(M[br])}let yr=lr;for(let br=mr.length-1,Mr=lr;br>0;br--)Mr=Mr.add(mr[br]),yr=yr.add(Mr);if(gr=gr.add(yr),wr!==0)for(let br=0;br<hr;br++)gr=gr.double()}return gr}function createField(r,e,M){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField(e),e}else return Field(r,{isLE:M})}function _createCurveFields(r,e,M={},tr){if(tr===void 0&&(tr=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const hr of["p","n","h"]){const fr=e[hr];if(!(typeof fr=="bigint"&&fr>_0n$3))throw new Error(`CURVE.${hr} must be positive bigint`)}const rr=createField(e.p,M.Fp,tr),ir=createField(e.n,M.Fn,tr),dr=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(const hr of dr)if(!rr.isValid(e[hr]))throw new Error(`CURVE.${hr} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:rr,Fn:ir}}const _0n$2=BigInt(0),_1n$3=BigInt(1),_2n$4=BigInt(2),_8n$1=BigInt(8);function isEdValidXY(r,e,M,tr){const rr=r.sqr(M),ir=r.sqr(tr),lr=r.add(r.mul(e.a,rr),ir),dr=r.add(r.ONE,r.mul(e.d,r.mul(rr,ir)));return r.eql(lr,dr)}function edwards(r,e={}){const M=_createCurveFields("edwards",r,e,e.FpFnLE),{Fp:tr,Fn:rr}=M;let ir=M.CURVE;const{h:lr}=ir;_validateObject(e,{},{uvRatio:"function"});const dr=_2n$4<<BigInt(rr.BYTES*8)-_1n$3,hr=Mr=>tr.create(Mr),fr=e.uvRatio||((Mr,vr)=>{try{return{isValid:!0,value:tr.sqrt(tr.div(Mr,vr))}}catch{return{isValid:!1,value:_0n$2}}});if(!isEdValidXY(tr,ir,ir.Gx,ir.Gy))throw new Error("bad curve params: generator point");function mr(Mr,vr,Sr=!1){const xr=Sr?_1n$3:_0n$2;return aInRange("coordinate "+Mr,vr,xr,dr),vr}function _r(Mr){if(!(Mr instanceof yr))throw new Error("ExtendedPoint expected")}const gr=memoized((Mr,vr)=>{const{X:Sr,Y:xr,Z:Ar}=Mr,Dr=Mr.is0();vr==null&&(vr=Dr?_8n$1:tr.inv(Ar));const Ir=hr(Sr*vr),kr=hr(xr*vr),Or=tr.mul(Ar,vr);if(Dr)return{x:_0n$2,y:_1n$3};if(Or!==_1n$3)throw new Error("invZ was invalid");return{x:Ir,y:kr}}),wr=memoized(Mr=>{const{a:vr,d:Sr}=ir;if(Mr.is0())throw new Error("bad point: ZERO");const{X:xr,Y:Ar,Z:Dr,T:Ir}=Mr,kr=hr(xr*xr),Or=hr(Ar*Ar),Fr=hr(Dr*Dr),Jr=hr(Fr*Fr),$n=hr(kr*vr),Gr=hr(Fr*hr($n+Or)),Lr=hr(Jr+hr(Sr*hr(kr*Or)));if(Gr!==Lr)throw new Error("bad point: equation left != right (1)");const $r=hr(xr*Ar),zr=hr(Dr*Ir);if($r!==zr)throw new Error("bad point: equation left != right (2)");return!0});class yr{constructor(vr,Sr,xr,Ar){this.X=mr("x",vr),this.Y=mr("y",Sr),this.Z=mr("z",xr,!0),this.T=mr("t",Ar),Object.freeze(this)}static CURVE(){return ir}static fromAffine(vr){if(vr instanceof yr)throw new Error("extended point not allowed");const{x:Sr,y:xr}=vr||{};return mr("x",Sr),mr("y",xr),new yr(Sr,xr,_1n$3,hr(Sr*xr))}static fromBytes(vr,Sr=!1){const xr=tr.BYTES,{a:Ar,d:Dr}=ir;vr=copyBytes(_abytes2(vr,xr,"point")),_abool2(Sr,"zip215");const Ir=copyBytes(vr),kr=vr[xr-1];Ir[xr-1]=kr&-129;const Or=bytesToNumberLE(Ir),Fr=Sr?dr:tr.ORDER;aInRange("point.y",Or,_0n$2,Fr);const Jr=hr(Or*Or),$n=hr(Jr-_1n$3),Gr=hr(Dr*Jr-Ar);let{isValid:Lr,value:$r}=fr($n,Gr);if(!Lr)throw new Error("bad point: invalid y coordinate");const zr=($r&_1n$3)===_1n$3,Qr=(kr&128)!==0;if(!Sr&&$r===_0n$2&&Qr)throw new Error("bad point: x=0 and x_0=1");return Qr!==zr&&($r=hr(-$r)),yr.fromAffine({x:$r,y:Or})}static fromHex(vr,Sr=!1){return yr.fromBytes(ensureBytes("point",vr),Sr)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(vr=8,Sr=!0){return br.createCache(this,vr),Sr||this.multiply(_2n$4),this}assertValidity(){wr(this)}equals(vr){_r(vr);const{X:Sr,Y:xr,Z:Ar}=this,{X:Dr,Y:Ir,Z:kr}=vr,Or=hr(Sr*kr),Fr=hr(Dr*Ar),Jr=hr(xr*kr),$n=hr(Ir*Ar);return Or===Fr&&Jr===$n}is0(){return this.equals(yr.ZERO)}negate(){return new yr(hr(-this.X),this.Y,this.Z,hr(-this.T))}double(){const{a:vr}=ir,{X:Sr,Y:xr,Z:Ar}=this,Dr=hr(Sr*Sr),Ir=hr(xr*xr),kr=hr(_2n$4*hr(Ar*Ar)),Or=hr(vr*Dr),Fr=Sr+xr,Jr=hr(hr(Fr*Fr)-Dr-Ir),$n=Or+Ir,Gr=$n-kr,Lr=Or-Ir,$r=hr(Jr*Gr),zr=hr($n*Lr),Qr=hr(Jr*Lr),qn=hr(Gr*$n);return new yr($r,zr,qn,Qr)}add(vr){_r(vr);const{a:Sr,d:xr}=ir,{X:Ar,Y:Dr,Z:Ir,T:kr}=this,{X:Or,Y:Fr,Z:Jr,T:$n}=vr,Gr=hr(Ar*Or),Lr=hr(Dr*Fr),$r=hr(kr*xr*$n),zr=hr(Ir*Jr),Qr=hr((Ar+Dr)*(Or+Fr)-Gr-Lr),qn=zr-$r,Kn=zr+$r,Hn=hr(Lr-Sr*Gr),Jn=hr(Qr*qn),Yn=hr(Kn*Hn),Zn=hr(Qr*Hn),ts=hr(qn*Kn);return new yr(Jn,Yn,ts,Zn)}subtract(vr){return this.add(vr.negate())}multiply(vr){if(!rr.isValidNot0(vr))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:Sr,f:xr}=br.cached(this,vr,Ar=>normalizeZ(yr,Ar));return normalizeZ(yr,[Sr,xr])[0]}multiplyUnsafe(vr,Sr=yr.ZERO){if(!rr.isValid(vr))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return vr===_0n$2?yr.ZERO:this.is0()||vr===_1n$3?this:br.unsafe(this,vr,xr=>normalizeZ(yr,xr),Sr)}isSmallOrder(){return this.multiplyUnsafe(lr).is0()}isTorsionFree(){return br.unsafe(this,ir.n).is0()}toAffine(vr){return gr(this,vr)}clearCofactor(){return lr===_1n$3?this:this.multiplyUnsafe(lr)}toBytes(){const{x:vr,y:Sr}=this.toAffine(),xr=tr.toBytes(Sr);return xr[xr.length-1]|=vr&_1n$3?128:0,xr}toHex(){return bytesToHex$1(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(vr){return normalizeZ(yr,vr)}static msm(vr,Sr){return pippenger(yr,rr,vr,Sr)}_setWindowSize(vr){this.precompute(vr)}toRawBytes(){return this.toBytes()}}yr.BASE=new yr(ir.Gx,ir.Gy,_1n$3,hr(ir.Gx*ir.Gy)),yr.ZERO=new yr(_0n$2,_1n$3,_1n$3,_0n$2),yr.Fp=tr,yr.Fn=rr;const br=new wNAF(yr,rr.BITS);return yr.BASE.precompute(8),yr}function eddsa(r,e,M={}){if(typeof e!="function")throw new Error('"hash" function param is required');_validateObject(M,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:tr}=M,{BASE:rr,Fp:ir,Fn:lr}=r,dr=M.randomBytes||randomBytes,hr=M.adjustScalarBytes||(Fr=>Fr),fr=M.domain||((Fr,Jr,$n)=>{if(_abool2($n,"phflag"),Jr.length||$n)throw new Error("Contexts/pre-hash are not supported");return Fr});function mr(Fr){return lr.create(bytesToNumberLE(Fr))}function _r(Fr){const Jr=xr.secretKey;Fr=ensureBytes("private key",Fr,Jr);const $n=ensureBytes("hashed private key",e(Fr),2*Jr),Gr=hr($n.slice(0,Jr)),Lr=$n.slice(Jr,2*Jr),$r=mr(Gr);return{head:Gr,prefix:Lr,scalar:$r}}function gr(Fr){const{head:Jr,prefix:$n,scalar:Gr}=_r(Fr),Lr=rr.multiply(Gr),$r=Lr.toBytes();return{head:Jr,prefix:$n,scalar:Gr,point:Lr,pointBytes:$r}}function wr(Fr){return gr(Fr).pointBytes}function yr(Fr=Uint8Array.of(),...Jr){const $n=concatBytes(...Jr);return mr(e(fr($n,ensureBytes("context",Fr),!!tr)))}function br(Fr,Jr,$n={}){Fr=ensureBytes("message",Fr),tr&&(Fr=tr(Fr));const{prefix:Gr,scalar:Lr,pointBytes:$r}=gr(Jr),zr=yr($n.context,Gr,Fr),Qr=rr.multiply(zr).toBytes(),qn=yr($n.context,Qr,$r,Fr),Kn=lr.create(zr+qn*Lr);if(!lr.isValid(Kn))throw new Error("sign failed: invalid s");const Hn=concatBytes(Qr,lr.toBytes(Kn));return _abytes2(Hn,xr.signature,"result")}const Mr={zip215:!0};function vr(Fr,Jr,$n,Gr=Mr){const{context:Lr,zip215:$r}=Gr,zr=xr.signature;Fr=ensureBytes("signature",Fr,zr),Jr=ensureBytes("message",Jr),$n=ensureBytes("publicKey",$n,xr.publicKey),$r!==void 0&&_abool2($r,"zip215"),tr&&(Jr=tr(Jr));const Qr=zr/2,qn=Fr.subarray(0,Qr),Kn=bytesToNumberLE(Fr.subarray(Qr,zr));let Hn,Jn,Yn;try{Hn=r.fromBytes($n,$r),Jn=r.fromBytes(qn,$r),Yn=rr.multiplyUnsafe(Kn)}catch{return!1}if(!$r&&Hn.isSmallOrder())return!1;const Zn=yr(Lr,Jn.toBytes(),Hn.toBytes(),Jr);return Jn.add(Hn.multiplyUnsafe(Zn)).subtract(Yn).clearCofactor().is0()}const Sr=ir.BYTES,xr={secretKey:Sr,publicKey:Sr,signature:2*Sr,seed:Sr};function Ar(Fr=dr(xr.seed)){return _abytes2(Fr,xr.seed,"seed")}function Dr(Fr){const Jr=Or.randomSecretKey(Fr);return{secretKey:Jr,publicKey:wr(Jr)}}function Ir(Fr){return isBytes$1(Fr)&&Fr.length===lr.BYTES}function kr(Fr,Jr){try{return!!r.fromBytes(Fr,Jr)}catch{return!1}}const Or={getExtendedPublicKey:gr,randomSecretKey:Ar,isValidSecretKey:Ir,isValidPublicKey:kr,toMontgomery(Fr){const{y:Jr}=r.fromBytes(Fr),$n=xr.publicKey,Gr=$n===32;if(!Gr&&$n!==57)throw new Error("only defined for 25519 and 448");const Lr=Gr?ir.div(_1n$3+Jr,_1n$3-Jr):ir.div(Jr-_1n$3,Jr+_1n$3);return ir.toBytes(Lr)},toMontgomerySecret(Fr){const Jr=xr.secretKey;_abytes2(Fr,Jr);const $n=e(Fr.subarray(0,Jr));return hr($n).subarray(0,Jr)},randomPrivateKey:Ar,precompute(Fr=8,Jr=r.BASE){return Jr.precompute(Fr,!1)}};return Object.freeze({keygen:Dr,getPublicKey:wr,sign:br,verify:vr,utils:Or,Point:r,lengths:xr})}function _eddsa_legacy_opts_to_new(r){const e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},M=r.Fp,tr=Field(e.n,r.nBitLength,!0),rr={Fp:M,Fn:tr,uvRatio:r.uvRatio},ir={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:rr,hash:r.hash,eddsaOpts:ir}}function _eddsa_new_output_to_legacy(r,e){const M=e.Point;return Object.assign({},e,{ExtendedPoint:M,CURVE:r,nBitLength:M.Fn.BITS,nByteLength:M.Fn.BYTES})}function twistedEdwards(r){const{CURVE:e,curveOpts:M,hash:tr,eddsaOpts:rr}=_eddsa_legacy_opts_to_new(r),ir=edwards(e,M),lr=eddsa(ir,tr,rr);return _eddsa_new_output_to_legacy(r,lr)}const _1n$2=BigInt(1),_2n$3=BigInt(2);BigInt(3);const _5n=BigInt(5),_8n=BigInt(8),ed25519_CURVE_p=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ed25519_CURVE={p:ed25519_CURVE_p,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:_8n,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ed25519_pow_2_252_3(r){const e=BigInt(10),M=BigInt(20),tr=BigInt(40),rr=BigInt(80),ir=ed25519_CURVE_p,dr=r*r%ir*r%ir,hr=pow2(dr,_2n$3,ir)*dr%ir,fr=pow2(hr,_1n$2,ir)*r%ir,mr=pow2(fr,_5n,ir)*fr%ir,_r=pow2(mr,e,ir)*mr%ir,gr=pow2(_r,M,ir)*_r%ir,wr=pow2(gr,tr,ir)*gr%ir,yr=pow2(wr,rr,ir)*wr%ir,br=pow2(yr,rr,ir)*wr%ir,Mr=pow2(br,e,ir)*mr%ir;return{pow_p_5_8:pow2(Mr,_2n$3,ir)*r%ir,b2:dr}}function adjustScalarBytes(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}const ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function uvRatio(r,e){const M=ed25519_CURVE_p,tr=mod(e*e*e,M),rr=mod(tr*tr*e,M),ir=ed25519_pow_2_252_3(r*rr).pow_p_5_8;let lr=mod(r*tr*ir,M);const dr=mod(e*lr*lr,M),hr=lr,fr=mod(lr*ED25519_SQRT_M1,M),mr=dr===r,_r=dr===mod(-r,M),gr=dr===mod(-r*ED25519_SQRT_M1,M);return mr&&(lr=hr),(_r||gr)&&(lr=fr),isNegativeLE(lr,M)&&(lr=mod(-lr,M)),{isValid:mr||_r,value:lr}}const Fp=Field(ed25519_CURVE.p,{isLE:!0}),ed25519Defaults={...ed25519_CURVE,Fp,hash:sha512,adjustScalarBytes,uvRatio},ed25519$1=twistedEdwards(ed25519Defaults);function edwardsToMontgomeryPub(r){return ed25519$1.utils.toMontgomery(ensureBytes("pub",r))}var src$3={exports:{}},src$2,hasRequiredSrc$2;function requireSrc$2(){if(hasRequiredSrc$2)return src$2;hasRequiredSrc$2=1;function r(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var M=new Uint8Array(256),tr=0;tr<M.length;tr++)M[tr]=255;for(var rr=0;rr<e.length;rr++){var ir=e.charAt(rr),lr=ir.charCodeAt(0);if(M[lr]!==255)throw new TypeError(ir+" is ambiguous");M[lr]=rr}var dr=e.length,hr=e.charAt(0),fr=Math.log(dr)/Math.log(256),mr=Math.log(256)/Math.log(dr);function _r(yr){if(yr instanceof Uint8Array||(ArrayBuffer.isView(yr)?yr=new Uint8Array(yr.buffer,yr.byteOffset,yr.byteLength):Array.isArray(yr)&&(yr=Uint8Array.from(yr))),!(yr instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(yr.length===0)return"";for(var br=0,Mr=0,vr=0,Sr=yr.length;vr!==Sr&&yr[vr]===0;)vr++,br++;for(var xr=(Sr-vr)*mr+1>>>0,Ar=new Uint8Array(xr);vr!==Sr;){for(var Dr=yr[vr],Ir=0,kr=xr-1;(Dr!==0||Ir<Mr)&&kr!==-1;kr--,Ir++)Dr+=256*Ar[kr]>>>0,Ar[kr]=Dr%dr>>>0,Dr=Dr/dr>>>0;if(Dr!==0)throw new Error("Non-zero carry");Mr=Ir,vr++}for(var Or=xr-Mr;Or!==xr&&Ar[Or]===0;)Or++;for(var Fr=hr.repeat(br);Or<xr;++Or)Fr+=e.charAt(Ar[Or]);return Fr}function gr(yr){if(typeof yr!="string")throw new TypeError("Expected String");if(yr.length===0)return new Uint8Array;var br=0;if(yr[br]!==" "){for(var Mr=0,vr=0;yr[br]===hr;)Mr++,br++;for(var Sr=(yr.length-br)*fr+1>>>0,xr=new Uint8Array(Sr);yr[br];){var Ar=M[yr.charCodeAt(br)];if(Ar===255)return;for(var Dr=0,Ir=Sr-1;(Ar!==0||Dr<vr)&&Ir!==-1;Ir--,Dr++)Ar+=dr*xr[Ir]>>>0,xr[Ir]=Ar%256>>>0,Ar=Ar/256>>>0;if(Ar!==0)throw new Error("Non-zero carry");vr=Dr,br++}if(yr[br]!==" "){for(var kr=Sr-vr;kr!==Sr&&xr[kr]===0;)kr++;for(var Or=new Uint8Array(Mr+(Sr-kr)),Fr=Mr;kr!==Sr;)Or[Fr++]=xr[kr++];return Or}}}function wr(yr){var br=gr(yr);if(br)return br;throw new Error("Non-base"+dr+" character")}return{encode:_r,decodeUnsafe:gr,decode:wr}}return src$2=r,src$2}var util$1,hasRequiredUtil$1;function requireUtil$1(){if(hasRequiredUtil$1)return util$1;hasRequiredUtil$1=1;const r=new TextDecoder,e=ir=>r.decode(ir),M=new TextEncoder,tr=ir=>M.encode(ir);function rr(ir,lr){const dr=new Uint8Array(lr);let hr=0;for(const fr of ir)dr.set(fr,hr),hr+=fr.length;return dr}return util$1={decodeText:e,encodeText:tr,concat:rr},util$1}var base$1,hasRequiredBase;function requireBase(){if(hasRequiredBase)return base$1;hasRequiredBase=1;const{encodeText:r}=requireUtil$1();class e{constructor(tr,rr,ir,lr){this.name=tr,this.code=rr,this.codeBuf=r(this.code),this.alphabet=lr,this.codec=ir(lr)}encode(tr){return this.codec.encode(tr)}decode(tr){for(const rr of tr)if(this.alphabet&&this.alphabet.indexOf(rr)<0)throw new Error(`invalid character '${rr}' in '${tr}'`);return this.codec.decode(tr)}}return base$1=e,base$1}var rfc4648_1,hasRequiredRfc4648;function requireRfc4648(){if(hasRequiredRfc4648)return rfc4648_1;hasRequiredRfc4648=1;const r=(tr,rr,ir)=>{const lr={};for(let gr=0;gr<rr.length;++gr)lr[rr[gr]]=gr;let dr=tr.length;for(;tr[dr-1]==="=";)--dr;const hr=new Uint8Array(dr*ir/8|0);let fr=0,mr=0,_r=0;for(let gr=0;gr<dr;++gr){const wr=lr[tr[gr]];if(wr===void 0)throw new SyntaxError("Invalid character "+tr[gr]);mr=mr<<ir|wr,fr+=ir,fr>=8&&(fr-=8,hr[_r++]=255&mr>>fr)}if(fr>=ir||255&mr<<8-fr)throw new SyntaxError("Unexpected end of data");return hr},e=(tr,rr,ir)=>{const lr=rr[rr.length-1]==="=",dr=(1<<ir)-1;let hr="",fr=0,mr=0;for(let _r=0;_r<tr.length;++_r)for(mr=mr<<8|tr[_r],fr+=8;fr>ir;)fr-=ir,hr+=rr[dr&mr>>fr];if(fr&&(hr+=rr[dr&mr<<ir-fr]),lr)for(;hr.length*ir&7;)hr+="=";return hr};return rfc4648_1={rfc4648:tr=>rr=>({encode(ir){return e(ir,rr,tr)},decode(ir){return r(ir,rr,tr)}})},rfc4648_1}var constants_1,hasRequiredConstants;function requireConstants(){if(hasRequiredConstants)return constants_1;hasRequiredConstants=1;const r=requireSrc$2(),e=requireBase(),{rfc4648:M}=requireRfc4648(),{decodeText:tr,encodeText:rr}=requireUtil$1(),lr=[["identity","\0",()=>({encode:tr,decode:rr}),""],["base2","0",M(1),"01"],["base8","7",M(3),"01234567"],["base10","9",r,"0123456789"],["base16","f",M(4),"0123456789abcdef"],["base16upper","F",M(4),"0123456789ABCDEF"],["base32hex","v",M(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",M(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",M(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",M(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",M(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",M(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",M(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",M(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",M(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",r,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",r,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",r,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",r,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",M(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",M(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",M(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",M(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],dr=lr.reduce((fr,mr)=>(fr[mr[0]]=new e(mr[0],mr[1],mr[2],mr[3]),fr),{}),hr=lr.reduce((fr,mr)=>(fr[mr[1]]=dr[mr[0]],fr),{});return constants_1={names:dr,codes:hr},constants_1}var hasRequiredSrc$1;function requireSrc$1(){return hasRequiredSrc$1||(hasRequiredSrc$1=1,(function(r,e){const M=requireConstants(),{encodeText:tr,decodeText:rr,concat:ir}=requireUtil$1();function lr(br,Mr){if(!Mr)throw new Error("requires an encoded Uint8Array");const{name:vr,codeBuf:Sr}=_r(br);return mr(vr,Mr),ir([Sr,Mr],Sr.length+Mr.length)}function dr(br,Mr){const vr=_r(br),Sr=tr(vr.encode(Mr));return ir([vr.codeBuf,Sr],vr.codeBuf.length+Sr.length)}function hr(br){br instanceof Uint8Array&&(br=rr(br));const Mr=br[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(Mr)&&(br=br.toLowerCase()),_r(br[0]).decode(br.substring(1))}function fr(br){if(br instanceof Uint8Array&&(br=rr(br)),Object.prototype.toString.call(br)!=="[object String]")return!1;try{return _r(br[0]).name}catch{return!1}}function mr(br,Mr){_r(br).decode(rr(Mr))}function _r(br){if(Object.prototype.hasOwnProperty.call(M.names,br))return M.names[br];if(Object.prototype.hasOwnProperty.call(M.codes,br))return M.codes[br];throw new Error(`Unsupported encoding: ${br}`)}function gr(br){return br instanceof Uint8Array&&(br=rr(br)),_r(br[0])}e=r.exports=lr,e.encode=dr,e.decode=hr,e.isEncoded=fr,e.encoding=_r,e.encodingFromData=gr;const wr=Object.freeze(M.names),yr=Object.freeze(M.codes);e.names=wr,e.codes=yr})(src$3,src$3.exports)),src$3.exports}var srcExports$1=requireSrc$1();class HMAC extends Hash{constructor(e,M){super(),this.finished=!1,this.destroyed=!1,ahash(e);const tr=toBytes(M);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const rr=this.blockLen,ir=new Uint8Array(rr);ir.set(tr.length>rr?e.create().update(tr).digest():tr);for(let lr=0;lr<ir.length;lr++)ir[lr]^=54;this.iHash.update(ir),this.oHash=e.create();for(let lr=0;lr<ir.length;lr++)ir[lr]^=106;this.oHash.update(ir),clean(ir)}update(e){return aexists(this),this.iHash.update(e),this}digestInto(e){aexists(this),abytes(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:M,iHash:tr,finished:rr,destroyed:ir,blockLen:lr,outputLen:dr}=this;return e=e,e.finished=rr,e.destroyed=ir,e.blockLen=lr,e.outputLen=dr,e.oHash=M._cloneInto(e.oHash),e.iHash=tr._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(r,e,M)=>new HMAC(r,e).update(M).digest();hmac.create=(r,e)=>new HMAC(r,e);const divNearest=(r,e)=>(r+(r>=0?e:-e)/_2n$2)/e;function _splitEndoScalar(r,e,M){const[[tr,rr],[ir,lr]]=e,dr=divNearest(lr*r,M),hr=divNearest(-rr*r,M);let fr=r-dr*tr-hr*ir,mr=-dr*rr-hr*lr;const _r=fr<_0n$1,gr=mr<_0n$1;_r&&(fr=-fr),gr&&(mr=-mr);const wr=bitMask(Math.ceil(bitLen(M)/2))+_1n$1;if(fr<_0n$1||fr>=wr||mr<_0n$1||mr>=wr)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:_r,k1:fr,k2neg:gr,k2:mr}}function validateSigFormat(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function validateSigOpts(r,e){const M={};for(let tr of Object.keys(e))M[tr]=r[tr]===void 0?e[tr]:r[tr];return _abool2(M.lowS,"lowS"),_abool2(M.prehash,"prehash"),M.format!==void 0&&validateSigFormat(M.format),M}class DERErr extends Error{constructor(e=""){super(e)}}const DER={Err:DERErr,_tlv:{encode:(r,e)=>{const{Err:M}=DER;if(r<0||r>256)throw new M("tlv.encode: wrong tag");if(e.length&1)throw new M("tlv.encode: unpadded data");const tr=e.length/2,rr=numberToHexUnpadded(tr);if(rr.length/2&128)throw new M("tlv.encode: long form length too big");const ir=tr>127?numberToHexUnpadded(rr.length/2|128):"";return numberToHexUnpadded(r)+ir+rr+e},decode(r,e){const{Err:M}=DER;let tr=0;if(r<0||r>256)throw new M("tlv.encode: wrong tag");if(e.length<2||e[tr++]!==r)throw new M("tlv.decode: wrong tlv");const rr=e[tr++],ir=!!(rr&128);let lr=0;if(!ir)lr=rr;else{const hr=rr&127;if(!hr)throw new M("tlv.decode(long): indefinite length not supported");if(hr>4)throw new M("tlv.decode(long): byte length is too big");const fr=e.subarray(tr,tr+hr);if(fr.length!==hr)throw new M("tlv.decode: length bytes not complete");if(fr[0]===0)throw new M("tlv.decode(long): zero leftmost byte");for(const mr of fr)lr=lr<<8|mr;if(tr+=hr,lr<128)throw new M("tlv.decode(long): not minimal encoding")}const dr=e.subarray(tr,tr+lr);if(dr.length!==lr)throw new M("tlv.decode: wrong value length");return{v:dr,l:e.subarray(tr+lr)}}},_int:{encode(r){const{Err:e}=DER;if(r<_0n$1)throw new e("integer: negative integers are not allowed");let M=numberToHexUnpadded(r);if(Number.parseInt(M[0],16)&8&&(M="00"+M),M.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return M},decode(r){const{Err:e}=DER;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(r)}},toSig(r){const{Err:e,_int:M,_tlv:tr}=DER,rr=ensureBytes("signature",r),{v:ir,l:lr}=tr.decode(48,rr);if(lr.length)throw new e("invalid signature: left bytes after parsing");const{v:dr,l:hr}=tr.decode(2,ir),{v:fr,l:mr}=tr.decode(2,hr);if(mr.length)throw new e("invalid signature: left bytes after parsing");return{r:M.decode(dr),s:M.decode(fr)}},hexFromSig(r){const{_tlv:e,_int:M}=DER,tr=e.encode(2,M.encode(r.r)),rr=e.encode(2,M.encode(r.s)),ir=tr+rr;return e.encode(48,ir)}},_0n$1=BigInt(0),_1n$1=BigInt(1),_2n$2=BigInt(2),_3n=BigInt(3),_4n=BigInt(4);function _normFnElement(r,e){const{BYTES:M}=r;let tr;if(typeof e=="bigint")tr=e;else{let rr=ensureBytes("private key",e);try{tr=r.fromBytes(rr)}catch{throw new Error(`invalid private key: expected ui8a of size ${M}, got ${typeof e}`)}}if(!r.isValidNot0(tr))throw new Error("invalid private key: out of range [1..N-1]");return tr}function weierstrassN(r,e={}){const M=_createCurveFields("weierstrass",r,e),{Fp:tr,Fn:rr}=M;let ir=M.CURVE;const{h:lr,n:dr}=ir;_validateObject(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:hr}=e;if(hr&&(!tr.is0(ir.a)||typeof hr.beta!="bigint"||!Array.isArray(hr.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const fr=getWLengths(tr,rr);function mr(){if(!tr.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function _r(Gr,Lr,$r){const{x:zr,y:Qr}=Lr.toAffine(),qn=tr.toBytes(zr);if(_abool2($r,"isCompressed"),$r){mr();const Kn=!tr.isOdd(Qr);return concatBytes(pprefix(Kn),qn)}else return concatBytes(Uint8Array.of(4),qn,tr.toBytes(Qr))}function gr(Gr){_abytes2(Gr,void 0,"Point");const{publicKey:Lr,publicKeyUncompressed:$r}=fr,zr=Gr.length,Qr=Gr[0],qn=Gr.subarray(1);if(zr===Lr&&(Qr===2||Qr===3)){const Kn=tr.fromBytes(qn);if(!tr.isValid(Kn))throw new Error("bad point: is not on curve, wrong x");const Hn=br(Kn);let Jn;try{Jn=tr.sqrt(Hn)}catch(ts){const es=ts instanceof Error?": "+ts.message:"";throw new Error("bad point: is not on curve, sqrt error"+es)}mr();const Yn=tr.isOdd(Jn);return(Qr&1)===1!==Yn&&(Jn=tr.neg(Jn)),{x:Kn,y:Jn}}else if(zr===$r&&Qr===4){const Kn=tr.BYTES,Hn=tr.fromBytes(qn.subarray(0,Kn)),Jn=tr.fromBytes(qn.subarray(Kn,Kn*2));if(!Mr(Hn,Jn))throw new Error("bad point: is not on curve");return{x:Hn,y:Jn}}else throw new Error(`bad point: got length ${zr}, expected compressed=${Lr} or uncompressed=${$r}`)}const wr=e.toBytes||_r,yr=e.fromBytes||gr;function br(Gr){const Lr=tr.sqr(Gr),$r=tr.mul(Lr,Gr);return tr.add(tr.add($r,tr.mul(Gr,ir.a)),ir.b)}function Mr(Gr,Lr){const $r=tr.sqr(Lr),zr=br(Gr);return tr.eql($r,zr)}if(!Mr(ir.Gx,ir.Gy))throw new Error("bad curve params: generator point");const vr=tr.mul(tr.pow(ir.a,_3n),_4n),Sr=tr.mul(tr.sqr(ir.b),BigInt(27));if(tr.is0(tr.add(vr,Sr)))throw new Error("bad curve params: a or b");function xr(Gr,Lr,$r=!1){if(!tr.isValid(Lr)||$r&&tr.is0(Lr))throw new Error(`bad point coordinate ${Gr}`);return Lr}function Ar(Gr){if(!(Gr instanceof Fr))throw new Error("ProjectivePoint expected")}function Dr(Gr){if(!hr||!hr.basises)throw new Error("no endo");return _splitEndoScalar(Gr,hr.basises,rr.ORDER)}const Ir=memoized((Gr,Lr)=>{const{X:$r,Y:zr,Z:Qr}=Gr;if(tr.eql(Qr,tr.ONE))return{x:$r,y:zr};const qn=Gr.is0();Lr==null&&(Lr=qn?tr.ONE:tr.inv(Qr));const Kn=tr.mul($r,Lr),Hn=tr.mul(zr,Lr),Jn=tr.mul(Qr,Lr);if(qn)return{x:tr.ZERO,y:tr.ZERO};if(!tr.eql(Jn,tr.ONE))throw new Error("invZ was invalid");return{x:Kn,y:Hn}}),kr=memoized(Gr=>{if(Gr.is0()){if(e.allowInfinityPoint&&!tr.is0(Gr.Y))return;throw new Error("bad point: ZERO")}const{x:Lr,y:$r}=Gr.toAffine();if(!tr.isValid(Lr)||!tr.isValid($r))throw new Error("bad point: x or y not field elements");if(!Mr(Lr,$r))throw new Error("bad point: equation left != right");if(!Gr.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Or(Gr,Lr,$r,zr,Qr){return $r=new Fr(tr.mul($r.X,Gr),$r.Y,$r.Z),Lr=negateCt(zr,Lr),$r=negateCt(Qr,$r),Lr.add($r)}class Fr{constructor(Lr,$r,zr){this.X=xr("x",Lr),this.Y=xr("y",$r,!0),this.Z=xr("z",zr),Object.freeze(this)}static CURVE(){return ir}static fromAffine(Lr){const{x:$r,y:zr}=Lr||{};if(!Lr||!tr.isValid($r)||!tr.isValid(zr))throw new Error("invalid affine point");if(Lr instanceof Fr)throw new Error("projective point not allowed");return tr.is0($r)&&tr.is0(zr)?Fr.ZERO:new Fr($r,zr,tr.ONE)}static fromBytes(Lr){const $r=Fr.fromAffine(yr(_abytes2(Lr,void 0,"point")));return $r.assertValidity(),$r}static fromHex(Lr){return Fr.fromBytes(ensureBytes("pointHex",Lr))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(Lr=8,$r=!0){return $n.createCache(this,Lr),$r||this.multiply(_3n),this}assertValidity(){kr(this)}hasEvenY(){const{y:Lr}=this.toAffine();if(!tr.isOdd)throw new Error("Field doesn't support isOdd");return!tr.isOdd(Lr)}equals(Lr){Ar(Lr);const{X:$r,Y:zr,Z:Qr}=this,{X:qn,Y:Kn,Z:Hn}=Lr,Jn=tr.eql(tr.mul($r,Hn),tr.mul(qn,Qr)),Yn=tr.eql(tr.mul(zr,Hn),tr.mul(Kn,Qr));return Jn&&Yn}negate(){return new Fr(this.X,tr.neg(this.Y),this.Z)}double(){const{a:Lr,b:$r}=ir,zr=tr.mul($r,_3n),{X:Qr,Y:qn,Z:Kn}=this;let Hn=tr.ZERO,Jn=tr.ZERO,Yn=tr.ZERO,Zn=tr.mul(Qr,Qr),ts=tr.mul(qn,qn),es=tr.mul(Kn,Kn),Xn=tr.mul(Qr,qn);return Xn=tr.add(Xn,Xn),Yn=tr.mul(Qr,Kn),Yn=tr.add(Yn,Yn),Hn=tr.mul(Lr,Yn),Jn=tr.mul(zr,es),Jn=tr.add(Hn,Jn),Hn=tr.sub(ts,Jn),Jn=tr.add(ts,Jn),Jn=tr.mul(Hn,Jn),Hn=tr.mul(Xn,Hn),Yn=tr.mul(zr,Yn),es=tr.mul(Lr,es),Xn=tr.sub(Zn,es),Xn=tr.mul(Lr,Xn),Xn=tr.add(Xn,Yn),Yn=tr.add(Zn,Zn),Zn=tr.add(Yn,Zn),Zn=tr.add(Zn,es),Zn=tr.mul(Zn,Xn),Jn=tr.add(Jn,Zn),es=tr.mul(qn,Kn),es=tr.add(es,es),Zn=tr.mul(es,Xn),Hn=tr.sub(Hn,Zn),Yn=tr.mul(es,ts),Yn=tr.add(Yn,Yn),Yn=tr.add(Yn,Yn),new Fr(Hn,Jn,Yn)}add(Lr){Ar(Lr);const{X:$r,Y:zr,Z:Qr}=this,{X:qn,Y:Kn,Z:Hn}=Lr;let Jn=tr.ZERO,Yn=tr.ZERO,Zn=tr.ZERO;const ts=ir.a,es=tr.mul(ir.b,_3n);let Xn=tr.mul($r,qn),rs=tr.mul(zr,Kn),ss=tr.mul(Qr,Hn),is=tr.add($r,zr),ns=tr.add(qn,Kn);is=tr.mul(is,ns),ns=tr.add(Xn,rs),is=tr.sub(is,ns),ns=tr.add($r,Qr);let os=tr.add(qn,Hn);return ns=tr.mul(ns,os),os=tr.add(Xn,ss),ns=tr.sub(ns,os),os=tr.add(zr,Qr),Jn=tr.add(Kn,Hn),os=tr.mul(os,Jn),Jn=tr.add(rs,ss),os=tr.sub(os,Jn),Zn=tr.mul(ts,ns),Jn=tr.mul(es,ss),Zn=tr.add(Jn,Zn),Jn=tr.sub(rs,Zn),Zn=tr.add(rs,Zn),Yn=tr.mul(Jn,Zn),rs=tr.add(Xn,Xn),rs=tr.add(rs,Xn),ss=tr.mul(ts,ss),ns=tr.mul(es,ns),rs=tr.add(rs,ss),ss=tr.sub(Xn,ss),ss=tr.mul(ts,ss),ns=tr.add(ns,ss),Xn=tr.mul(rs,ns),Yn=tr.add(Yn,Xn),Xn=tr.mul(os,ns),Jn=tr.mul(is,Jn),Jn=tr.sub(Jn,Xn),Xn=tr.mul(is,rs),Zn=tr.mul(os,Zn),Zn=tr.add(Zn,Xn),new Fr(Jn,Yn,Zn)}subtract(Lr){return this.add(Lr.negate())}is0(){return this.equals(Fr.ZERO)}multiply(Lr){const{endo:$r}=e;if(!rr.isValidNot0(Lr))throw new Error("invalid scalar: out of range");let zr,Qr;const qn=Kn=>$n.cached(this,Kn,Hn=>normalizeZ(Fr,Hn));if($r){const{k1neg:Kn,k1:Hn,k2neg:Jn,k2:Yn}=Dr(Lr),{p:Zn,f:ts}=qn(Hn),{p:es,f:Xn}=qn(Yn);Qr=ts.add(Xn),zr=Or($r.beta,Zn,es,Kn,Jn)}else{const{p:Kn,f:Hn}=qn(Lr);zr=Kn,Qr=Hn}return normalizeZ(Fr,[zr,Qr])[0]}multiplyUnsafe(Lr){const{endo:$r}=e,zr=this;if(!rr.isValid(Lr))throw new Error("invalid scalar: out of range");if(Lr===_0n$1||zr.is0())return Fr.ZERO;if(Lr===_1n$1)return zr;if($n.hasCache(this))return this.multiply(Lr);if($r){const{k1neg:Qr,k1:qn,k2neg:Kn,k2:Hn}=Dr(Lr),{p1:Jn,p2:Yn}=mulEndoUnsafe(Fr,zr,qn,Hn);return Or($r.beta,Jn,Yn,Qr,Kn)}else return $n.unsafe(zr,Lr)}multiplyAndAddUnsafe(Lr,$r,zr){const Qr=this.multiplyUnsafe($r).add(Lr.multiplyUnsafe(zr));return Qr.is0()?void 0:Qr}toAffine(Lr){return Ir(this,Lr)}isTorsionFree(){const{isTorsionFree:Lr}=e;return lr===_1n$1?!0:Lr?Lr(Fr,this):$n.unsafe(this,dr).is0()}clearCofactor(){const{clearCofactor:Lr}=e;return lr===_1n$1?this:Lr?Lr(Fr,this):this.multiplyUnsafe(lr)}isSmallOrder(){return this.multiplyUnsafe(lr).is0()}toBytes(Lr=!0){return _abool2(Lr,"isCompressed"),this.assertValidity(),wr(Fr,this,Lr)}toHex(Lr=!0){return bytesToHex$1(this.toBytes(Lr))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(Lr=!0){return this.toBytes(Lr)}_setWindowSize(Lr){this.precompute(Lr)}static normalizeZ(Lr){return normalizeZ(Fr,Lr)}static msm(Lr,$r){return pippenger(Fr,rr,Lr,$r)}static fromPrivateKey(Lr){return Fr.BASE.multiply(_normFnElement(rr,Lr))}}Fr.BASE=new Fr(ir.Gx,ir.Gy,tr.ONE),Fr.ZERO=new Fr(tr.ZERO,tr.ONE,tr.ZERO),Fr.Fp=tr,Fr.Fn=rr;const Jr=rr.BITS,$n=new wNAF(Fr,e.endo?Math.ceil(Jr/2):Jr);return Fr.BASE.precompute(8),Fr}function pprefix(r){return Uint8Array.of(r?2:3)}function getWLengths(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ecdh(r,e={}){const{Fn:M}=r,tr=e.randomBytes||randomBytes,rr=Object.assign(getWLengths(r.Fp,M),{seed:getMinHashLength(M.ORDER)});function ir(wr){try{return!!_normFnElement(M,wr)}catch{return!1}}function lr(wr,yr){const{publicKey:br,publicKeyUncompressed:Mr}=rr;try{const vr=wr.length;return yr===!0&&vr!==br||yr===!1&&vr!==Mr?!1:!!r.fromBytes(wr)}catch{return!1}}function dr(wr=tr(rr.seed)){return mapHashToField(_abytes2(wr,rr.seed,"seed"),M.ORDER)}function hr(wr,yr=!0){return r.BASE.multiply(_normFnElement(M,wr)).toBytes(yr)}function fr(wr){const yr=dr(wr);return{secretKey:yr,publicKey:hr(yr)}}function mr(wr){if(typeof wr=="bigint")return!1;if(wr instanceof r)return!0;const{secretKey:yr,publicKey:br,publicKeyUncompressed:Mr}=rr;if(M.allowedLengths||yr===br)return;const vr=ensureBytes("key",wr).length;return vr===br||vr===Mr}function _r(wr,yr,br=!0){if(mr(wr)===!0)throw new Error("first arg must be private key");if(mr(yr)===!1)throw new Error("second arg must be public key");const Mr=_normFnElement(M,wr);return r.fromHex(yr).multiply(Mr).toBytes(br)}return Object.freeze({getPublicKey:hr,getSharedSecret:_r,keygen:fr,Point:r,utils:{isValidSecretKey:ir,isValidPublicKey:lr,randomSecretKey:dr,isValidPrivateKey:ir,randomPrivateKey:dr,normPrivateKeyToScalar:wr=>_normFnElement(M,wr),precompute(wr=8,yr=r.BASE){return yr.precompute(wr,!1)}},lengths:rr})}function ecdsa(r,e,M={}){ahash(e),_validateObject(M,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const tr=M.randomBytes||randomBytes,rr=M.hmac||(($r,...zr)=>hmac(e,$r,concatBytes(...zr))),{Fp:ir,Fn:lr}=r,{ORDER:dr,BITS:hr}=lr,{keygen:fr,getPublicKey:mr,getSharedSecret:_r,utils:gr,lengths:wr}=ecdh(r,M),yr={prehash:!1,lowS:typeof M.lowS=="boolean"?M.lowS:!1,format:void 0,extraEntropy:!1},br="compact";function Mr($r){const zr=dr>>_1n$1;return $r>zr}function vr($r,zr){if(!lr.isValidNot0(zr))throw new Error(`invalid signature ${$r}: out of range 1..Point.Fn.ORDER`);return zr}function Sr($r,zr){validateSigFormat(zr);const Qr=wr.signature,qn=zr==="compact"?Qr:zr==="recovered"?Qr+1:void 0;return _abytes2($r,qn,`${zr} signature`)}class xr{constructor(zr,Qr,qn){this.r=vr("r",zr),this.s=vr("s",Qr),qn!=null&&(this.recovery=qn),Object.freeze(this)}static fromBytes(zr,Qr=br){Sr(zr,Qr);let qn;if(Qr==="der"){const{r:Yn,s:Zn}=DER.toSig(_abytes2(zr));return new xr(Yn,Zn)}Qr==="recovered"&&(qn=zr[0],Qr="compact",zr=zr.subarray(1));const Kn=lr.BYTES,Hn=zr.subarray(0,Kn),Jn=zr.subarray(Kn,Kn*2);return new xr(lr.fromBytes(Hn),lr.fromBytes(Jn),qn)}static fromHex(zr,Qr){return this.fromBytes(hexToBytes$1(zr),Qr)}addRecoveryBit(zr){return new xr(this.r,this.s,zr)}recoverPublicKey(zr){const Qr=ir.ORDER,{r:qn,s:Kn,recovery:Hn}=this;if(Hn==null||![0,1,2,3].includes(Hn))throw new Error("recovery id invalid");if(dr*_2n$2<Qr&&Hn>1)throw new Error("recovery id is ambiguous for h>1 curve");const Yn=Hn===2||Hn===3?qn+dr:qn;if(!ir.isValid(Yn))throw new Error("recovery id 2 or 3 invalid");const Zn=ir.toBytes(Yn),ts=r.fromBytes(concatBytes(pprefix((Hn&1)===0),Zn)),es=lr.inv(Yn),Xn=Dr(ensureBytes("msgHash",zr)),rs=lr.create(-Xn*es),ss=lr.create(Kn*es),is=r.BASE.multiplyUnsafe(rs).add(ts.multiplyUnsafe(ss));if(is.is0())throw new Error("point at infinify");return is.assertValidity(),is}hasHighS(){return Mr(this.s)}toBytes(zr=br){if(validateSigFormat(zr),zr==="der")return hexToBytes$1(DER.hexFromSig(this));const Qr=lr.toBytes(this.r),qn=lr.toBytes(this.s);if(zr==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return concatBytes(Uint8Array.of(this.recovery),Qr,qn)}return concatBytes(Qr,qn)}toHex(zr){return bytesToHex$1(this.toBytes(zr))}assertValidity(){}static fromCompact(zr){return xr.fromBytes(ensureBytes("sig",zr),"compact")}static fromDER(zr){return xr.fromBytes(ensureBytes("sig",zr),"der")}normalizeS(){return this.hasHighS()?new xr(this.r,lr.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return bytesToHex$1(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return bytesToHex$1(this.toBytes("compact"))}}const Ar=M.bits2int||function(zr){if(zr.length>8192)throw new Error("input is too large");const Qr=bytesToNumberBE(zr),qn=zr.length*8-hr;return qn>0?Qr>>BigInt(qn):Qr},Dr=M.bits2int_modN||function(zr){return lr.create(Ar(zr))},Ir=bitMask(hr);function kr($r){return aInRange("num < 2^"+hr,$r,_0n$1,Ir),lr.toBytes($r)}function Or($r,zr){return _abytes2($r,void 0,"message"),zr?_abytes2(e($r),void 0,"prehashed message"):$r}function Fr($r,zr,Qr){if(["recovered","canonical"].some(rs=>rs in Qr))throw new Error("sign() legacy options not supported");const{lowS:qn,prehash:Kn,extraEntropy:Hn}=validateSigOpts(Qr,yr);$r=Or($r,Kn);const Jn=Dr($r),Yn=_normFnElement(lr,zr),Zn=[kr(Yn),kr(Jn)];if(Hn!=null&&Hn!==!1){const rs=Hn===!0?tr(wr.secretKey):Hn;Zn.push(ensureBytes("extraEntropy",rs))}const ts=concatBytes(...Zn),es=Jn;function Xn(rs){const ss=Ar(rs);if(!lr.isValidNot0(ss))return;const is=lr.inv(ss),ns=r.BASE.multiply(ss).toAffine(),os=lr.create(ns.x);if(os===_0n$1)return;const ls=lr.create(is*lr.create(es+os*Yn));if(ls===_0n$1)return;let cs=(ns.x===os?0:2)|Number(ns.y&_1n$1),us=ls;return qn&&Mr(ls)&&(us=lr.neg(ls),cs^=1),new xr(os,us,cs)}return{seed:ts,k2sig:Xn}}function Jr($r,zr,Qr={}){$r=ensureBytes("message",$r);const{seed:qn,k2sig:Kn}=Fr($r,zr,Qr);return createHmacDrbg(e.outputLen,lr.BYTES,rr)(qn,Kn)}function $n($r){let zr;const Qr=typeof $r=="string"||isBytes$1($r),qn=!Qr&&$r!==null&&typeof $r=="object"&&typeof $r.r=="bigint"&&typeof $r.s=="bigint";if(!Qr&&!qn)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(qn)zr=new xr($r.r,$r.s);else if(Qr){try{zr=xr.fromBytes(ensureBytes("sig",$r),"der")}catch(Kn){if(!(Kn instanceof DER.Err))throw Kn}if(!zr)try{zr=xr.fromBytes(ensureBytes("sig",$r),"compact")}catch{return!1}}return zr||!1}function Gr($r,zr,Qr,qn={}){const{lowS:Kn,prehash:Hn,format:Jn}=validateSigOpts(qn,yr);if(Qr=ensureBytes("publicKey",Qr),zr=Or(ensureBytes("message",zr),Hn),"strict"in qn)throw new Error("options.strict was renamed to lowS");const Yn=Jn===void 0?$n($r):xr.fromBytes(ensureBytes("sig",$r),Jn);if(Yn===!1)return!1;try{const Zn=r.fromBytes(Qr);if(Kn&&Yn.hasHighS())return!1;const{r:ts,s:es}=Yn,Xn=Dr(zr),rs=lr.inv(es),ss=lr.create(Xn*rs),is=lr.create(ts*rs),ns=r.BASE.multiplyUnsafe(ss).add(Zn.multiplyUnsafe(is));return ns.is0()?!1:lr.create(ns.x)===ts}catch{return!1}}function Lr($r,zr,Qr={}){const{prehash:qn}=validateSigOpts(Qr,yr);return zr=Or(zr,qn),xr.fromBytes($r,"recovered").recoverPublicKey(zr).toBytes()}return Object.freeze({keygen:fr,getPublicKey:mr,getSharedSecret:_r,utils:gr,lengths:wr,Point:r,sign:Jr,verify:Gr,recoverPublicKey:Lr,Signature:xr,hash:e})}function _weierstrass_legacy_opts_to_new(r){const e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},M=r.Fp;let tr=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(lr=>Math.ceil(lr/2)))):void 0;const rr=Field(e.n,{BITS:r.nBitLength,allowedLengths:tr,modFromBytes:r.wrapPrivateKey}),ir={Fp:M,Fn:rr,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:ir}}function _ecdsa_legacy_opts_to_new(r){const{CURVE:e,curveOpts:M}=_weierstrass_legacy_opts_to_new(r),tr={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:M,hash:r.hash,ecdsaOpts:tr}}function _ecdsa_new_output_to_legacy(r,e){const M=e.Point;return Object.assign({},e,{ProjectivePoint:M,CURVE:Object.assign({},r,nLength(M.Fn.ORDER,M.Fn.BITS))})}function weierstrass(r){const{CURVE:e,curveOpts:M,hash:tr,ecdsaOpts:rr}=_ecdsa_legacy_opts_to_new(r),ir=weierstrassN(e,M),lr=ecdsa(ir,tr,rr);return _ecdsa_new_output_to_legacy(r,lr)}function createCurve(r,e){const M=tr=>weierstrass({...r,hash:tr});return{...M(e),create:M}}const secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_2n$1=BigInt(2);function sqrtMod(r){const e=secp256k1_CURVE.p,M=BigInt(3),tr=BigInt(6),rr=BigInt(11),ir=BigInt(22),lr=BigInt(23),dr=BigInt(44),hr=BigInt(88),fr=r*r*r%e,mr=fr*fr*r%e,_r=pow2(mr,M,e)*mr%e,gr=pow2(_r,M,e)*mr%e,wr=pow2(gr,_2n$1,e)*fr%e,yr=pow2(wr,rr,e)*wr%e,br=pow2(yr,ir,e)*yr%e,Mr=pow2(br,dr,e)*br%e,vr=pow2(Mr,hr,e)*Mr%e,Sr=pow2(vr,dr,e)*br%e,xr=pow2(Sr,M,e)*mr%e,Ar=pow2(xr,lr,e)*yr%e,Dr=pow2(Ar,tr,e)*fr%e,Ir=pow2(Dr,_2n$1,e);if(!Fpk1.eql(Fpk1.sqr(Ir),r))throw new Error("Cannot find square root");return Ir}const Fpk1=Field(secp256k1_CURVE.p,{sqrt:sqrtMod}),secp256k1$1=createCurve({...secp256k1_CURVE,Fp:Fpk1,lowS:!0,endo:secp256k1_ENDO},sha256$2);const p256_CURVE={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},p384_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},p521_CURVE={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Fp256=Field(p256_CURVE.p),Fp384=Field(p384_CURVE.p),Fp521=Field(p521_CURVE.p),p256$1=createCurve({...p256_CURVE,Fp:Fp256,lowS:!1},sha256$2),p384$1=createCurve({...p384_CURVE,Fp:Fp384,lowS:!1},sha384),p521$1=createCurve({...p521_CURVE,Fp:Fp521,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},sha512);const p256=p256$1,sha256$1=sha256$2,Rho160=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Id160=Uint8Array.from(new Array(16).fill(0).map((r,e)=>e)),Pi160=Id160.map(r=>(9*r+5)%16),idxLR=(()=>{const M=[[Id160],[Pi160]];for(let tr=0;tr<4;tr++)for(let rr of M)rr.push(rr[tr].map(ir=>Rho160[ir]));return M})(),idxL=idxLR[0],idxR=idxLR[1],shifts160=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(r=>Uint8Array.from(r)),shiftsL160=idxL.map((r,e)=>r.map(M=>shifts160[e][M])),shiftsR160=idxR.map((r,e)=>r.map(M=>shifts160[e][M])),Kl160=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Kr160=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function ripemd_f(r,e,M,tr){return r===0?e^M^tr:r===1?e&M|~e&tr:r===2?(e|~M)^tr:r===3?e&tr|M&~tr:e^(M|~tr)}const BUF_160=new Uint32Array(16);class RIPEMD160 extends HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:M,h2:tr,h3:rr,h4:ir}=this;return[e,M,tr,rr,ir]}set(e,M,tr,rr,ir){this.h0=e|0,this.h1=M|0,this.h2=tr|0,this.h3=rr|0,this.h4=ir|0}process(e,M){for(let wr=0;wr<16;wr++,M+=4)BUF_160[wr]=e.getUint32(M,!0);let tr=this.h0|0,rr=tr,ir=this.h1|0,lr=ir,dr=this.h2|0,hr=dr,fr=this.h3|0,mr=fr,_r=this.h4|0,gr=_r;for(let wr=0;wr<5;wr++){const yr=4-wr,br=Kl160[wr],Mr=Kr160[wr],vr=idxL[wr],Sr=idxR[wr],xr=shiftsL160[wr],Ar=shiftsR160[wr];for(let Dr=0;Dr<16;Dr++){const Ir=rotl(tr+ripemd_f(wr,ir,dr,fr)+BUF_160[vr[Dr]]+br,xr[Dr])+_r|0;tr=_r,_r=fr,fr=rotl(dr,10)|0,dr=ir,ir=Ir}for(let Dr=0;Dr<16;Dr++){const Ir=rotl(rr+ripemd_f(yr,lr,hr,mr)+BUF_160[Sr[Dr]]+Mr,Ar[Dr])+gr|0;rr=gr,gr=mr,mr=rotl(hr,10)|0,hr=lr,lr=Ir}}this.set(this.h1+dr+mr|0,this.h2+fr+gr|0,this.h3+_r+rr|0,this.h4+tr+lr|0,this.h0+ir+hr|0)}roundClean(){clean(BUF_160)}destroy(){this.destroyed=!0,clean(this.buffer),this.set(0,0,0,0,0)}}const ripemd160$1=createHasher(()=>new RIPEMD160),ripemd160=ripemd160$1,_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_7n=BigInt(7),_256n=BigInt(256),_0x71n=BigInt(113),SHA3_PI=[],SHA3_ROTL=[],_SHA3_IOTA=[];for(let r=0,e=_1n,M=1,tr=0;r<24;r++){[M,tr]=[tr,(2*M+3*tr)%5],SHA3_PI.push(2*(5*tr+M)),SHA3_ROTL.push((r+1)*(r+2)/2%64);let rr=_0n;for(let ir=0;ir<7;ir++)e=(e<<_1n^(e>>_7n)*_0x71n)%_256n,e&_2n&&(rr^=_1n<<(_1n<<BigInt(ir))-_1n);_SHA3_IOTA.push(rr)}const IOTAS=split(_SHA3_IOTA,!0),SHA3_IOTA_H=IOTAS[0],SHA3_IOTA_L=IOTAS[1],rotlH=(r,e,M)=>M>32?rotlBH(r,e,M):rotlSH(r,e,M),rotlL=(r,e,M)=>M>32?rotlBL(r,e,M):rotlSL(r,e,M);function keccakP(r,e=24){const M=new Uint32Array(10);for(let tr=24-e;tr<24;tr++){for(let lr=0;lr<10;lr++)M[lr]=r[lr]^r[lr+10]^r[lr+20]^r[lr+30]^r[lr+40];for(let lr=0;lr<10;lr+=2){const dr=(lr+8)%10,hr=(lr+2)%10,fr=M[hr],mr=M[hr+1],_r=rotlH(fr,mr,1)^M[dr],gr=rotlL(fr,mr,1)^M[dr+1];for(let wr=0;wr<50;wr+=10)r[lr+wr]^=_r,r[lr+wr+1]^=gr}let rr=r[2],ir=r[3];for(let lr=0;lr<24;lr++){const dr=SHA3_ROTL[lr],hr=rotlH(rr,ir,dr),fr=rotlL(rr,ir,dr),mr=SHA3_PI[lr];rr=r[mr],ir=r[mr+1],r[mr]=hr,r[mr+1]=fr}for(let lr=0;lr<50;lr+=10){for(let dr=0;dr<10;dr++)M[dr]=r[lr+dr];for(let dr=0;dr<10;dr++)r[lr+dr]^=~M[(dr+2)%10]&M[(dr+4)%10]}r[0]^=SHA3_IOTA_H[tr],r[1]^=SHA3_IOTA_L[tr]}clean(M)}class Keccak extends Hash{constructor(e,M,tr,rr=!1,ir=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=M,this.outputLen=tr,this.enableXOF=rr,this.rounds=ir,anumber$1(tr),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=u32(this.state)}clone(){return this._cloneInto()}keccak(){swap32IfBE(this.state32),keccakP(this.state32,this.rounds),swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(e){aexists(this),e=toBytes(e),abytes(e);const{blockLen:M,state:tr}=this,rr=e.length;for(let ir=0;ir<rr;){const lr=Math.min(M-this.pos,rr-ir);for(let dr=0;dr<lr;dr++)tr[this.pos++]^=e[ir++];this.pos===M&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:M,pos:tr,blockLen:rr}=this;e[tr]^=M,(M&128)!==0&&tr===rr-1&&this.keccak(),e[rr-1]^=128,this.keccak()}writeInto(e){aexists(this,!1),abytes(e),this.finish();const M=this.state,{blockLen:tr}=this;for(let rr=0,ir=e.length;rr<ir;){this.posOut>=tr&&this.keccak();const lr=Math.min(tr-this.posOut,ir-rr);e.set(M.subarray(this.posOut,this.posOut+lr),rr),this.posOut+=lr,rr+=lr}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return anumber$1(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(aoutput(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,clean(this.state)}_cloneInto(e){const{blockLen:M,suffix:tr,outputLen:rr,rounds:ir,enableXOF:lr}=this;return e||(e=new Keccak(M,tr,rr,lr,ir)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=ir,e.suffix=tr,e.outputLen=rr,e.enableXOF=lr,e.destroyed=this.destroyed,e}}const gen=(r,e,M)=>createHasher(()=>new Keccak(e,r,M)),keccak_256=gen(1,136,256/8);var canonicalize,hasRequiredCanonicalize;function requireCanonicalize(){return hasRequiredCanonicalize||(hasRequiredCanonicalize=1,canonicalize=function r(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?r(e.toJSON()):Array.isArray(e)?`[${e.reduce((rr,ir,lr)=>`${rr}${lr===0?"":","}${r(ir===void 0||typeof ir=="symbol"?null:ir)}`,"")}]`:`{${Object.keys(e).sort().reduce((tr,rr)=>{if(e[rr]===void 0||typeof e[rr]=="symbol")return tr;const ir=tr.length===0?"":",";return`${tr}${ir}${r(rr)}:${r(e[rr])}`},"")}}`}),canonicalize}var canonicalizeExports=requireCanonicalize();const canonicalizeData=getDefaultExportFromCjs(canonicalizeExports);function _catch$2(r,e){try{var M=r()}catch(tr){return e(tr)}return M&&M.then?M.then(void 0,e):M}function inMemoryCache(){const r=new Map;return function(e,M){try{let rr=function(lr){if(tr)return lr;const dr=r.get(e.didUrl);return dr!==void 0?dr:Promise.resolve(M()).then(function(hr){var fr;return((fr=hr.didResolutionMetadata)==null?void 0:fr.error)!=="notFound"&&r.set(e.didUrl,hr),hr})},tr;const ir=(function(){if(e.params&&e.params["no-cache"]==="true")return Promise.resolve(M()).then(function(lr){return tr=1,lr})})();return Promise.resolve(ir&&ir.then?ir.then(rr):rr(ir))}catch(tr){return Promise.reject(tr)}}}function noCache(r,e){return e()}const PCT_ENCODED="(?:%[0-9a-fA-F]{2})",ID_CHAR=`(?:[a-zA-Z0-9._-]|${PCT_ENCODED})`,METHOD="([a-z0-9]+)",METHOD_ID=`((?:${ID_CHAR}*:)*(${ID_CHAR}+))`,PARAM_CHAR="[a-zA-Z0-9_.:%-]",PARAM=`;${PARAM_CHAR}+=${PARAM_CHAR}*`,PARAMS=`((${PARAM})*)`,PATH="(/[^#?]*)?",QUERY="([?][^#]*)?",FRAGMENT="(#.*)?",DID_MATCHER=new RegExp(`^did:${METHOD}:${METHOD_ID}${PARAMS}${PATH}${QUERY}${FRAGMENT}$`);function parse(r){if(r===""||!r)return null;const e=r.match(DID_MATCHER);if(e){const M={did:`did:${e[1]}:${e[2]}`,method:e[1],id:e[2],didUrl:r};if(e[4]){const tr=e[4].slice(1).split(";");M.params={};for(const rr of tr){const ir=rr.split("=");M.params[ir[0]]=ir[1]}}return e[6]&&(M.path=e[6]),e[7]&&(M.query=e[7].slice(1)),e[8]&&(M.fragment=e[8].slice(1)),M}return null}const EMPTY_RESULT={didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};function wrapLegacyResolver(r){return function(e,M,tr){try{return Promise.resolve(_catch$2(function(){return Promise.resolve(r(e,M,tr)).then(function(rr){return{...EMPTY_RESULT,didResolutionMetadata:{contentType:"application/did+ld+json"},didDocument:rr}})},function(rr){return{...EMPTY_RESULT,didResolutionMetadata:{error:"notFound",message:rr.toString()}}}))}catch(rr){return Promise.reject(rr)}}}class Resolver{constructor(e={},M={}){this.registry=void 0,this.cache=void 0,this.registry=e,this.cache=M.cache===!0?inMemoryCache():M.cache||noCache,M.legacyResolvers&&Object.keys(M.legacyResolvers).map(tr=>{this.registry[tr]||(this.registry[tr]=wrapLegacyResolver(M.legacyResolvers[tr]))})}resolve(e,M={}){try{const tr=this,rr=parse(e);if(rr===null)return Promise.resolve({...EMPTY_RESULT,didResolutionMetadata:{error:"invalidDid"}});const ir=tr.registry[rr.method];return ir?Promise.resolve(tr.cache(rr,()=>ir(rr.did,rr,tr,M))):Promise.resolve({...EMPTY_RESULT,didResolutionMetadata:{error:"unsupportedDidMethod"}})}catch(tr){return Promise.reject(tr)}}}function isBytes(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function isArrayOf(r,e){return Array.isArray(e)?e.length===0?!0:r?e.every(M=>typeof M=="string"):e.every(M=>Number.isSafeInteger(M)):!1}function afn(r){if(typeof r!="function")throw new Error("function expected");return!0}function astr(r,e){if(typeof e!="string")throw new Error(`${r}: string expected`);return!0}function anumber(r){if(!Number.isSafeInteger(r))throw new Error(`invalid integer: ${r}`)}function aArr(r){if(!Array.isArray(r))throw new Error("array expected")}function astrArr(r,e){if(!isArrayOf(!0,e))throw new Error(`${r}: array of strings expected`)}function anumArr(r,e){if(!isArrayOf(!1,e))throw new Error(`${r}: array of numbers expected`)}function chain(...r){const e=ir=>ir,M=(ir,lr)=>dr=>ir(lr(dr)),tr=r.map(ir=>ir.encode).reduceRight(M,e),rr=r.map(ir=>ir.decode).reduce(M,e);return{encode:tr,decode:rr}}function alphabet$1(r){const e=typeof r=="string"?r.split(""):r,M=e.length;astrArr("alphabet",e);const tr=new Map(e.map((rr,ir)=>[rr,ir]));return{encode:rr=>(aArr(rr),rr.map(ir=>{if(!Number.isSafeInteger(ir)||ir<0||ir>=M)throw new Error(`alphabet.encode: digit index outside alphabet "${ir}". Allowed: ${r}`);return e[ir]})),decode:rr=>(aArr(rr),rr.map(ir=>{astr("alphabet.decode",ir);const lr=tr.get(ir);if(lr===void 0)throw new Error(`Unknown letter: "${ir}". Allowed: ${r}`);return lr}))}}function join(r=""){return astr("join",r),{encode:e=>(astrArr("join.decode",e),e.join(r)),decode:e=>(astr("join.decode",e),e.split(r))}}const gcd=(r,e)=>e===0?r:gcd(e,r%e),radix2carry=(r,e)=>r+(e-gcd(r,e)),powers=(()=>{let r=[];for(let e=0;e<40;e++)r.push(2**e);return r})();function convertRadix2(r,e,M,tr){if(aArr(r),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(M<=0||M>32)throw new Error(`convertRadix2: wrong to=${M}`);if(radix2carry(e,M)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${M} carryBits=${radix2carry(e,M)}`);let rr=0,ir=0;const lr=powers[e],dr=powers[M]-1,hr=[];for(const fr of r){if(anumber(fr),fr>=lr)throw new Error(`convertRadix2: invalid data word=${fr} from=${e}`);if(rr=rr<<e|fr,ir+e>32)throw new Error(`convertRadix2: carry overflow pos=${ir} from=${e}`);for(ir+=e;ir>=M;ir-=M)hr.push((rr>>ir-M&dr)>>>0);const mr=powers[ir];if(mr===void 0)throw new Error("invalid carry");rr&=mr-1}if(rr=rr<<M-ir&dr,!tr&&ir>=e)throw new Error("Excess padding");if(!tr&&rr>0)throw new Error(`Non-zero padding: ${rr}`);return tr&&ir>0&&hr.push(rr>>>0),hr}function radix2(r,e=!1){if(anumber(r),r<=0||r>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,r)>32||radix2carry(r,8)>32)throw new Error("radix2: carry overflow");return{encode:M=>{if(!isBytes(M))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2(Array.from(M),8,r,!e)},decode:M=>(anumArr("radix2.decode",M),Uint8Array.from(convertRadix2(M,r,8,e)))}}function unsafeWrapper(r){return afn(r),function(...e){try{return r.apply(null,e)}catch{}}}const BECH_ALPHABET=chain(alphabet$1("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join("")),POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(r){const e=r>>25;let M=(r&33554431)<<5;for(let tr=0;tr<POLYMOD_GENERATORS.length;tr++)(e>>tr&1)===1&&(M^=POLYMOD_GENERATORS[tr]);return M}function bechChecksum(r,e,M=1){const tr=r.length;let rr=1;for(let ir=0;ir<tr;ir++){const lr=r.charCodeAt(ir);if(lr<33||lr>126)throw new Error(`Invalid prefix (${r})`);rr=bech32Polymod(rr)^lr>>5}rr=bech32Polymod(rr);for(let ir=0;ir<tr;ir++)rr=bech32Polymod(rr)^r.charCodeAt(ir)&31;for(let ir of e)rr=bech32Polymod(rr)^ir;for(let ir=0;ir<6;ir++)rr=bech32Polymod(rr);return rr^=M,BECH_ALPHABET.encode(convertRadix2([rr%powers[30]],30,5,!1))}function genBech32(r){const e=r==="bech32"?1:734539939,M=radix2(5),tr=M.decode,rr=M.encode,ir=unsafeWrapper(tr);function lr(_r,gr,wr=90){astr("bech32.encode prefix",_r),isBytes(gr)&&(gr=Array.from(gr)),anumArr("bech32.encode",gr);const yr=_r.length;if(yr===0)throw new TypeError(`Invalid prefix length ${yr}`);const br=yr+7+gr.length;if(wr!==!1&&br>wr)throw new TypeError(`Length ${br} exceeds limit ${wr}`);const Mr=_r.toLowerCase(),vr=bechChecksum(Mr,gr,e);return`${Mr}1${BECH_ALPHABET.encode(gr)}${vr}`}function dr(_r,gr=90){astr("bech32.decode input",_r);const wr=_r.length;if(wr<8||gr!==!1&&wr>gr)throw new TypeError(`invalid string length: ${wr} (${_r}). Expected (8..${gr})`);const yr=_r.toLowerCase();if(_r!==yr&&_r!==_r.toUpperCase())throw new Error("String must be lowercase or uppercase");const br=yr.lastIndexOf("1");if(br===0||br===-1)throw new Error('Letter "1" must be present between prefix and data only');const Mr=yr.slice(0,br),vr=yr.slice(br+1);if(vr.length<6)throw new Error("Data must be at least 6 characters long");const Sr=BECH_ALPHABET.decode(vr).slice(0,-6),xr=bechChecksum(Mr,Sr,e);if(!vr.endsWith(xr))throw new Error(`Invalid checksum in ${_r}: expected "${xr}"`);return{prefix:Mr,words:Sr}}const hr=unsafeWrapper(dr);function fr(_r){const{prefix:gr,words:wr}=dr(_r,!1);return{prefix:gr,words:wr,bytes:tr(wr)}}function mr(_r,gr){return lr(_r,rr(gr))}return{encode:lr,decode:dr,encodeFromBytes:mr,decodeToBytes:fr,decodeUnsafe:hr,fromWords:tr,fromWordsUnsafe:ir,toWords:rr}}const bech32=genBech32("bech32"),u8a={toString:toString$2,fromString:fromString$2,concat:concat$1};function bytesToBase64url(r){return u8a.toString(r,"base64url")}function base64ToBytes(r){const e=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return u8a.fromString(e,"base64url")}function base58ToBytes(r){return u8a.fromString(r,"base58btc")}function bytesToBase58(r){return u8a.toString(r,"base58btc")}const SUPPORTED_PUBLIC_KEY_TYPES={ES256:["JsonWebKey2020","Multikey","EcdsaSecp256r1VerificationKey2019"],ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","JsonWebKey2020","Multikey"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","ConditionalProof2022","JsonWebKey2020","Multikey"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018","Ed25519VerificationKey2020","JsonWebKey2020","Multikey"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018","Ed25519VerificationKey2020","JsonWebKey2020","Multikey"]},VM_TO_KEY_TYPE={Secp256k1SignatureVerificationKey2018:"Secp256k1",Secp256k1VerificationKey2018:"Secp256k1",EcdsaSecp256k1VerificationKey2019:"Secp256k1",EcdsaPublicKeySecp256k1:"Secp256k1",EcdsaSecp256k1RecoveryMethod2020:"Secp256k1",EcdsaSecp256r1VerificationKey2019:"P-256",Ed25519VerificationKey2018:"Ed25519",Ed25519VerificationKey2020:"Ed25519",ED25519SignatureVerification:"Ed25519",X25519KeyAgreementKey2019:"X25519",X25519KeyAgreementKey2020:"X25519",ConditionalProof2022:void 0,JsonWebKey2020:void 0,Multikey:void 0},supportedCodecs={"ed25519-pub":237,"x25519-pub":236,"secp256k1-pub":231,"bls12_381-g1-pub":234,"bls12_381-g2-pub":235,"p256-pub":4608},CODEC_TO_KEY_TYPE={"bls12_381-g1-pub":"Bls12381G1","bls12_381-g2-pub":"Bls12381G2","ed25519-pub":"Ed25519","p256-pub":"P-256","secp256k1-pub":"Secp256k1","x25519-pub":"X25519"};function extractPublicKeyBytes(r){if(r.publicKeyBase58)return{keyBytes:base58ToBytes(r.publicKeyBase58),keyType:VM_TO_KEY_TYPE[r.type]};if(r.publicKeyBase64)return{keyBytes:base64ToBytes(r.publicKeyBase64),keyType:VM_TO_KEY_TYPE[r.type]};if(r.publicKeyHex)return{keyBytes:hexToBytes(r.publicKeyHex),keyType:VM_TO_KEY_TYPE[r.type]};if(r.publicKeyJwk&&r.publicKeyJwk.crv==="secp256k1"&&r.publicKeyJwk.x&&r.publicKeyJwk.y)return{keyBytes:secp256k1$1.ProjectivePoint.fromAffine({x:bytesToBigInt(base64ToBytes(r.publicKeyJwk.x)),y:bytesToBigInt(base64ToBytes(r.publicKeyJwk.y))}).toRawBytes(!1),keyType:"Secp256k1"};if(r.publicKeyJwk&&r.publicKeyJwk.crv==="P-256"&&r.publicKeyJwk.x&&r.publicKeyJwk.y)return{keyBytes:p256.ProjectivePoint.fromAffine({x:bytesToBigInt(base64ToBytes(r.publicKeyJwk.x)),y:bytesToBigInt(base64ToBytes(r.publicKeyJwk.y))}).toRawBytes(!1),keyType:"P-256"};if(r.publicKeyJwk&&r.publicKeyJwk.kty==="OKP"&&["Ed25519","X25519"].includes(r.publicKeyJwk.crv??"")&&r.publicKeyJwk.x)return{keyBytes:base64ToBytes(r.publicKeyJwk.x),keyType:r.publicKeyJwk.crv};if(r.publicKeyMultibase){const{keyBytes:e,keyType:M}=multibaseToBytes(r.publicKeyMultibase);return{keyBytes:e,keyType:M??VM_TO_KEY_TYPE[r.type]}}return{keyBytes:new Uint8Array}}function multibaseToBytes(r){const e=srcExports$1.decode(r);if([32,33,48,64,65,96].includes(e.length))return{keyBytes:e};try{const[M,tr]=decode$6(e),rr=Object.entries(supportedCodecs).filter(([,ir])=>ir===M)?.[0][0]??"";return{keyBytes:e.slice(tr),keyType:CODEC_TO_KEY_TYPE[rr]}}catch{return{keyBytes:e}}}function hexToBytes(r,e){let M=r.startsWith("0x")?r.substring(2):r;return M.length%2!==0&&(M=`0${M}`),u8a.fromString(M.toLowerCase(),"base16")}function encodeBase64url(r){return bytesToBase64url(u8a.fromString(r))}function decodeBase64url(r){return u8a.toString(base64ToBytes(r))}function bytesToHex(r){return u8a.toString(r,"base16")}function bytesToBigInt(r){return BigInt("0x"+u8a.toString(r,"base16"))}function stringToBytes(r){return u8a.fromString(r,"utf-8")}function toJose({r,s:e,recoveryParam:M},tr){const rr=new Uint8Array(tr?65:64);if(rr.set(u8a.fromString(r,"base16"),0),rr.set(u8a.fromString(e,"base16"),32),tr){if(typeof M>"u")throw new Error("Signer did not return a recoveryParam");rr[64]=M}return bytesToBase64url(rr)}function fromJose(r){const e=base64ToBytes(r);if(e.length<64||e.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${e.length}`);const M=bytesToHex(e.slice(0,32)),tr=bytesToHex(e.slice(32,64)),rr=e.length===65?e[64]:void 0;return{r:M,s:tr,recoveryParam:rr}}function sha256(r){const e=typeof r=="string"?fromString$2(r):r;return sha256$1(e)}const keccak=keccak_256;function toEthereumAddress(r){const e=fromString$2(r.slice(2),"base16");return`0x${toString$2(keccak(e).slice(-20),"base16")}`}function instanceOfEcdsaSignature(r){return typeof r=="object"&&"r"in r&&"s"in r}function ES256SignerAlg(){return function(e,M){try{return Promise.resolve(M(e)).then(function(tr){return instanceOfEcdsaSignature(tr)?toJose(tr):tr})}catch(tr){return Promise.reject(tr)}}}function ES256KSignerAlg(r){return function(M,tr){try{return Promise.resolve(tr(M)).then(function(rr){if(instanceOfEcdsaSignature(rr))return toJose(rr,r);if(r&&typeof fromJose(rr).recoveryParam>"u")throw new Error("not_supported: ES256K-R not supported when signer doesn't provide a recovery param");return rr})}catch(rr){return Promise.reject(rr)}}}function Ed25519SignerAlg(){return function(e,M){try{return Promise.resolve(M(e)).then(function(tr){if(instanceOfEcdsaSignature(tr))throw new Error("invalid_config: expected a signer function that returns a string instead of signature object");return tr})}catch(tr){return Promise.reject(tr)}}}const algorithms$1={ES256:ES256SignerAlg(),ES256K:ES256KSignerAlg(),"ES256K-R":ES256KSignerAlg(!0),Ed25519:Ed25519SignerAlg(),EdDSA:Ed25519SignerAlg()};function SignerAlg(r){const e=algorithms$1[r];if(!e)throw new Error(`not_supported: Unsupported algorithm ${r}`);return e}function publicKeyToAddress$1(r,e){const M=bytesToHex(base58ToBytes(e).slice(0,1)),tr=hexToBytes(r),rr=ripemd160(sha256(tr)),ir=M+bytesToHex(rr),lr=sha256(hexToBytes(ir)),dr=sha256(lr),hr=bytesToHex(dr).substring(0,8),fr=ir+hr;return bytesToBase58(hexToBytes(fr))}function publicKeyToAddress(r,e){const M=secp256k1$1.ProjectivePoint.fromHex(r).toRawBytes(),tr=ripemd160(sha256(M)),rr=bech32.toWords(tr);return bech32.encode(e,rr).replace(e,"")}function verifyBlockchainAccountId(r,e){if(e){const M=e.split(":");switch(M[0]){case"bip122":M[M.length-1]=publicKeyToAddress$1(r,M[M.length-1]);break;case"cosmos":M[M.length-1]=publicKeyToAddress(r,M[1]);break;case"eip155":M[M.length-1]=toEthereumAddress(r);break;default:return!1}return M.join(":").toLowerCase()===e.toLowerCase()}return!1}function toSignatureObject(r,e=!1){const M=base64ToBytes(r);if(M.length!==(e?65:64))throw new Error("wrong signature length");const tr=bytesToHex(M.slice(0,32)),rr=bytesToHex(M.slice(32,64)),ir={r:tr,s:rr};return e&&(ir.recoveryParam=M[64]),ir}function toSignatureObject2(r,e=!1){const M=base64ToBytes(r);if(M.length!==(e?65:64))throw new Error("wrong signature length");return{compact:M.slice(0,64),recovery:M[64]}}function verifyES256(r,e,M){const tr=sha256(r),rr=p256.Signature.fromCompact(toSignatureObject2(e).compact),lr=M.filter(dr=>!dr.ethereumAddress&&!dr.blockchainAccountId).find(dr=>{try{const{keyBytes:hr}=extractPublicKeyBytes(dr);return p256.verify(rr,tr,hr)}catch{return!1}});if(!lr)throw new Error("invalid_signature: Signature invalid for JWT");return lr}function verifyES256K(r,e,M){const tr=sha256(r),rr=secp256k1$1.Signature.fromCompact(base64ToBytes(e)).normalizeS(),ir=M.filter(hr=>!hr.ethereumAddress&&!hr.blockchainAccountId),lr=M.filter(hr=>hr.ethereumAddress||hr.blockchainAccountId);let dr=ir.find(hr=>{try{const{keyBytes:fr}=extractPublicKeyBytes(hr);return secp256k1$1.verify(rr,tr,fr)}catch{return!1}});if(!dr&&lr.length>0&&(dr=verifyRecoverableES256K(r,e,lr)),!dr)throw new Error("invalid_signature: Signature invalid for JWT");return dr}function verifyRecoverableES256K(r,e,M){const tr=[];if(e.length>86)tr.push(toSignatureObject2(e,!0));else{const lr=toSignatureObject2(e,!1);tr.push({...lr,recovery:0}),tr.push({...lr,recovery:1})}const rr=sha256(r),ir=lr=>{const hr=secp256k1$1.Signature.fromCompact(lr.compact).addRecoveryBit(lr.recovery||0).recoverPublicKey(rr),fr=toEthereumAddress(hr.toHex(!1)).toLowerCase(),mr=hr.toHex(!1),_r=hr.toHex(!0);return M.find(gr=>{const{keyBytes:wr}=extractPublicKeyBytes(gr),yr=bytesToHex(wr);return yr===mr||yr===_r||gr.ethereumAddress?.toLowerCase()===fr||gr.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===fr||verifyBlockchainAccountId(mr,gr.blockchainAccountId)})};for(const lr of tr){const dr=ir(lr);if(dr)return dr}throw new Error("invalid_signature: Signature invalid for JWT")}function verifyEd25519(r,e,M){const tr=stringToBytes(r),rr=base64ToBytes(e),ir=M.find(lr=>{const{keyBytes:dr,keyType:hr}=extractPublicKeyBytes(lr);return hr==="Ed25519"?ed25519$1.verify(rr,tr,dr):!1});if(!ir)throw new Error("invalid_signature: Signature invalid for JWT");return ir}const algorithms={ES256:verifyES256,ES256K:verifyES256K,"ES256K-R":verifyRecoverableES256K,Ed25519:verifyEd25519,EdDSA:verifyEd25519};function VerifierAlgorithm(r){const e=algorithms[r];if(!e)throw new Error(`not_supported: Unsupported algorithm ${r}`);return e}VerifierAlgorithm.toSignatureObject=toSignatureObject;const JWT_ERROR={INVALID_JWT:"invalid_jwt",INVALID_AUDIENCE:"invalid_config",INVALID_SIGNATURE:"invalid_signature",NO_SUITABLE_KEYS:"no_suitable_keys",NOT_SUPPORTED:"not_supported",RESOLVER_ERROR:"resolver_error"};function _catch$1(r,e){try{var M=r()}catch(tr){return e(tr)}return M&&M.then?M.then(void 0,e):M}const verifyConditionDelegated=function(r,{header:e,payload:M,data:tr,signature:rr},ir,lr){try{if(!ir.conditionDelegated)throw new Error("Expected conditionDelegated");if(!lr.resolver)throw new Error("Expected resolver");let dr;const hr=ir.conditionDelegated;return Promise.resolve(resolveAuthenticator(lr.resolver,e.alg,hr,lr.proofPurpose)).then(function(fr){let mr;function _r(br){if(dr)return ir;throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: condition for authenticator ${ir.id} is not met.`)}const gr=fr.didResolutionResult;if(!gr?.didDocument)throw new Error(`${JWT_ERROR.RESOLVER_ERROR}: Could not resolve delegated DID ${hr}.`);const wr=fr.authenticators.find(br=>br.id===hr);if(!wr)throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: Could not find delegated authenticator ${hr} in it's DID Document`);const yr=(function(){if(wr.type===CONDITIONAL_PROOF_2022)return Promise.resolve(verifyJWT(r,{...lr,didAuthenticator:{didResolutionResult:gr,authenticators:[wr],issuer:wr.id}})).then(function({verified:br}){br&&(dr=wr)});try{dr=verifyJWTDecoded({header:e,payload:M,data:tr,signature:rr},wr)}catch(br){if(!br.message.startsWith("invalid_signature:"))throw br}})();return yr&&yr.then?yr.then(_r):_r(yr)})}catch(dr){return Promise.reject(dr)}},_iteratorSymbol$1=typeof Symbol<"u"?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function _settle$2(r,e,M){if(!r.s){if(M instanceof _Pact$2)if(M.s)e&1&&(e=M.s),M=M.v;else{M.o=_settle$2.bind(null,r,e);return}if(M&&M.then){M.then(_settle$2.bind(null,r,e),_settle$2.bind(null,r,2));return}r.s=e,r.v=M;const tr=r.o;tr&&tr(r)}}const _Pact$2=(function(){function r(){}return r.prototype.then=function(e,M){const tr=new r,rr=this.s;if(rr){const ir=rr&1?e:M;if(ir){try{_settle$2(tr,1,ir(this.v))}catch(lr){_settle$2(tr,2,lr)}return tr}else return this}return this.o=function(ir){try{const lr=ir.v;ir.s&1?_settle$2(tr,1,e?e(lr):lr):M?_settle$2(tr,1,M(lr)):_settle$2(tr,2,lr)}catch(lr){_settle$2(tr,2,lr)}},tr},r})();function _isSettledPact$2(r){return r instanceof _Pact$2&&r.s&1}function _forTo$2(r,e,M){var tr=-1,rr,ir;function lr(dr){try{for(;++tr<r.length&&(!M||!M());)if(dr=e(tr),dr&&dr.then)if(_isSettledPact$2(dr))dr=dr.v;else{dr.then(lr,ir||(ir=_settle$2.bind(null,rr=new _Pact$2,2)));return}rr?_settle$2(rr,1,dr):rr=dr}catch(hr){_settle$2(rr||(rr=new _Pact$2),2,hr)}}return lr(),rr}const verifyConditionWeightedThreshold=function(r,{header:e,payload:M,data:tr,signature:rr},ir,lr){try{let dr=function(wr){if(hr)return wr;throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: condition for authenticator ${ir.id} is not met.`)},hr;if(!ir.conditionWeightedThreshold||!ir.threshold)throw new Error("Expected conditionWeightedThreshold and threshold");const fr=[],mr=ir.threshold;let _r=0;const gr=_forOf$1(ir.conditionWeightedThreshold,function(wr){function yr(Sr){if(hr)return Sr;if(Mr&&!fr.includes(Mr.id)&&(fr.push(Mr.id),_r+=wr.weight,_r>=mr))return hr=1,ir}const br=wr.condition;let Mr;const vr=_catch$1(function(){if(br.type===CONDITIONAL_PROOF_2022){if(!lr.didAuthenticator)throw new Error("Expected didAuthenticator");const Sr={...lr,didAuthenticator:{didResolutionResult:lr.didAuthenticator?.didResolutionResult,authenticators:[br],issuer:br.id}};return Promise.resolve(verifyJWT(r,Sr)).then(function({verified:xr}){xr&&(Mr=br)})}else return Promise.resolve(verifyJWTDecoded({header:e,payload:M,data:tr,signature:rr},br)).then(function(Sr){Mr=Sr})},function(Sr){if(!Sr.message.startsWith(JWT_ERROR.INVALID_SIGNATURE))throw Sr});return vr&&vr.then?vr.then(yr):yr(vr)},function(){return hr});return Promise.resolve(gr&&gr.then?gr.then(dr):dr(gr))}catch(dr){return Promise.reject(dr)}};function _forOf$1(r,e,M){if(typeof r[_iteratorSymbol$1]=="function"){let mr=function(_r){try{for(;!(rr=tr.next()).done&&(!M||!M());)if(_r=e(rr.value),_r&&_r.then)if(_isSettledPact$2(_r))_r=_r.v;else{_r.then(mr,lr||(lr=_settle$2.bind(null,ir=new _Pact$2,2)));return}ir?_settle$2(ir,1,_r):ir=_r}catch(gr){_settle$2(ir||(ir=new _Pact$2),2,gr)}};var tr=r[_iteratorSymbol$1](),rr,ir,lr;if(mr(),tr.return){var dr=function(_r){try{rr.done||tr.return()}catch{}return _r};if(ir&&ir.then)return ir.then(dr,function(_r){throw dr(_r)});dr()}return ir}if(!("length"in r))throw new TypeError("Object is not iterable");for(var hr=[],fr=0;fr<r.length;fr++)hr.push(r[fr]);return _forTo$2(hr,function(mr){return e(hr[mr])},M)}const verifyConditionalProof=function(r,{header:e,payload:M,signature:tr,data:rr},ir,lr){try{if(ir.conditionWeightedThreshold)return verifyConditionWeightedThreshold(r,{header:e,payload:M,data:rr,signature:tr},ir,lr);if(ir.conditionDelegated)return verifyConditionDelegated(r,{header:e,payload:M,data:rr,signature:tr},ir,lr);throw new Error(`${JWT_ERROR.INVALID_JWT}: conditional proof type did not find condition for authenticator ${ir.id}.`)}catch(dr){return Promise.reject(dr)}},verifyProof=function(r,{header:e,payload:M,signature:tr,data:rr},ir,lr){try{return ir.type===CONDITIONAL_PROOF_2022?verifyConditionalProof(r,{payload:M,header:e,signature:tr,data:rr},ir,lr):Promise.resolve(verifyJWTDecoded({header:e,payload:M,data:rr,signature:tr},[ir]))}catch(dr){return Promise.reject(dr)}},CONDITIONAL_PROOF_2022="ConditionalProof2022";function _settle$1(r,e,M){if(!r.s){if(M instanceof _Pact$1)if(M.s)e&1&&(e=M.s),M=M.v;else{M.o=_settle$1.bind(null,r,e);return}if(M&&M.then){M.then(_settle$1.bind(null,r,e),_settle$1.bind(null,r,2));return}r.s=e,r.v=M;const tr=r.o;tr&&tr(r)}}const _Pact$1=(function(){function r(){}return r.prototype.then=function(e,M){const tr=new r,rr=this.s;if(rr){const ir=rr&1?e:M;if(ir){try{_settle$1(tr,1,ir(this.v))}catch(lr){_settle$1(tr,2,lr)}return tr}else return this}return this.o=function(ir){try{const lr=ir.v;ir.s&1?_settle$1(tr,1,e?e(lr):lr):M?_settle$1(tr,1,M(lr)):_settle$1(tr,2,lr)}catch(lr){_settle$1(tr,2,lr)}},tr},r})();function _isSettledPact$1(r){return r instanceof _Pact$1&&r.s&1}function _forTo$1(r,e,M){var tr=-1,rr,ir;function lr(dr){try{for(;++tr<r.length&&(!M||!M());)if(dr=e(tr),dr&&dr.then)if(_isSettledPact$1(dr))dr=dr.v;else{dr.then(lr,ir||(ir=_settle$1.bind(null,rr=new _Pact$1,2)));return}rr?_settle$1(rr,1,dr):rr=dr}catch(hr){_settle$1(rr||(rr=new _Pact$1),2,hr)}}return lr(),rr}function _catch(r,e){try{var M=r()}catch(tr){return e(tr)}return M&&M.then?M.then(void 0,e):M}function _for$1(r,e,M){for(var tr;;){var rr=r();if(_isSettledPact$1(rr)&&(rr=rr.v),!rr)return ir;if(rr.then){tr=0;break}var ir=M();if(ir&&ir.then)if(_isSettledPact$1(ir))ir=ir.s;else{tr=1;break}var lr}var dr=new _Pact$1,hr=_settle$1.bind(null,dr,2);return(tr===0?rr.then(mr):tr===1?ir.then(fr):lr.then(_r)).then(void 0,hr),dr;function fr(gr){ir=gr;do{if(rr=r(),!rr||_isSettledPact$1(rr)&&!rr.v){_settle$1(dr,1,ir);return}if(rr.then){rr.then(mr).then(void 0,hr);return}ir=M(),_isSettledPact$1(ir)&&(ir=ir.v)}while(!ir||!ir.then);ir.then(fr).then(void 0,hr)}function mr(gr){gr?(ir=M(),ir&&ir.then?ir.then(fr).then(void 0,hr):fr(ir)):_settle$1(dr,1,ir)}function _r(){(rr=r())?rr.then?rr.then(mr).then(void 0,hr):mr(rr):_settle$1(dr,1,ir)}}const resolveAuthenticator=function(r,e,M,tr){try{const rr=SUPPORTED_PUBLIC_KEY_TYPES[e];if(!rr||rr.length===0)throw new Error(`${JWT_ERROR.NOT_SUPPORTED}: No supported signature types for algorithm ${e}`);let ir;return Promise.resolve(r.resolve(M,{accept:DID_JSON$1})).then(function(lr){if(Object.getOwnPropertyNames(lr).indexOf("didDocument")===-1?ir={didDocument:lr,didDocumentMetadata:{},didResolutionMetadata:{contentType:DID_JSON$1}}:ir=lr,ir.didResolutionMetadata?.error||ir.didDocument==null){const{error:mr,message:_r}=ir.didResolutionMetadata;throw new Error(`${JWT_ERROR.RESOLVER_ERROR}: Unable to resolve DID document for ${M}: ${mr}, ${_r||""}`)}const dr=(mr,_r)=>{const gr=mr.filter(({id:wr})=>_r===wr);return gr.length>0?gr[0]:null};let hr=[...ir?.didDocument?.verificationMethod||[],...ir?.didDocument?.publicKey||[]];typeof tr=="string"&&(tr.startsWith("assertion")&&!Object.getOwnPropertyNames(ir?.didDocument).includes("assertionMethod")&&(ir.didDocument={...ir.didDocument},ir.didDocument.assertionMethod=[...hr.map(mr=>mr.id)]),hr=(ir.didDocument[tr]||[]).map(mr=>typeof mr=="string"?dr(hr,mr):typeof mr.publicKey=="string"?dr(hr,mr.publicKey):mr).filter(mr=>mr!=null));const fr=hr.filter(({type:mr})=>rr.find(_r=>_r===mr));if(typeof tr=="string"&&(!fr||fr.length===0))throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${M} does not have public keys suitable for ${e} with ${tr} purpose`);if(!fr||fr.length===0)throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${M} does not have public keys for ${e}`);return{authenticators:fr,issuer:M,didResolutionResult:ir}})}catch(rr){return Promise.reject(rr)}},verifyJWT=function(r,e={resolver:void 0,auth:void 0,audience:void 0,callbackUrl:void 0,skewTime:void 0,proofPurpose:void 0,policies:{},didAuthenticator:void 0}){try{let M=function(){let wr;function yr(Sr){if(Mr){const xr=typeof e.policies?.now=="number"?e.policies.now:Math.floor(Date.now()/1e3),Ar=typeof e.skewTime<"u"&&e.skewTime>=0?e.skewTime:NBF_SKEW,Dr=xr+Ar;if(e.policies?.nbf!==!1&&tr.nbf){if(tr.nbf>Dr)throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${tr.nbf}`)}else if(e.policies?.iat!==!1&&tr.iat&&tr.iat>Dr)throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${tr.iat}`);if(e.policies?.exp!==!1&&tr.exp&&tr.exp<=xr-Ar)throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${tr.exp} < now: ${xr}`);if(e.policies?.aud!==!1&&tr.aud){if(!e.audience&&!e.callbackUrl)throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`);if(typeof(Array.isArray(tr.aud)?tr.aud:[tr.aud]).find(Or=>e.audience===Or||e.callbackUrl===Or)>"u")throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)}return{verified:!0,payload:tr,didResolutionResult:_r,issuer:mr,signer:Mr,jwt:r,policies:e.policies}}throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`)}const{did:br}=parse(hr);let Mr=null;const vr=(function(){if(br!==hr){const Sr=fr.find(xr=>xr.id===hr);if(!Sr)throw new Error(`${JWT_ERROR.INVALID_JWT}: No authenticator found for did URL ${hr}`);return Promise.resolve(verifyProof(r,{payload:tr,header:rr,signature:ir,data:lr},Sr,e)).then(function(xr){Mr=xr})}else{let Sr=0;return _for$1(function(){return!wr&&!Mr&&Sr<fr.length},void 0,function(){function xr(Ir){Sr++}const Ar=fr[Sr],Dr=_catch(function(){return Promise.resolve(verifyProof(r,{payload:tr,header:rr,signature:ir,data:lr},Ar,e)).then(function(Ir){Mr=Ir})},function(Ir){if(!Ir.message.includes(JWT_ERROR.INVALID_SIGNATURE)||Sr===fr.length-1)throw Ir});return Dr&&Dr.then?Dr.then(xr):xr(Dr)})}})();return vr&&vr.then?vr.then(yr):yr(vr)};if(!e.resolver)throw new Error("missing_resolver: No DID resolver has been configured");const{payload:tr,header:rr,signature:ir,data:lr}=decodeJWT(r,!1),dr=Object.prototype.hasOwnProperty.call(e,"auth")?e.auth?"authentication":void 0:e.proofPurpose;let hr;if(!tr.iss&&!tr.client_id)throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`);if(e.didAuthenticator)hr=e.didAuthenticator.issuer;else if(tr.iss===SELF_ISSUED_V2||tr.iss===SELF_ISSUED_V2_VC_INTEROP){if(!tr.sub)throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`);typeof tr.sub_jwk>"u"?hr=tr.sub:hr=(rr.kid||"").split("#")[0]}else if(tr.iss===SELF_ISSUED_V0_1){if(!tr.did)throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`);hr=tr.did}else if(!tr.iss&&tr.scope==="openid"&&tr.redirect_uri){if(!tr.client_id)throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`);hr=tr.client_id}else hr=tr.iss;if(!hr)throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`);let fr,mr,_r;const gr=(function(){if(e.didAuthenticator)({didResolutionResult:_r,authenticators:fr,issuer:mr}=e.didAuthenticator);else return Promise.resolve(resolveAuthenticator(e.resolver,rr.alg,hr,dr)).then(function(wr){({didResolutionResult:_r,authenticators:fr,issuer:mr}=wr),e.didAuthenticator={didResolutionResult:_r,authenticators:fr,issuer:mr}})})();return Promise.resolve(gr&&gr.then?gr.then(M):M(gr))}catch(M){return Promise.reject(M)}},createMultisignatureJWT=function(r,{expiresIn:e,canonicalize:M},tr){try{if(tr.length===0)throw new Error("invalid_argument: must provide one or more issuers");let rr=r,ir="";const lr=_forTo$1(tr,function(dr){const hr=tr[dr],fr={typ:"JWT",alg:hr.alg};return dr!==0&&(fr.cty="JWT"),Promise.resolve(createJWT(rr,{...hr,canonicalize:M,expiresIn:e},fr)).then(function(mr){ir=mr,rr={jwt:ir}})});return Promise.resolve(lr&&lr.then?lr.then(function(){return ir}):ir)}catch(rr){return Promise.reject(rr)}},createJWT=function(r,{issuer:e,signer:M,alg:tr,expiresIn:rr,canonicalize:ir},lr={}){try{if(!M)throw new Error("missing_signer: No Signer functionality has been configured");if(!e)throw new Error("missing_issuer: No issuing DID has been configured");lr.typ||(lr.typ="JWT"),lr.alg||(lr.alg=tr);const dr={iat:Math.floor(Date.now()/1e3),exp:void 0};if(rr)if(typeof rr=="number")dr.exp=(r.nbf||dr.iat)+Math.floor(rr);else throw new Error("invalid_argument: JWT expiresIn is not a number");const hr={...dr,...r,iss:e};return createJWS(hr,M,lr,{canonicalize:ir})}catch(dr){return Promise.reject(dr)}},createJWS=function(r,e,M={},tr={}){try{M.alg||(M.alg=defaultAlg);const rr=typeof r=="string"?r:encodeSection(r,tr.canonicalize),ir=[encodeSection(M,tr.canonicalize),rr].join("."),lr=SignerAlg(M.alg);return Promise.resolve(lr(ir,e)).then(function(dr){return[ir,dr].join(".")})}catch(rr){return Promise.reject(rr)}},SELF_ISSUED_V2="https://self-issued.me/v2",SELF_ISSUED_V2_VC_INTEROP="https://self-issued.me/v2/openid-vc",SELF_ISSUED_V0_1="https://self-issued.me",defaultAlg="ES256K",DID_JSON$1="application/did+json";function encodeSection(r,e=!1){return encodeBase64url(e?canonicalizeData(r):JSON.stringify(r))}const NBF_SKEW=300;function decodeJWS(r){const e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(decodeBase64url(e[1])),payload:e[2],signature:e[3],data:`${e[1]}.${e[2]}`};throw new Error("invalid_argument: Incorrect format JWS")}function decodeJWT(r,e=!0){if(!r)throw new Error("invalid_argument: no JWT passed into decodeJWT");try{const M=decodeJWS(r),tr=Object.assign(M,{payload:JSON.parse(decodeBase64url(M.payload))}),rr=tr.payload.iss;if(tr.header.cty==="JWT"&&e){const ir=decodeJWT(tr.payload.jwt);if(ir.payload.iss!==rr)throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`);return ir}return tr}catch(M){throw new Error(`invalid_argument: ${JWT_ERROR.INVALID_JWT}: ${M}`)}}function verifyJWTDecoded({header:r,payload:e,data:M,signature:tr},rr){Array.isArray(rr)||(rr=[rr]);const ir=e.iss;let lr=!0;do{if(ir!==e.iss)throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`);try{return VerifierAlgorithm(r.alg)(M,tr,rr)}catch(dr){if(!dr.message.startsWith(JWT_ERROR.INVALID_SIGNATURE))throw dr}r.cty!=="JWT"?lr=!1:{payload:e,header:r,signature:tr,data:M}=decodeJWT(e.jwt,!1)}while(lr);throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: no matching public key found`)}typeof Symbol<"u"&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")));function allocUnsafe(r=0){return new Uint8Array(r)}function asUint8Array(r){return r}function concat(r,e){e==null&&(e=r.reduce((rr,ir)=>rr+ir.length,0));const M=allocUnsafe(e);let tr=0;for(const rr of r)M.set(rr,tr),tr+=rr.length;return M}function coerce(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function fromString$1(r){return new TextEncoder().encode(r)}function toString$1(r){return new TextDecoder().decode(r)}function base(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var M=new Uint8Array(256),tr=0;tr<M.length;tr++)M[tr]=255;for(var rr=0;rr<r.length;rr++){var ir=r.charAt(rr),lr=ir.charCodeAt(0);if(M[lr]!==255)throw new TypeError(ir+" is ambiguous");M[lr]=rr}var dr=r.length,hr=r.charAt(0),fr=Math.log(dr)/Math.log(256),mr=Math.log(256)/Math.log(dr);function _r(yr){if(yr instanceof Uint8Array||(ArrayBuffer.isView(yr)?yr=new Uint8Array(yr.buffer,yr.byteOffset,yr.byteLength):Array.isArray(yr)&&(yr=Uint8Array.from(yr))),!(yr instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(yr.length===0)return"";for(var br=0,Mr=0,vr=0,Sr=yr.length;vr!==Sr&&yr[vr]===0;)vr++,br++;for(var xr=(Sr-vr)*mr+1>>>0,Ar=new Uint8Array(xr);vr!==Sr;){for(var Dr=yr[vr],Ir=0,kr=xr-1;(Dr!==0||Ir<Mr)&&kr!==-1;kr--,Ir++)Dr+=256*Ar[kr]>>>0,Ar[kr]=Dr%dr>>>0,Dr=Dr/dr>>>0;if(Dr!==0)throw new Error("Non-zero carry");Mr=Ir,vr++}for(var Or=xr-Mr;Or!==xr&&Ar[Or]===0;)Or++;for(var Fr=hr.repeat(br);Or<xr;++Or)Fr+=r.charAt(Ar[Or]);return Fr}function gr(yr){if(typeof yr!="string")throw new TypeError("Expected String");if(yr.length===0)return new Uint8Array;var br=0;if(yr[br]!==" "){for(var Mr=0,vr=0;yr[br]===hr;)Mr++,br++;for(var Sr=(yr.length-br)*fr+1>>>0,xr=new Uint8Array(Sr);yr[br];){var Ar=M[yr.charCodeAt(br)];if(Ar===255)return;for(var Dr=0,Ir=Sr-1;(Ar!==0||Dr<vr)&&Ir!==-1;Ir--,Dr++)Ar+=dr*xr[Ir]>>>0,xr[Ir]=Ar%256>>>0,Ar=Ar/256>>>0;if(Ar!==0)throw new Error("Non-zero carry");vr=Dr,br++}if(yr[br]!==" "){for(var kr=Sr-vr;kr!==Sr&&xr[kr]===0;)kr++;for(var Or=new Uint8Array(Mr+(Sr-kr)),Fr=Mr;kr!==Sr;)Or[Fr++]=xr[kr++];return Or}}}function wr(yr){var br=gr(yr);if(br)return br;throw new Error(`Non-${e} character`)}return{encode:_r,decodeUnsafe:gr,decode:wr}}var src$1=base,_brrp__multiformats_scope_baseX=src$1;class Encoder{name;prefix;baseEncode;constructor(e,M,tr){this.name=e,this.prefix=M,this.baseEncode=tr}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Decoder{name;prefix;baseDecode;prefixCodePoint;constructor(e,M,tr){this.name=e,this.prefix=M;const rr=M.codePointAt(0);if(rr===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=rr,this.baseDecode=tr}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return or(this,e)}}class ComposedDecoder{decoders;constructor(e){this.decoders=e}or(e){return or(this,e)}decode(e){const M=e[0],tr=this.decoders[M];if(tr!=null)return tr.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function or(r,e){return new ComposedDecoder({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}class Codec{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,M,tr,rr){this.name=e,this.prefix=M,this.baseEncode=tr,this.baseDecode=rr,this.encoder=new Encoder(e,M,tr),this.decoder=new Decoder(e,M,rr)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function from({name:r,prefix:e,encode:M,decode:tr}){return new Codec(r,e,M,tr)}function baseX({name:r,prefix:e,alphabet:M}){const{encode:tr,decode:rr}=_brrp__multiformats_scope_baseX(M,r);return from({prefix:e,name:r,encode:tr,decode:ir=>coerce(rr(ir))})}function decode$2(r,e,M,tr){let rr=r.length;for(;r[rr-1]==="=";)--rr;const ir=new Uint8Array(rr*M/8|0);let lr=0,dr=0,hr=0;for(let fr=0;fr<rr;++fr){const mr=e[r[fr]];if(mr===void 0)throw new SyntaxError(`Non-${tr} character`);dr=dr<<M|mr,lr+=M,lr>=8&&(lr-=8,ir[hr++]=255&dr>>lr)}if(lr>=M||(255&dr<<8-lr)!==0)throw new SyntaxError("Unexpected end of data");return ir}function encode$1(r,e,M){const tr=e[e.length-1]==="=",rr=(1<<M)-1;let ir="",lr=0,dr=0;for(let hr=0;hr<r.length;++hr)for(dr=dr<<8|r[hr],lr+=8;lr>M;)lr-=M,ir+=e[rr&dr>>lr];if(lr!==0&&(ir+=e[rr&dr<<M-lr]),tr)for(;(ir.length*M&7)!==0;)ir+="=";return ir}function createAlphabetIdx(r){const e={};for(let M=0;M<r.length;++M)e[r[M]]=M;return e}function rfc4648({name:r,prefix:e,bitsPerChar:M,alphabet:tr}){const rr=createAlphabetIdx(tr);return from({prefix:e,name:r,encode(ir){return encode$1(ir,tr,M)},decode(ir){return decode$2(ir,rr,M,r)}})}const base10=baseX({prefix:"9",name:"base10",alphabet:"0123456789"}),base10$1=Object.freeze(Object.defineProperty({__proto__:null,base10},Symbol.toStringTag,{value:"Module"})),base16=rfc4648({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper=rfc4648({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),base16$1=Object.freeze(Object.defineProperty({__proto__:null,base16,base16upper},Symbol.toStringTag,{value:"Module"})),base2=rfc4648({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),base2$1=Object.freeze(Object.defineProperty({__proto__:null,base2},Symbol.toStringTag,{value:"Module"})),alphabet=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),alphabetBytesToChars=alphabet.reduce((r,e,M)=>(r[M]=e,r),[]),alphabetCharsToBytes=alphabet.reduce((r,e,M)=>{const tr=e.codePointAt(0);if(tr==null)throw new Error(`Invalid character: ${e}`);return r[tr]=M,r},[]);function encode(r){return r.reduce((e,M)=>(e+=alphabetBytesToChars[M],e),"")}function decode$1(r){const e=[];for(const M of r){const tr=M.codePointAt(0);if(tr==null)throw new Error(`Invalid character: ${M}`);const rr=alphabetCharsToBytes[tr];if(rr==null)throw new Error(`Non-base256emoji character: ${M}`);e.push(rr)}return new Uint8Array(e)}const base256emoji=from({prefix:"🚀",name:"base256emoji",encode,decode:decode$1}),base256emoji$1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji},Symbol.toStringTag,{value:"Module"})),base32=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper=rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad=rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper=rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex=rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper=rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad=rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper=rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z=rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),base32$1=Object.freeze(Object.defineProperty({__proto__:null,base32,base32hex,base32hexpad,base32hexpadupper,base32hexupper,base32pad,base32padupper,base32upper,base32z},Symbol.toStringTag,{value:"Module"})),base36=baseX({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper=baseX({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),base36$1=Object.freeze(Object.defineProperty({__proto__:null,base36,base36upper},Symbol.toStringTag,{value:"Module"})),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr=baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),base58=Object.freeze(Object.defineProperty({__proto__:null,base58btc,base58flickr},Symbol.toStringTag,{value:"Module"})),base64=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad=rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad=rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),base64$1=Object.freeze(Object.defineProperty({__proto__:null,base64,base64pad,base64url,base64urlpad},Symbol.toStringTag,{value:"Module"})),base8=rfc4648({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),base8$1=Object.freeze(Object.defineProperty({__proto__:null,base8},Symbol.toStringTag,{value:"Module"})),identity=from({prefix:"\0",name:"identity",encode:r=>toString$1(r),decode:r=>fromString$1(r)}),identityBase=Object.freeze(Object.defineProperty({__proto__:null,identity},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const bases={...identityBase,...base2$1,...base8$1,...base10$1,...base16$1,...base32$1,...base36$1,...base58,...base64$1,...base256emoji$1};function createCodec(r,e,M,tr){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:M},decoder:{decode:tr}}}const string=createCodec("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ascii=createCodec("ascii","a",r=>{let e="a";for(let M=0;M<r.length;M++)e+=String.fromCharCode(r[M]);return e},r=>{r=r.substring(1);const e=allocUnsafe(r.length);for(let M=0;M<r.length;M++)e[M]=r.charCodeAt(M);return e}),BASES={utf8:string,"utf-8":string,hex:bases.base16,latin1:ascii,ascii,binary:ascii,...bases};function fromString(r,e="utf8"){const M=BASES[e];if(M==null)throw new Error(`Unsupported encoding "${e}"`);return M.decoder.decode(`${M.prefix}${r}`)}function toString(r,e="utf8"){const M=BASES[e];if(M==null)throw new Error(`Unsupported encoding "${e}"`);return M.encoder.encode(r).substring(1)}const __viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze(Object.defineProperty({__proto__:null,default:__viteBrowserExternal},Symbol.toStringTag,{value:"Module"})),require$$9=getAugmentedNamespace(__viteBrowserExternal$1);var encode_1,hasRequiredEncode;function requireEncode(){if(hasRequiredEncode)return encode_1;hasRequiredEncode=1,encode_1=tr;var r=128,e=-128,M=Math.pow(2,31);function tr(rr,ir,lr){if(Number.MAX_SAFE_INTEGER&&rr>Number.MAX_SAFE_INTEGER)throw tr.bytes=0,new RangeError("Could not encode varint");ir=ir||[],lr=lr||0;for(var dr=lr;rr>=M;)ir[lr++]=rr&255|r,rr/=128;for(;rr&e;)ir[lr++]=rr&255|r,rr>>>=7;return ir[lr]=rr|0,tr.bytes=lr-dr+1,ir}return encode_1}var decode,hasRequiredDecode;function requireDecode(){if(hasRequiredDecode)return decode;hasRequiredDecode=1,decode=M;var r=128,e=127;function M(tr,lr){var ir=0,lr=lr||0,dr=0,hr=lr,fr,mr=tr.length;do{if(hr>=mr||dr>49)throw M.bytes=0,new RangeError("Could not decode varint");fr=tr[hr++],ir+=dr<28?(fr&e)<<dr:(fr&e)*Math.pow(2,dr),dr+=7}while(fr>=r);return M.bytes=hr-lr,ir}return decode}var length,hasRequiredLength;function requireLength(){if(hasRequiredLength)return length;hasRequiredLength=1;var r=Math.pow(2,7),e=Math.pow(2,14),M=Math.pow(2,21),tr=Math.pow(2,28),rr=Math.pow(2,35),ir=Math.pow(2,42),lr=Math.pow(2,49),dr=Math.pow(2,56),hr=Math.pow(2,63);return length=function(fr){return fr<r?1:fr<e?2:fr<M?3:fr<tr?4:fr<rr?5:fr<ir?6:fr<lr?7:fr<dr?8:fr<hr?9:10},length}var varint$1,hasRequiredVarint;function requireVarint(){return hasRequiredVarint||(hasRequiredVarint=1,varint$1={encode:requireEncode(),decode:requireDecode(),encodingLength:requireLength()}),varint$1}var varintExports=requireVarint();const varint=getDefaultExportFromCjs(varintExports);function keyToDidDoc$4(r,e){const M=`did:key:${e}`,tr=`${M}#${e}`;return{id:M,verificationMethod:[{id:tr,type:"Secp256k1VerificationKey2018",controller:M,publicKeyBase58:toString(r,"base58btc")}],authentication:[tr],assertionMethod:[tr],capabilityDelegation:[tr],capabilityInvocation:[tr]}}const secp256k1=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:keyToDidDoc$4},Symbol.toStringTag,{value:"Module"}));function encodeKey(r){const e=new Uint8Array(r.length+2);return e[0]=236,e[1]=1,e.set(r,2),`z${toString(e,"base58btc")}`}function keyToDidDoc$3(r,e){const M=`did:key:${e}`,tr=`${M}#${e}`,rr=edwardsToMontgomeryPub(r),ir=`${M}#${encodeKey(rr)}`;return{id:M,verificationMethod:[{id:tr,type:"Ed25519VerificationKey2018",controller:M,publicKeyBase58:toString(r,"base58btc")}],authentication:[tr],assertionMethod:[tr],capabilityDelegation:[tr],capabilityInvocation:[tr],keyAgreement:[{id:ir,type:"X25519KeyAgreementKey2019",controller:M,publicKeyBase58:toString(rr,"base58btc")}]}}const ed25519=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:keyToDidDoc$3},Symbol.toStringTag,{value:"Module"})),numberToVarBytesBE=numberToVarBytesBE$1;function keyToDidDoc$2(r,e){const M=`did:key:${e}`,tr=`${M}#${e}`,rr=p256.ProjectivePoint.fromHex(normalizePubKeyBytes$1(r));return{id:M,verificationMethod:[{id:tr,type:"JsonWebKey2020",controller:M,publicKeyJwk:{kty:"EC",crv:"P-256",x:toString(numberToVarBytesBE(rr.x),"base64url"),y:toString(numberToVarBytesBE(rr.y),"base64url")}}],authentication:[tr],assertionMethod:[tr],capabilityDelegation:[tr],capabilityInvocation:[tr]}}function normalizePubKeyBytes$1(r){return r.length===64?concat([new Uint8Array([4]),r]):r}const secp256r1=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:keyToDidDoc$2},Symbol.toStringTag,{value:"Module"}));const p384=p384$1;function keyToDidDoc$1(r,e){const M=`did:key:${e}`,tr=`${M}#${e}`,rr=p384.ProjectivePoint.fromHex(normalizePubKeyBytes(r));return{id:M,verificationMethod:[{id:tr,type:"JsonWebKey2020",controller:M,publicKeyJwk:{kty:"EC",crv:"P-384",x:toString(numberToVarBytesBE(rr.x),"base64url"),y:toString(numberToVarBytesBE(rr.y),"base64url")}}],authentication:[tr],assertionMethod:[tr],capabilityDelegation:[tr],capabilityInvocation:[tr]}}function normalizePubKeyBytes(r){return r.length===96?concat([new Uint8Array([4]),r]):r}const secp384r1=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:keyToDidDoc$1},Symbol.toStringTag,{value:"Module"}));const p521=p521$1;function keyToDidDoc(r,e){const M=`did:key:${e}`,tr=`${M}#${e}`,rr=p521.ProjectivePoint.fromHex(r);return{id:M,verificationMethod:[{id:tr,type:"JsonWebKey2020",controller:M,publicKeyJwk:{kty:"EC",crv:"P-521",x:toString(numberToVarBytesBE(rr.x),"base64url"),y:toString(numberToVarBytesBE(rr.y),"base64url")}}],authentication:[tr],assertionMethod:[tr],capabilityDelegation:[tr],capabilityInvocation:[tr]}}const secp521r1=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc},Symbol.toStringTag,{value:"Module"})),DID_LD_JSON="application/did+ld+json",DID_JSON="application/did+json",prefixToDriverMap={231:secp256k1,237:ed25519,4608:secp256r1,4609:secp384r1,4610:secp521r1};function getResolver$1(){return{key:async(r,e,M,tr)=>{const rr=tr.accept||DID_JSON,ir={didResolutionMetadata:{contentType:rr},didDocument:null,didDocumentMetadata:{}};try{const lr=base58btc.decode(e.id),dr=varint.decode(lr),hr=lr.slice(varint.decode.bytes),fr=await prefixToDriverMap[dr].keyToDidDoc(hr,e.id);rr===DID_LD_JSON?(fr["@context"]="https://w3id.org/did/v1",ir.didDocument=fr):rr===DID_JSON?ir.didDocument=fr:(delete ir.didResolutionMetadata.contentType,ir.didResolutionMetadata.error="representationNotSupported")}catch(lr){ir.didResolutionMetadata.error="invalidDid",ir.didResolutionMetadata.message=lr.toString()}return ir}}}const JWT_ALG="ES256K",JWT_FORMAT=/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/,DEFAULT_CONTEXT="https://www.w3.org/2018/credentials/v1",DEFAULT_VC_TYPE="VerifiableCredential",DEFAULT_JWT_PROOF_TYPE="JwtProof2020",additionalPropNames=["evidence","termsOfUse","refreshService","credentialSchema","credentialStatus"];function asArray(r){return Array.isArray(r)?r:[r]}function deepCopy(r){return Array.isArray(r)?r.map(e=>deepCopy(e)):r instanceof Date?new Date(r.getTime()):r&&typeof r=="object"?Object.getOwnPropertyNames(r).reduce((e,M)=>(Object.defineProperty(e,M,Object.getOwnPropertyDescriptor(r,M)),e[M]=deepCopy(r[M]),e),Object.create(Object.getPrototypeOf(r))):r}function notEmpty(r){return r!=null}function cleanUndefined(r){if(typeof r!="object"||r===null)return r;const e={...r};return Object.keys(e).forEach(M=>e[M]===void 0&&delete e[M]),e}function isLegacyAttestationFormat(r){return typeof r=="object"&&r.sub&&r.iss&&r.claim&&r.iat}function attestationToVcFormat(r){const{iat:e,nbf:M,claim:tr,vc:rr,...ir}=r,lr={...ir,nbf:M||e,vc:{"@context":[DEFAULT_CONTEXT],type:[DEFAULT_VC_TYPE],credentialSubject:tr}};return rr&&(r.issVc=rr),lr}function normalizeJwtCredentialPayload(r,e=!0){let M=deepCopy(r);isLegacyAttestationFormat(r)&&(M=attestationToVcFormat(r)),M.credentialSubject={...r.credentialSubject,...r.vc?.credentialSubject},r.sub&&!r.credentialSubject?.id&&M.credentialSubject&&(M.credentialSubject.id=r.sub,e&&delete M.sub),e&&delete M.vc?.credentialSubject,(typeof r.issuer>"u"||typeof r.issuer=="object")&&(M.issuer=cleanUndefined({id:r.iss,...r.issuer}),e&&!r.issuer?.id&&delete M.iss),!r.id&&r.jti&&(M.id=M.id||M.jti,e&&delete M.jti);const tr=[...asArray(M.type),...asArray(M.vc?.type)].filter(notEmpty);M.type=[...new Set(tr)],e&&delete M.vc?.type;for(const ir of additionalPropNames)r.vc&&r.vc[ir]&&(M[ir]||(M[ir]=r.vc[ir]),e&&delete M.vc[ir]);const rr=[...asArray(r.context),...asArray(r["@context"]),...asArray(r.vc?.["@context"])].filter(notEmpty);return M["@context"]=[...new Set(rr)],e&&(delete M.context,delete M.vc?.["@context"]),!r.issuanceDate&&(r.iat||r.nbf)&&(M.issuanceDate=new Date((r.nbf||r.iat)*1e3).toISOString(),e&&(r.nbf?delete M.nbf:delete M.iat)),!r.expirationDate&&r.exp&&(M.expirationDate=new Date(r.exp*1e3).toISOString(),e&&delete M.exp),e&&M.vc&&Object.keys(M.vc).length===0&&delete M.vc,M}function normalizeJwtCredential(r,e=!0){let M;try{M=decodeJWT(r)}catch{throw new TypeError("unknown credential format")}return{...normalizeJwtCredentialPayload(M.payload,e),proof:{type:DEFAULT_JWT_PROOF_TYPE,jwt:r}}}function normalizeCredential(r,e=!0){if(typeof r=="string"){if(JWT_FORMAT.test(r))return normalizeJwtCredential(r,e);{let M;try{M=JSON.parse(r)}catch{throw new TypeError("unknown credential format")}return normalizeCredential(M,e)}}else return r.proof?.jwt?deepCopy({...normalizeJwtCredential(r.proof.jwt,e),proof:r.proof}):{proof:{},...normalizeJwtCredentialPayload(r,e)}}function transformCredentialInput(r,e=!0){if(Array.isArray(r.credentialSubject))throw Error("credentialSubject of type array not supported");const M=deepCopy({vc:{...r.vc},...r});M.vc=M.vc;const tr={...r.credentialSubject,...r.vc?.credentialSubject};r.sub||(M.sub=r.credentialSubject?.id,e&&delete tr.id);const rr=[...asArray(r.context),...asArray(r["@context"]),...asArray(r.vc?.["@context"])].filter(notEmpty);M.vc["@context"]=[...new Set(rr)],e&&(delete M.context,delete M["@context"]);const ir=[...asArray(r.type),...asArray(r.vc?.type)].filter(notEmpty);if(M.vc.type=[...new Set(ir)],e&&delete M.type,r.id&&Object.getOwnPropertyNames(r).indexOf("jti")===-1&&(M.jti=r.id,e&&delete M.id),r.issuanceDate&&Object.getOwnPropertyNames(r).indexOf("nbf")===-1){const lr=Date.parse(r.issuanceDate);isNaN(lr)||(M.nbf=Math.floor(lr/1e3),e&&delete M.issuanceDate)}if(r.expirationDate&&Object.getOwnPropertyNames(r).indexOf("exp")===-1){const lr=Date.parse(r.expirationDate);isNaN(lr)||(M.exp=Math.floor(lr/1e3),e&&delete M.expirationDate)}r.issuer&&Object.getOwnPropertyNames(r).indexOf("iss")===-1&&(typeof r.issuer=="object"?(M.iss=r.issuer?.id,e&&(delete M.issuer.id,Object.keys(M.issuer).length===0&&delete M.issuer)):typeof r.issuer=="string"&&(M.iss=r.iss||""+r.issuer,e&&delete M.issuer)),M.vc.credentialSubject=tr,e&&delete M.credentialSubject;for(const lr of additionalPropNames)r[lr]&&(M.vc[lr]||(M.vc[lr]=r[lr]),e&&delete M[lr]);return M}const VC_ERROR={SCHEMA_ERROR:"schema_error"};function isDateObject(r){return r&&!isNaN(r)&&Object.prototype.toString.call(r)==="[object Date]"}function validateTimestamp(r){if(typeof r=="number"){if(!(Number.isInteger(r)&&r<1e11))throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: "${r}" is not a unix timestamp in seconds`)}else if(typeof r=="string")validateTimestamp(Math.floor(new Date(r).valueOf()/1e3));else if(!isDateObject(r))throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: "${r}" is not a valid time`)}function validateContext(r){const e=asArray(r);if(e.length<1||e.indexOf(DEFAULT_CONTEXT)===-1)throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: @context is missing default context "${DEFAULT_CONTEXT}"`)}function validateVcType(r){const e=asArray(r);if(e.length<1||e.indexOf(DEFAULT_VC_TYPE)===-1)throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: type is missing default "${DEFAULT_VC_TYPE}"`)}function validateCredentialSubject(r){if(Object.keys(r).length===0)throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: credentialSubject must not be empty`)}const verifyCredential=function(r,e,M={}){try{const tr=M?.policies?.issuanceDate===!1?!1:void 0,rr=M?.policies?.expirationDate===!1?!1:void 0;return M={...M,policies:{...M?.policies,nbf:tr,exp:rr,iat:tr}},Promise.resolve(verifyJWT(r,{resolver:e,...M})).then(function(ir){return ir.verifiableCredential=normalizeCredential(ir.jwt,M?.removeOriginalFields),M?.policies?.format!==!1&&validateCredentialPayload(ir.verifiableCredential),ir})}catch(tr){return Promise.reject(tr)}},createVerifiableCredentialJwt=function(r,e,M={}){try{const tr={iat:void 0,...transformCredentialInput(r,M.removeOriginalFields)};if(validateJwtCredentialPayload(tr),Array.isArray(e)){const rr=e[0].did,ir=[];for(const lr of e){if(lr.did!==rr)throw new Error("All issuers must be the same did to comply with the Verifiable Conditions spec");ir.push({issuer:lr.did||tr.iss||"",signer:lr.signer,alg:lr.alg||M.header?.alg||JWT_ALG})}return Promise.resolve(createMultisignatureJWT(tr,{...M},ir))}else return Promise.resolve(createJWT(tr,{...M,issuer:e.did||tr.iss||"",signer:e.signer},{...M.header,alg:e.alg||M.header?.alg||JWT_ALG}))}catch(tr){return Promise.reject(tr)}};function validateJwtCredentialPayload(r){validateContext(r.vc["@context"]),validateVcType(r.vc.type),validateCredentialSubject(r.vc.credentialSubject),r.nbf&&validateTimestamp(r.nbf),r.exp&&validateTimestamp(r.exp)}function validateCredentialPayload(r){validateContext(r["@context"]),validateVcType(r.type),validateCredentialSubject(r.credentialSubject),r.issuanceDate&&validateTimestamp(r.issuanceDate),r.expirationDate&&validateTimestamp(r.expirationDate)}function parsePkhDid(r){const e=r.split(":");if(!r.startsWith("did:pkh:")||e.length!==5)throw new Error("Invalid pkh did");const[,,M,tr,rr]=e;if(!rr.startsWith("0x"))throw new Error(`Invalid address: ${rr}`);const ir=Number(tr);if(isNaN(ir))throw new Error(`Invalid chain id: ${tr}`);return{chainId:ir,networkId:M,address:rr}}async function verifyAuthBearerToken(r){try{const e=parseInt(String(Date.now()/1e3)),M=await verifyCredential(r,getResolver(),{policies:{now:parseInt(String(Date.now()/1e3)),expirationDate:!0,issuanceDate:!0}});return M.payload.exp&&M.payload.exp<e?!1:(assertIsAuthCredential(M),M)}catch(e){return console.error(e),!1}}function assertIsAuthCredential(r){const e=Object.keys(r.verifiableCredential.credentialSubject);if(!["address","chainId","networkId"].every(M=>e.includes(M)))throw new Error("Invalid Auth Credential Subject:"+JSON.stringify(r.verifiableCredential.credentialSubject,null,2))}async function createAuthBearerToken(r,e,M,tr,rr){const ir={sub:tr.did,vc:{"@context":["https://www.w3.org/2018/credentials/v1"],type:["VerifiableCredential"],credentialSubject:{chainId:r,networkId:e,address:M}},aud:rr?.aud};return await createVerifiableCredentialJwt(ir,tr,{expiresIn:rr?.expiresIn})}const getResolver=()=>{const r=getResolver$1();if(!r)throw new Error("Failed to get key resolver");return new Resolver(r)};var compare_1,hasRequiredCompare;function requireCompare(){if(hasRequiredCompare)return compare_1;hasRequiredCompare=1;function r(e,M){for(let tr=0;tr<e.byteLength;tr++){if(e[tr]<M[tr])return-1;if(e[tr]>M[tr])return 1}return e.byteLength>M.byteLength?1:e.byteLength<M.byteLength?-1:0}return compare_1=r,compare_1}var concat_1,hasRequiredConcat;function requireConcat(){if(hasRequiredConcat)return concat_1;hasRequiredConcat=1;function r(e,M){M||(M=e.reduce((ir,lr)=>ir+lr.length,0));const tr=new Uint8Array(M);let rr=0;for(const ir of e)tr.set(ir,rr),rr+=ir.length;return tr}return concat_1=r,concat_1}var equals_1,hasRequiredEquals;function requireEquals(){if(hasRequiredEquals)return equals_1;hasRequiredEquals=1;function r(e,M){if(e===M)return!0;if(e.byteLength!==M.byteLength)return!1;for(let tr=0;tr<e.byteLength;tr++)if(e[tr]!==M[tr])return!1;return!0}return equals_1=r,equals_1}const require$$0=getAugmentedNamespace(basics);var bases_1,hasRequiredBases;function requireBases(){if(hasRequiredBases)return bases_1;hasRequiredBases=1;const{bases:r}=require$$0;function e(ir,lr,dr,hr){return{name:ir,prefix:lr,encoder:{name:ir,prefix:lr,encode:dr},decoder:{decode:hr}}}const M=e("utf8","u",ir=>"u"+new TextDecoder("utf8").decode(ir),ir=>new TextEncoder().encode(ir.substring(1))),tr=e("ascii","a",ir=>{let lr="a";for(let dr=0;dr<ir.length;dr++)lr+=String.fromCharCode(ir[dr]);return lr},ir=>{ir=ir.substring(1);const lr=new Uint8Array(ir.length);for(let dr=0;dr<ir.length;dr++)lr[dr]=ir.charCodeAt(dr);return lr});return bases_1={utf8:M,"utf-8":M,hex:r.base16,latin1:tr,ascii:tr,binary:tr,...r},bases_1}var fromString_1,hasRequiredFromString;function requireFromString(){if(hasRequiredFromString)return fromString_1;hasRequiredFromString=1;const r=requireBases();function e(M,tr="utf8"){const rr=r[tr];if(!rr)throw new Error(`Unsupported encoding "${tr}"`);return rr.decoder.decode(`${rr.prefix}${M}`)}return fromString_1=e,fromString_1}var toString_1,hasRequiredToString;function requireToString(){if(hasRequiredToString)return toString_1;hasRequiredToString=1;const r=requireBases();function e(M,tr="utf8"){const rr=r[tr];if(!rr)throw new Error(`Unsupported encoding "${tr}"`);return rr.encoder.encode(M).substring(1)}return toString_1=e,toString_1}var xor_1,hasRequiredXor;function requireXor(){if(hasRequiredXor)return xor_1;hasRequiredXor=1;function r(e,M){if(e.length!==M.length)throw new Error("Inputs should have the same length");const tr=new Uint8Array(e.length);for(let rr=0;rr<e.length;rr++)tr[rr]=e[rr]^M[rr];return tr}return xor_1=r,xor_1}var uint8arrays,hasRequiredUint8arrays;function requireUint8arrays(){if(hasRequiredUint8arrays)return uint8arrays;hasRequiredUint8arrays=1;const r=requireCompare(),e=requireConcat(),M=requireEquals(),tr=requireFromString(),rr=requireToString(),ir=requireXor();return uint8arrays={compare:r,concat:e,equals:M,fromString:tr,toString:rr,xor:ir},uint8arrays}var uint8arraysExports=requireUint8arrays();const require$$1$1=getAugmentedNamespace(concat$2),require$$1=getAugmentedNamespace(toString$3),require$$2=getAugmentedNamespace(fromString$3);var util,hasRequiredUtil;function requireUtil(){if(hasRequiredUtil)return util;hasRequiredUtil=1;const r=requireVarint(),{toString:e}=require$$1,{fromString:M}=require$$2;util={numberToUint8Array:rr,uint8ArrayToNumber:tr,varintUint8ArrayEncode:ir,varintEncode:lr};function tr(dr){return parseInt(e(dr,"base16"),16)}function rr(dr){let hr=dr.toString(16);return hr.length%2===1&&(hr="0"+hr),M(hr,"base16")}function ir(dr){return Uint8Array.from(r.encode(tr(dr)))}function lr(dr){return Uint8Array.from(r.encode(dr))}return util}var generatedTable,hasRequiredGeneratedTable;function requireGeneratedTable(){return hasRequiredGeneratedTable||(hasRequiredGeneratedTable=1,generatedTable={baseTable:Object.freeze({identity:0,cidv1:1,cidv2:2,cidv3:3,ip4:4,tcp:6,sha1:17,"sha2-256":18,"sha2-512":19,"sha3-512":20,"sha3-384":21,"sha3-256":22,"sha3-224":23,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake3:30,dccp:33,"murmur3-128":34,"murmur3-32":35,ip6:41,ip6zone:42,path:47,multicodec:48,multihash:49,multiaddr:50,multibase:51,dns:53,dns4:54,dns6:55,dnsaddr:56,protobuf:80,cbor:81,raw:85,"dbl-sha2-256":86,rlp:96,bencode:99,"dag-pb":112,"dag-cbor":113,"libp2p-key":114,"git-raw":120,"torrent-info":123,"torrent-file":124,"leofcoin-block":129,"leofcoin-tx":130,"leofcoin-pr":131,sctp:132,"dag-jose":133,"dag-cose":134,"eth-block":144,"eth-block-list":145,"eth-tx-trie":146,"eth-tx":147,"eth-tx-receipt-trie":148,"eth-tx-receipt":149,"eth-state-trie":150,"eth-account-snapshot":151,"eth-storage-trie":152,"eth-receipt-log-trie":153,"eth-reciept-log":154,"bitcoin-block":176,"bitcoin-tx":177,"bitcoin-witness-commitment":178,"zcash-block":192,"zcash-tx":193,"caip-50":202,streamid:206,"stellar-block":208,"stellar-tx":209,md4:212,md5:213,bmt:214,"decred-block":224,"decred-tx":225,"ipld-ns":226,"ipfs-ns":227,"swarm-ns":228,"ipns-ns":229,zeronet:230,"secp256k1-pub":231,"bls12_381-g1-pub":234,"bls12_381-g2-pub":235,"x25519-pub":236,"ed25519-pub":237,"bls12_381-g1g2-pub":238,"dash-block":240,"dash-tx":241,"swarm-manifest":250,"swarm-feed":251,udp:273,"p2p-webrtc-star":275,"p2p-webrtc-direct":276,"p2p-stardust":277,"p2p-circuit":290,"dag-json":297,udt:301,utp:302,unix:400,thread:406,p2p:421,ipfs:421,https:443,onion:444,onion3:445,garlic64:446,garlic32:447,tls:448,noise:454,quic:460,ws:477,wss:478,"p2p-websocket-star":479,http:480,"swhid-1-snp":496,json:512,messagepack:513,"libp2p-peer-record":769,"libp2p-relay-rsvp":770,"car-index-sorted":1024,"sha2-256-trunc254-padded":4114,"ripemd-128":4178,"ripemd-160":4179,"ripemd-256":4180,"ripemd-320":4181,x11:4352,"p256-pub":4608,"p384-pub":4609,"p521-pub":4610,"ed448-pub":4611,"x448-pub":4612,"ed25519-priv":4864,"secp256k1-priv":4865,"x25519-priv":4866,kangarootwelve:7425,"sm3-256":21325,"blake2b-8":45569,"blake2b-16":45570,"blake2b-24":45571,"blake2b-32":45572,"blake2b-40":45573,"blake2b-48":45574,"blake2b-56":45575,"blake2b-64":45576,"blake2b-72":45577,"blake2b-80":45578,"blake2b-88":45579,"blake2b-96":45580,"blake2b-104":45581,"blake2b-112":45582,"blake2b-120":45583,"blake2b-128":45584,"blake2b-136":45585,"blake2b-144":45586,"blake2b-152":45587,"blake2b-160":45588,"blake2b-168":45589,"blake2b-176":45590,"blake2b-184":45591,"blake2b-192":45592,"blake2b-200":45593,"blake2b-208":45594,"blake2b-216":45595,"blake2b-224":45596,"blake2b-232":45597,"blake2b-240":45598,"blake2b-248":45599,"blake2b-256":45600,"blake2b-264":45601,"blake2b-272":45602,"blake2b-280":45603,"blake2b-288":45604,"blake2b-296":45605,"blake2b-304":45606,"blake2b-312":45607,"blake2b-320":45608,"blake2b-328":45609,"blake2b-336":45610,"blake2b-344":45611,"blake2b-352":45612,"blake2b-360":45613,"blake2b-368":45614,"blake2b-376":45615,"blake2b-384":45616,"blake2b-392":45617,"blake2b-400":45618,"blake2b-408":45619,"blake2b-416":45620,"blake2b-424":45621,"blake2b-432":45622,"blake2b-440":45623,"blake2b-448":45624,"blake2b-456":45625,"blake2b-464":45626,"blake2b-472":45627,"blake2b-480":45628,"blake2b-488":45629,"blake2b-496":45630,"blake2b-504":45631,"blake2b-512":45632,"blake2s-8":45633,"blake2s-16":45634,"blake2s-24":45635,"blake2s-32":45636,"blake2s-40":45637,"blake2s-48":45638,"blake2s-56":45639,"blake2s-64":45640,"blake2s-72":45641,"blake2s-80":45642,"blake2s-88":45643,"blake2s-96":45644,"blake2s-104":45645,"blake2s-112":45646,"blake2s-120":45647,"blake2s-128":45648,"blake2s-136":45649,"blake2s-144":45650,"blake2s-152":45651,"blake2s-160":45652,"blake2s-168":45653,"blake2s-176":45654,"blake2s-184":45655,"blake2s-192":45656,"blake2s-200":45657,"blake2s-208":45658,"blake2s-216":45659,"blake2s-224":45660,"blake2s-232":45661,"blake2s-240":45662,"blake2s-248":45663,"blake2s-256":45664,"skein256-8":45825,"skein256-16":45826,"skein256-24":45827,"skein256-32":45828,"skein256-40":45829,"skein256-48":45830,"skein256-56":45831,"skein256-64":45832,"skein256-72":45833,"skein256-80":45834,"skein256-88":45835,"skein256-96":45836,"skein256-104":45837,"skein256-112":45838,"skein256-120":45839,"skein256-128":45840,"skein256-136":45841,"skein256-144":45842,"skein256-152":45843,"skein256-160":45844,"skein256-168":45845,"skein256-176":45846,"skein256-184":45847,"skein256-192":45848,"skein256-200":45849,"skein256-208":45850,"skein256-216":45851,"skein256-224":45852,"skein256-232":45853,"skein256-240":45854,"skein256-248":45855,"skein256-256":45856,"skein512-8":45857,"skein512-16":45858,"skein512-24":45859,"skein512-32":45860,"skein512-40":45861,"skein512-48":45862,"skein512-56":45863,"skein512-64":45864,"skein512-72":45865,"skein512-80":45866,"skein512-88":45867,"skein512-96":45868,"skein512-104":45869,"skein512-112":45870,"skein512-120":45871,"skein512-128":45872,"skein512-136":45873,"skein512-144":45874,"skein512-152":45875,"skein512-160":45876,"skein512-168":45877,"skein512-176":45878,"skein512-184":45879,"skein512-192":45880,"skein512-200":45881,"skein512-208":45882,"skein512-216":45883,"skein512-224":45884,"skein512-232":45885,"skein512-240":45886,"skein512-248":45887,"skein512-256":45888,"skein512-264":45889,"skein512-272":45890,"skein512-280":45891,"skein512-288":45892,"skein512-296":45893,"skein512-304":45894,"skein512-312":45895,"skein512-320":45896,"skein512-328":45897,"skein512-336":45898,"skein512-344":45899,"skein512-352":45900,"skein512-360":45901,"skein512-368":45902,"skein512-376":45903,"skein512-384":45904,"skein512-392":45905,"skein512-400":45906,"skein512-408":45907,"skein512-416":45908,"skein512-424":45909,"skein512-432":45910,"skein512-440":45911,"skein512-448":45912,"skein512-456":45913,"skein512-464":45914,"skein512-472":45915,"skein512-480":45916,"skein512-488":45917,"skein512-496":45918,"skein512-504":45919,"skein512-512":45920,"skein1024-8":45921,"skein1024-16":45922,"skein1024-24":45923,"skein1024-32":45924,"skein1024-40":45925,"skein1024-48":45926,"skein1024-56":45927,"skein1024-64":45928,"skein1024-72":45929,"skein1024-80":45930,"skein1024-88":45931,"skein1024-96":45932,"skein1024-104":45933,"skein1024-112":45934,"skein1024-120":45935,"skein1024-128":45936,"skein1024-136":45937,"skein1024-144":45938,"skein1024-152":45939,"skein1024-160":45940,"skein1024-168":45941,"skein1024-176":45942,"skein1024-184":45943,"skein1024-192":45944,"skein1024-200":45945,"skein1024-208":45946,"skein1024-216":45947,"skein1024-224":45948,"skein1024-232":45949,"skein1024-240":45950,"skein1024-248":45951,"skein1024-256":45952,"skein1024-264":45953,"skein1024-272":45954,"skein1024-280":45955,"skein1024-288":45956,"skein1024-296":45957,"skein1024-304":45958,"skein1024-312":45959,"skein1024-320":45960,"skein1024-328":45961,"skein1024-336":45962,"skein1024-344":45963,"skein1024-352":45964,"skein1024-360":45965,"skein1024-368":45966,"skein1024-376":45967,"skein1024-384":45968,"skein1024-392":45969,"skein1024-400":45970,"skein1024-408":45971,"skein1024-416":45972,"skein1024-424":45973,"skein1024-432":45974,"skein1024-440":45975,"skein1024-448":45976,"skein1024-456":45977,"skein1024-464":45978,"skein1024-472":45979,"skein1024-480":45980,"skein1024-488":45981,"skein1024-496":45982,"skein1024-504":45983,"skein1024-512":45984,"skein1024-520":45985,"skein1024-528":45986,"skein1024-536":45987,"skein1024-544":45988,"skein1024-552":45989,"skein1024-560":45990,"skein1024-568":45991,"skein1024-576":45992,"skein1024-584":45993,"skein1024-592":45994,"skein1024-600":45995,"skein1024-608":45996,"skein1024-616":45997,"skein1024-624":45998,"skein1024-632":45999,"skein1024-640":46e3,"skein1024-648":46001,"skein1024-656":46002,"skein1024-664":46003,"skein1024-672":46004,"skein1024-680":46005,"skein1024-688":46006,"skein1024-696":46007,"skein1024-704":46008,"skein1024-712":46009,"skein1024-720":46010,"skein1024-728":46011,"skein1024-736":46012,"skein1024-744":46013,"skein1024-752":46014,"skein1024-760":46015,"skein1024-768":46016,"skein1024-776":46017,"skein1024-784":46018,"skein1024-792":46019,"skein1024-800":46020,"skein1024-808":46021,"skein1024-816":46022,"skein1024-824":46023,"skein1024-832":46024,"skein1024-840":46025,"skein1024-848":46026,"skein1024-856":46027,"skein1024-864":46028,"skein1024-872":46029,"skein1024-880":46030,"skein1024-888":46031,"skein1024-896":46032,"skein1024-904":46033,"skein1024-912":46034,"skein1024-920":46035,"skein1024-928":46036,"skein1024-936":46037,"skein1024-944":46038,"skein1024-952":46039,"skein1024-960":46040,"skein1024-968":46041,"skein1024-976":46042,"skein1024-984":46043,"skein1024-992":46044,"skein1024-1000":46045,"skein1024-1008":46046,"skein1024-1016":46047,"skein1024-1024":46048,"poseidon-bls12_381-a2-fc1":46081,"poseidon-bls12_381-a2-fc1-sc":46082,"zeroxcert-imprint-256":52753,"fil-commitment-unsealed":61697,"fil-commitment-sealed":61698,"holochain-adr-v0":8417572,"holochain-adr-v1":8483108,"holochain-key-v0":9728292,"holochain-key-v1":9793828,"holochain-sig-v0":10645796,"holochain-sig-v1":10711332,"skynet-ns":11639056,"arweave-ns":11704592})}),generatedTable}var maps,hasRequiredMaps;function requireMaps(){if(hasRequiredMaps)return maps;hasRequiredMaps=1;const{baseTable:r}=requireGeneratedTable(),e=requireUtil().varintEncode,M={},tr={},rr={};for(const lr in r){const dr=lr,hr=r[dr];M[dr]=e(hr);const fr=dr.toUpperCase().replace(/-/g,"_");tr[fr]=hr,rr[hr]||(rr[hr]=dr)}Object.freeze(M),Object.freeze(tr),Object.freeze(rr);const ir=Object.freeze(r);return maps={nameToVarint:M,constantToCode:tr,nameToCode:ir,codeToName:rr},maps}var src,hasRequiredSrc;function requireSrc(){if(hasRequiredSrc)return src;hasRequiredSrc=1;const r=requireVarint(),{concat:e}=require$$1$1,M=requireUtil(),{nameToVarint:tr,constantToCode:rr,nameToCode:ir,codeToName:lr}=requireMaps();function dr(Dr,Ir){let kr;if(Dr instanceof Uint8Array)kr=M.varintUint8ArrayEncode(Dr);else if(tr[Dr])kr=tr[Dr];else throw new Error("multicodec not recognized");return e([kr,Ir],kr.length+Ir.length)}function hr(Dr){return r.decode(Dr),Dr.slice(r.decode.bytes)}function fr(Dr){const Ir=r.decode(Dr),kr=lr[Ir];if(kr===void 0)throw new Error(`Code "${Ir}" not found`);return kr}function mr(Dr){return lr[Dr]}function _r(Dr){const Ir=ir[Dr];if(Ir===void 0)throw new Error(`Codec "${Dr}" not found`);return Ir}function gr(Dr){return r.decode(Dr)}function wr(Dr){const Ir=tr[Dr];if(Ir===void 0)throw new Error(`Codec "${Dr}" not found`);return Ir}function yr(Dr){return M.varintEncode(Dr)}function br(Dr){return fr(Dr)}function Mr(Dr){return mr(Dr)}function vr(Dr){return _r(Dr)}function Sr(Dr){return gr(Dr)}function xr(Dr){return wr(Dr)}function Ar(Dr){return Array.from(yr(Dr))}return src={addPrefix:dr,rmPrefix:hr,getNameFromData:fr,getNameFromCode:mr,getCodeFromName:_r,getCodeFromData:gr,getVarintFromName:wr,getVarintFromCode:yr,getCodec:br,getName:Mr,getNumber:vr,getCode:Sr,getCodeVarint:xr,getVarint:Ar,...rr,nameToVarint:tr,nameToCode:ir,codeToName:lr},src}var srcExports=requireSrc();const multicodec=getDefaultExportFromCjs(srcExports);function ECPointCompress(r,e){const M=new Uint8Array(r.length+1);return M[0]=2+(e[e.length-1]&1),M.set(r,1),M}function compressedKeyInHexfromRaw(r){const e=r.slice(0,r.length/2),M=r.slice(r.length/2,r.length),tr=uint8arraysExports.fromString(e,"base16"),rr=uint8arraysExports.fromString(M,"base16"),ir=ECPointCompress(tr,rr);return uint8arraysExports.toString(ir,"base16")}function rawKeyInHexfromUncompressed(r){return r.slice(2)}function encodeDIDfromHexString(r,e){const M=uint8arraysExports.fromString(e,"base16");return encodeDIDfromBytes(r,M)}function encodeDIDfromBytes(r,e){const M=multicodec.addPrefix(r,e);return`did:key:${base58btc$1.encode(M)}`}const ECDSA_ALGORITHM={name:"ECDSA",namedCurve:"P-256"},ECDSA_SIGN_ALGORITHM={name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"};function ab2hex(r){return Array.prototype.map.call(new Uint8Array(r),e=>("00"+e.toString(16)).slice(-2)).join("")}async function parseDid(r,e){const M=await e.exportKey("raw",r.publicKey),tr="p256-pub",rr=rawKeyInHexfromUncompressed(ab2hex(M)),ir=compressedKeyInHexfromRaw(rr);return encodeDIDfromHexString(tr,ir)}async function exportKeyPair(r,e){return{publicKey:await e.exportKey("jwk",r.publicKey),privateKey:await e.exportKey("jwk",r.privateKey)}}async function importKeyPair(r,e,M=ECDSA_ALGORITHM){return{publicKey:await e.importKey("jwk",r.publicKey,M,!0,["verify"]),privateKey:await e.importKey("jwk",r.privateKey,M,!0,["sign"])}}async function generateKeyPair(r,e=ECDSA_ALGORITHM){return r.generateKey(e,!0,["sign","verify"])}const RENOWN_NETWORK_ID="eip155",RENOWN_CHAIN_ID=1;class RenownCrypto{#e;#t;#r;did;static algorithm=ECDSA_ALGORITHM;static signAlgorithm=ECDSA_SIGN_ALGORITHM;constructor(e,M,tr,rr){this.#r=e,this.#e=M,this.#t=tr,this.did=rr}get publicKey(){return this.#t.publicKey}async getBearerToken(e,M){return await createAuthBearerToken(Number(RENOWN_CHAIN_ID),RENOWN_NETWORK_ID,e||this.did,this.issuer,M)}async removeDid(){await this.#r.removeKeyPair()}#s(e){return fromString(e,"utf-8")}async sign(e){const M=typeof e=="string"?this.#s(e):e,tr=await this.#e.sign(RenownCrypto.signAlgorithm,this.#t.privateKey,M.buffer);return new Uint8Array(tr)}async verify(e,M){return this.#e.verify({name:"ECDSA",hash:"SHA-256"},this.#t.publicKey,M.buffer,e.buffer)}get issuer(){return{did:this.did,signer:async e=>{const M=await this.sign(typeof e=="string"?new TextEncoder().encode(e):e);return bytesToBase64url(M)},alg:"ES256"}}}class RenownCryptoBuilder{keyPairStorage;subtleCrypto;withKeyPairStorage(e){return this.keyPairStorage=e,this}withSubtleCrypto(e){return this.subtleCrypto=e,this}async build(){if(!this.keyPairStorage)throw new Error("KeyPairStorage is required. Use withKeyPairStorage() to set it.");const e=this.subtleCrypto??globalThis.crypto.subtle,M=await this.#e(e,this.keyPairStorage),tr=await parseDid(M,e);return new RenownCrypto(this.keyPairStorage,e,M,tr)}async#e(e,M){const tr=await M.loadKeyPair();if(tr)return importKeyPair(tr,e);const rr=await generateKeyPair(e),ir=await exportKeyPair(rr,e);return await M.saveKeyPair(ir),rr}}const DEFAULT_DB_NAME="renownKeyDB",STORE_NAME="keyPairs",KEY="keyPair";class BrowserKeyStorage{#e;constructor(e){this.#e=e}static async create(e=DEFAULT_DB_NAME){const M=await BrowserKeyStorage.#t(e);return new BrowserKeyStorage(M)}static#t(e){return new Promise((M,tr)=>{const rr=indexedDB.open(e);rr.onupgradeneeded=ir=>{const lr=ir.target.result;lr.objectStoreNames.contains(STORE_NAME)||lr.createObjectStore(STORE_NAME)},rr.onsuccess=()=>{const ir=rr.result;if(ir.objectStoreNames.contains(STORE_NAME))M(ir);else{const lr=ir.version;ir.close();const dr=indexedDB.open(e,lr+1);dr.onupgradeneeded=hr=>{const fr=hr.target.result;fr.objectStoreNames.contains(STORE_NAME)||fr.createObjectStore(STORE_NAME)},dr.onsuccess=()=>M(dr.result),dr.onerror=()=>tr(dr.error)}},rr.onerror=()=>tr(rr.error)})}#r(e="readwrite"){return this.#e.transaction(STORE_NAME,e).objectStore(STORE_NAME)}async saveKeyPair(e){const tr=this.#r().put(e,KEY);return new Promise((rr,ir)=>{tr.onsuccess=()=>rr(),tr.onerror=()=>ir(new Error("Failed to save key pair"))})}async loadKeyPair(){const M=this.#r("readonly").get(KEY);return new Promise((tr,rr)=>{M.onsuccess=()=>{const ir=M.result;tr(ir)},M.onerror=()=>rr(new Error("Failed to load key pair"))})}async removeKeyPair(){const M=this.#r().delete(KEY);return new Promise((tr,rr)=>{M.onsuccess=()=>tr(),M.onerror=()=>rr(new Error("Failed to remove key pair"))})}}class InvalidSignatureError extends Error{constructor(){super("Invalid signature")}}class RenownCryptoSigner{crypto;appName;user;app;constructor(e,M,tr){this.crypto=e,this.appName=M,this.user=tr,this.app={key:this.crypto.did,name:this.appName}}get publicKey(){return this.crypto.publicKey}async sign(e){return this.crypto.sign(e)}async verify(e,M){if(!await this.crypto.verify(e,M))throw new InvalidSignatureError}async signAction(e,M){const tr=e.context?.prevOpHash??"";return this._signAction(e,tr,M)}async signActionWithResultingState(e,M,tr){const ir=`${e.context?.prevOpHash??""}:${M}`;return this._signAction(e,ir,tr)}async _signAction(e,M,tr){if(tr?.aborted)throw new Error("Signing aborted");const rr=(new Date().getTime()/1e3).toFixed(0),ir=await this.hashAction(e);if(tr?.aborted)throw new Error("Signing aborted");const lr=[rr,this.crypto.did,ir,M],dr=this.buildSignatureMessage(lr),hr=await this.crypto.sign(dr),fr=`0x${this.arrayBufferToHex(hr)}`;if(tr?.aborted)throw new Error("Signing aborted");return[...lr,fr]}async hashAction(e){const M=[e.scope,e.type,JSON.stringify(e.input)].join(""),rr=new TextEncoder().encode(M),ir=await crypto.subtle.digest("SHA-256",rr);return this.arrayBufferToBase64(ir)}buildSignatureMessage(e){const M=e.join(""),tr=`Signed Operation:
135
+ `+M.length.toString();return new TextEncoder().encode(tr+M)}arrayBufferToHex(e){const M=e instanceof Uint8Array?e:new Uint8Array(e);return Array.from(M).map(tr=>tr.toString(16).padStart(2,"0")).join("")}arrayBufferToBase64(e){const M=new Uint8Array(e);let tr="";for(let rr=0;rr<M.length;rr++)tr+=String.fromCharCode(M[rr]);return btoa(tr)}}function createSignatureVerifier(){return async(r,e)=>{const M=r.action.context?.signer;if(!M)return!0;const tr=M.signatures;if(tr.length===0)return!1;const rr=tr[tr.length-1],[ir,lr,dr,hr,fr]=rr;if(lr!==e)return!1;const _r=buildSignatureMessage([ir,lr,dr,hr]),gr=hexToUint8Array(fr),wr=await importPublicKey(e);return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},wr,gr.buffer,_r.buffer)}}function buildSignatureMessage(r){const e=r.join(""),M=`Signed Operation:
136
+ `+e.length.toString();return new TextEncoder().encode(M+e)}function hexToUint8Array(r){const e=r.startsWith("0x")?r.slice(2):r,M=new Uint8Array(e.length/2);for(let tr=0;tr<e.length;tr+=2)M[tr/2]=parseInt(e.substring(tr,tr+2),16);return M}async function importPublicKey(r){const e=extractKeyFromDid(r);return crypto.subtle.importKey("raw",e.buffer,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"])}function extractKeyFromDid(r){const e=r.split(":");if(e.length<3||e[0]!=="did"||e[1]!=="key")throw new Error(`Invalid DID format: ${r}`);const M=e[2];if(!M.startsWith("z"))throw new Error(`Unsupported multibase encoding: ${M[0]}`);const tr=base58Decode(M.slice(1));if(tr[0]!==128||tr[1]!==36)throw new Error("Not a P-256 public key multicodec");const rr=tr.slice(2);return decompressP256PublicKey(rr)}function base58Decode(r){const e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",M=new Map;for(let rr=0;rr<e.length;rr++)M.set(e[rr],rr);if(r.length===0)return new Uint8Array(0);const tr=[0];for(const rr of r){const ir=M.get(rr);if(ir===void 0)throw new Error(`Invalid base58 character: ${rr}`);let lr=ir;for(let dr=0;dr<tr.length;dr++)lr+=tr[dr]*58,tr[dr]=lr&255,lr>>=8;for(;lr>0;)tr.push(lr&255),lr>>=8}for(const rr of r){if(rr!=="1")break;tr.push(0)}return new Uint8Array(tr.reverse())}function decompressP256PublicKey(r){if(r.length!==33)throw new Error(`Invalid compressed key length: ${r.length}`);const e=r[0];if(e!==2&&e!==3)throw new Error(`Invalid compression prefix: ${e}`);const M=BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),tr=BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),rr=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");let ir=BigInt(0);for(let wr=1;wr<r.length;wr++)ir=ir<<BigInt(8)|BigInt(r[wr]);const lr=(modPow(ir,BigInt(3),M)+tr*ir+rr)%M;let dr=modPow(lr,(M+BigInt(1))/BigInt(4),M);dr%BigInt(2)===BigInt(0)!==(e===2)&&(dr=M-dr);const mr=new Uint8Array(65);mr[0]=4;const _r=bigIntToBytes(ir,32),gr=bigIntToBytes(dr,32);return mr.set(_r,1),mr.set(gr,33),mr}function modPow(r,e,M){let tr=BigInt(1);for(r=r%M;e>BigInt(0);)e%BigInt(2)===BigInt(1)&&(tr=tr*r%M),e=e>>BigInt(1),r=r*r%M;return tr}function bigIntToBytes(r,e){const M=new Uint8Array(e);for(let tr=e-1;tr>=0;tr--)M[tr]=Number(r&BigInt(255)),r=r>>BigInt(8);return M}class BaseStorage{}class MemoryStorage extends BaseStorage{data=new Map;get(e){return this.data.get(e)}set(e,M){M===void 0?this.data.delete(e):this.data.set(e,M)}delete(e){this.data.delete(e)}}class RenownMemoryStorage extends MemoryStorage{}class Renown{#e;#t;#r;#s;#n;#a;constructor(e,M,tr,rr,ir=DEFAULT_RENOWN_URL){this.#t=e,this.#r=M,this.#e=ir,this.#n=tr,this.#s=rr,this.#a=new RenownCryptoSigner(tr,this.#s,this.user),this.on("user",lr=>{this.#a.user=lr})}get baseUrl(){return this.#e}get user(){return this.#t.get("user")}get signer(){return this.#a}get did(){return this.#n.did}#o(e){e?this.#t.set("user",e):this.#t.delete("user"),this.#r.emit("user",e)}async login(e){try{const M=parsePkhDid(e),tr=await this.#i(M.address,M.chainId,this.#n.did);if(!tr)throw this.#o(void 0),new Error("Credential not found");const rr={...M,address:tr.issuer.ethereumAddress,did:e,credential:tr};return this.#o(rr),rr}catch(M){throw this.#o(void 0),M}}logout(){return this.#o(void 0),Promise.resolve()}on(e,M){return this.#r.on(e,M)}async#i(e,M,tr){if(!this.#e)throw new Error("RENOWN_URL is not set");const rr=new URL(`/api/auth/credential?address=${encodeURIComponent(e)}&chainId=${encodeURIComponent(M)}&connectId=${encodeURIComponent(tr)}`,this.#e),ir=await fetch(rr,{method:"GET"});if(ir.ok)return(await ir.json()).credential;throw new Error(`Failed to get credential: ${ir.status}`)}async verifyBearerToken(e){return verifyAuthBearerToken(e)}async getBearerToken(e){if(!this.user)throw new Error("User not found");return this.#n.getBearerToken(this.user.address,e)}}class TypedCustomEvent extends CustomEvent{constructor(e,M){super(e,{detail:M})}}class BrowserEventEmitter{#e=new EventTarget;on(e,M){const tr=rr=>{rr instanceof TypedCustomEvent&&M(rr.detail)};return this.#e.addEventListener(e.toString(),tr),()=>{this.#e.removeEventListener(e.toString(),tr)}}emit(e,M){const tr=new TypedCustomEvent(e.toString(),M);this.#e.dispatchEvent(tr)}}class MemoryEventEmitter{#e=new Map;on(e,M){return this.#e.has(e)||this.#e.set(e,new Set),this.#e.get(e).add(M),()=>{this.#e.get(e)?.delete(M)}}emit(e,M){this.#e.get(e)?.forEach(tr=>tr(M))}}class BaseRenownBuilder{#e;#t;#r;#s;#n;#a;constructor(e){this.#e=e}withStorage(e){return this.#t=e,this}withEventEmitter(e){return this.#r=e,this}withCrypto(e){return this.#s=e,this}withKeyPairStorage(e){return this.#n=e,this}withBaseUrl(e){return this.#a=e,this}async build(){if(!this.#s&&!this.#n)throw new Error("Either crypto or keyPairStorage is required. Use withCrypto() or withKeyPairStorage() to set one.");const e=this.#s??await new RenownCryptoBuilder().withKeyPairStorage(this.#n).build(),M=this.#t??new RenownMemoryStorage,tr=this.#r??new MemoryEventEmitter,rr=this.#a??DEFAULT_RENOWN_URL,ir=new Renown(M,tr,e,this.#e,rr);if(ir.user)try{await ir.login(ir.user.did)}catch(lr){console.error("Failed to re-authenticate user:",lr)}return ir}static from(e){const M=new BaseRenownBuilder(e.appName);return e.storage&&M.withStorage(e.storage),e.eventEmitter&&M.withEventEmitter(e.eventEmitter),e.crypto&&M.withCrypto(e.crypto),e.keyPairStorage&&M.withKeyPairStorage(e.keyPairStorage),e.baseUrl&&M.withBaseUrl(e.baseUrl),M}}class BrowserStorage extends BaseStorage{namespace;constructor(e,M){super(),this.namespace=`${M}:${e}`}#e(e){return`${this.namespace}:${e.toString()}`}get(e){const M=localStorage.getItem(this.#e(e));if(M)return JSON.parse(M)}set(e,M){return M?localStorage.setItem(this.#e(e),JSON.stringify(M)):localStorage.removeItem(this.#e(e))}delete(e){return localStorage.removeItem(this.#e(e))}}class BrowserRenownStorage extends BrowserStorage{}class BrowserRenownEventEmitter extends BrowserEventEmitter{}class RenownBuilder extends BaseRenownBuilder{#e;#t;constructor(e,M={}){super(e),this.#e=M.basename,this.#t=M.keyDbName,this.withStorage(new BrowserRenownStorage("renown",this.#e)),this.withEventEmitter(new BrowserRenownEventEmitter),M.baseUrl&&this.withBaseUrl(M.baseUrl)}withBasename(e){return this.#e=e,this.withStorage(new BrowserRenownStorage("renown",this.#e)),this}withKeyDbName(e){return this.#t=e,this}async build(){const e=await BrowserKeyStorage.create(this.#t);return this.withKeyPairStorage(e),super.build()}}const DEFAULT_DEBOUNCE_DELAY_MS=200,DEFAULT_IMMEDIATE_THRESHOLD_MS=1e3;async function _refreshReactorDataClient(r){if(!r)return;const e=await r.find({type:"powerhouse/document-drive"});setDrives(e.results)}function createDebouncedRefreshReactorDataClient(r=DEFAULT_DEBOUNCE_DELAY_MS,e=DEFAULT_IMMEDIATE_THRESHOLD_MS){let M=null,tr=0;return(rr,ir=!1)=>{const lr=Date.now(),dr=lr-tr;return M!==null&&clearTimeout(M),ir||dr>=e?(tr=lr,_refreshReactorDataClient(rr)):new Promise(hr=>{M=setTimeout(()=>{tr=Date.now(),_refreshReactorDataClient(rr).then(hr)},r)})}}const refreshReactorDataClient=createDebouncedRefreshReactorDataClient();export{useEditorModuleById as $,convertLegacyLibToVetraPackage as A,setVetraPackages as B,createSignatureVerifier as C,ReactorBuilder as D,ChannelScheme as E,addRemoteDrive as F,GqlRequestChannel as G,useSelectedDocument as H,IntervalPollTimer as I,validateDocument as J,Kysely as K,exportFile as L,useSelectedDrive as M,useSelectedDocumentId as N,useDriveEditorModuleById as O,PGliteDialect as P,QueryClient as Q,ReactorClientBuilder as R,SyncOperationStatus as S,useDefaultDriveEditorModule as T,useSyncList as U,driveCollectionId as V,We as W,useSelectedTimelineItem as X,useRevisionHistoryVisible as Y,useDocumentOperations as Z,useDocumentModelModuleById as _,useSetPHDocumentEditorConfig as a,setDriveAvailableOffline as a$,useFallbackEditorModule as a0,setRevisionHistoryVisible as a1,getRevisionFromDate as a2,usePHModal as a3,DEFAULT_DRIVE_EDITOR_ID as a4,COMMON_PACKAGE_ID as a5,Cr as a6,Ur as a7,Pr as a8,u as a9,setDrives as aA,setFeatures as aB,refreshReactorDataClient as aC,dropAllReactorStorage as aD,useUser as aE,useSelectedFolder as aF,setPHDocumentEditorConfig as aG,setPHDriveEditorConfig as aH,useDrives as aI,useReactorClient as aJ,useInspectorEnabled as aK,logout as aL,openRenown as aM,useRenown as aN,useDriveEditorModules as aO,closePHModal as aP,addDrive as aQ,useParentFolderForSelectedNode as aR,addDocument as aS,removeTrigger as aT,registerNewPullResponderTrigger as aU,addTrigger as aV,useDriveById as aW,deleteDrive as aX,useNodeById as aY,deleteNode as aZ,setDriveSharingType as a_,k as aa,R$1 as ab,x$3 as ac,h$1 as ad,T$2 as ae,Nr as af,createRelationalDb as ag,createOrGetAnalyticsStore as ah,DEFAULT_ANALYTICS_PROCESSOR_DB_NAME as ai,addPHEventHandlers as aj,setPHToast as ak,BrowserKeyStorage as al,RenownCryptoBuilder as am,RenownBuilder as an,getDrives as ao,extractDriveSlugFromPath as ap,extractNodeSlugFromPath as aq,login as ar,ReactorClientDocumentCache as as,setDefaultPHGlobalConfig as at,setReactorClientModule as au,setReactorClient as av,setDocumentCache as aw,setConnectCrypto as ax,setDid as ay,setRenown as az,usePHToast as b,renameDrive as b0,useVetraPackages as b1,makeVetraPackageManifest as b2,useDatabase as b3,usePGlite as b4,REACTOR_SCHEMA as b5,sql as b6,useReactorClientModule as b7,InMemoryQueue as b8,useSync as b9,AnalyticsSubscriptionManager as ba,DateTime as bb,AnalyticsPath as bc,require$$9 as bd,PassthroughAnalyticsProfiler as be,ur as bf,C$1 as bg,cr as bh,pr as bi,U$1 as bj,useDocumentModelModules as bk,showCreateDocumentModal as bl,useNodesInSelectedDriveOrFolder as bm,isFileNodeKind as bn,isFolderNodeKind as bo,useSetPHDriveEditorConfig as bp,__viteBrowserExternal$1 as bq,useUserPermissions as c,useSelectedDriveSafe as d,useSelectedDriveId as e,useSelectedNodePath as f,setSelectedNode as g,addFolder as h,useDocumentById as i,useSelectedDocumentSafe as j,useNodeActions as k,useNodeParentFolderById as l,useGetSwitchboardLink as m,showRevisionHistory as n,setSelectedTimelineItem as o,exportDocument as p,useIsDragAndDropEnabled as q,useOnDropFile as r,setSelectedDrive as s,keccak_256 as t,useSelectedDocumentOfType as u,useQuery as v,getSyncStatusSync as w,showDeleteNodeModal as x,showPHModal as y,QueryClientProvider as z};