@powerhousedao/ph-clint-app 0.1.0-dev.89 → 0.1.0-dev.90
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.
- package/dist/browser/{editor-BuHwuzRa.js → editor-Bp2wUo8R.js} +748 -522
- package/dist/browser/editor-Bp2wUo8R.js.map +1 -0
- package/dist/browser/editors/ph-clint-project-editor/module.js +1 -1
- package/dist/connect/assets/{AddDriveModal-BoKLJyUY-DwlVwt2n.js → AddDriveModal-BoKLJyUY-cGJwd_2F.js} +2 -2
- package/dist/connect/assets/{AddDriveModal-BoKLJyUY-DwlVwt2n.js.map → AddDriveModal-BoKLJyUY-cGJwd_2F.js.map} +1 -1
- package/dist/connect/assets/{ClearStorageModal-CXoNWmRe-lBEW3sSH.js → ClearStorageModal-CXoNWmRe-D3ifKRm-.js} +2 -2
- package/dist/connect/assets/{ClearStorageModal-CXoNWmRe-lBEW3sSH.js.map → ClearStorageModal-CXoNWmRe-D3ifKRm-.js.map} +1 -1
- package/dist/connect/assets/{CookiesPolicyModal-1nOh6oN3-BYSDp-5J.js → CookiesPolicyModal-1nOh6oN3-kK_sx5mz.js} +2 -2
- package/dist/connect/assets/{CookiesPolicyModal-1nOh6oN3-BYSDp-5J.js.map → CookiesPolicyModal-1nOh6oN3-kK_sx5mz.js.map} +1 -1
- package/dist/connect/assets/{CreateDocumentModal-nQbLVDq3-DJbJhlYp.js → CreateDocumentModal-nQbLVDq3-DFAye2CX.js} +2 -2
- package/dist/connect/assets/{CreateDocumentModal-nQbLVDq3-DJbJhlYp.js.map → CreateDocumentModal-nQbLVDq3-DFAye2CX.js.map} +1 -1
- package/dist/connect/assets/{DebugSettingsModal-5SDhy5gt-Du3PKhbh.js → DebugSettingsModal-5SDhy5gt-DLMPdDQB.js} +2 -2
- package/dist/connect/assets/{DebugSettingsModal-5SDhy5gt-Du3PKhbh.js.map → DebugSettingsModal-5SDhy5gt-DLMPdDQB.js.map} +1 -1
- package/dist/connect/assets/{DeleteDriveModal-6P0T1QgD-CaEKmseP.js → DeleteDriveModal-6P0T1QgD-CK6cPXbT.js} +2 -2
- package/dist/connect/assets/{DeleteDriveModal-6P0T1QgD-CaEKmseP.js.map → DeleteDriveModal-6P0T1QgD-CK6cPXbT.js.map} +1 -1
- package/dist/connect/assets/{DeleteItemModal-BmV1aQyZ-B01dssV-.js → DeleteItemModal-BmV1aQyZ-Ld9lHNhl.js} +2 -2
- package/dist/connect/assets/{DeleteItemModal-BmV1aQyZ-B01dssV-.js.map → DeleteItemModal-BmV1aQyZ-Ld9lHNhl.js.map} +1 -1
- package/dist/connect/assets/{DisclaimerModal-CVTFfN0_-CfPGYzP1.js → DisclaimerModal-CVTFfN0_-D7N9TDI4.js} +2 -2
- package/dist/connect/assets/{DisclaimerModal-CVTFfN0_-CfPGYzP1.js.map → DisclaimerModal-CVTFfN0_-D7N9TDI4.js.map} +1 -1
- package/dist/connect/assets/{DownloadDocumentWithErrorsModal-CXeFUtaz-UexzRqQT.js → DownloadDocumentWithErrorsModal-CXeFUtaz-CYIIl42M.js} +2 -2
- package/dist/connect/assets/{DownloadDocumentWithErrorsModal-CXeFUtaz-UexzRqQT.js.map → DownloadDocumentWithErrorsModal-CXeFUtaz-CYIIl42M.js.map} +1 -1
- package/dist/connect/assets/{DriveAuthRequiredModal-B3VdLwSH-C5FZCMC5.js → DriveAuthRequiredModal-B3VdLwSH-fqmI_4sF.js} +2 -2
- package/dist/connect/assets/{DriveAuthRequiredModal-B3VdLwSH-C5FZCMC5.js.map → DriveAuthRequiredModal-B3VdLwSH-fqmI_4sF.js.map} +1 -1
- package/dist/connect/assets/{DriveSettingsModal-CsNFEJ9E-BoXSbW1c.js → DriveSettingsModal-CsNFEJ9E-BR2vyeU8.js} +2 -2
- package/dist/connect/assets/{DriveSettingsModal-CsNFEJ9E-BoXSbW1c.js.map → DriveSettingsModal-CsNFEJ9E-BR2vyeU8.js.map} +1 -1
- package/dist/connect/assets/{InspectorModal-BsSihzuc-hukmcBoP.js → InspectorModal-BsSihzuc-B0n5gbGB.js} +2 -2
- package/dist/connect/assets/{InspectorModal-BsSihzuc-hukmcBoP.js.map → InspectorModal-BsSihzuc-B0n5gbGB.js.map} +1 -1
- package/dist/connect/assets/{MissingPackageModal-Bn036mWQ-BOXHWmFa.js → MissingPackageModal-Bn036mWQ-C021G1nV.js} +2 -2
- package/dist/connect/assets/{MissingPackageModal-Bn036mWQ-BOXHWmFa.js.map → MissingPackageModal-Bn036mWQ-C021G1nV.js.map} +1 -1
- package/dist/connect/assets/{SettingsModal-S_A5qf95-Fz0f2CXX.js → SettingsModal-S_A5qf95-uzigz0nk.js} +2 -2
- package/dist/connect/assets/{SettingsModal-S_A5qf95-Fz0f2CXX.js.map → SettingsModal-S_A5qf95-uzigz0nk.js.map} +1 -1
- package/dist/connect/assets/{UpgradeDriveModal-C7lV4rAX-BkeBWpDi.js → UpgradeDriveModal-C7lV4rAX-CTIf4duw.js} +2 -2
- package/dist/connect/assets/{UpgradeDriveModal-C7lV4rAX-BkeBWpDi.js.map → UpgradeDriveModal-C7lV4rAX-CTIf4duw.js.map} +1 -1
- package/dist/connect/assets/build-info-cc1PjSvF-DtAGzh0W.js.map +1 -1
- package/dist/connect/assets/chunk-pbuEa-1d-KEQyMDN_.js.map +1 -1
- package/dist/connect/assets/{components-ByEUkO4U-Mc23VVA-.js → components-ByEUkO4U-xPZUVkzr.js} +4 -4
- package/dist/connect/assets/{components-ByEUkO4U-Mc23VVA-.js.map → components-ByEUkO4U-xPZUVkzr.js.map} +1 -1
- package/dist/connect/assets/{components-HCKyLh9m.js → components-Djrujufg.js} +2 -2
- package/dist/connect/assets/{components-HCKyLh9m.js.map → components-Djrujufg.js.map} +1 -1
- package/dist/connect/assets/{connect-pRAhId57.js → connect-CGvtDtZh.js} +2 -2
- package/dist/connect/assets/{connect-pRAhId57.js.map → connect-CGvtDtZh.js.map} +1 -1
- package/dist/connect/assets/{connect.config-Bt4pvvWV-CAyer5pZ.js → connect.config-Bt4pvvWV-Dj3FkjaZ.js} +2 -2
- package/dist/connect/assets/{connect.config-Bt4pvvWV-CAyer5pZ.js.map → connect.config-Bt4pvvWV-Dj3FkjaZ.js.map} +1 -1
- package/dist/connect/assets/{dist-DmhUSVtT.js → dist-t-ezfpxv.js} +3 -3
- package/dist/connect/assets/{dist-DmhUSVtT.js.map → dist-t-ezfpxv.js.map} +1 -1
- package/dist/connect/assets/{editor-B560eld_-CIE3_3II.js → editor-B560eld_-DLpKHubk.js} +2 -2
- package/dist/connect/assets/{editor-B560eld_-CIE3_3II.js.map → editor-B560eld_-DLpKHubk.js.map} +1 -1
- package/dist/connect/assets/editor-BaQ62r3i.js +2 -0
- package/dist/connect/assets/editor-BaQ62r3i.js.map +1 -0
- package/dist/connect/assets/{editor-CAVHtR-v-ClzvSfK5.js → editor-CAVHtR-v-D33T9vW0.js} +2 -2
- package/dist/connect/assets/{editor-CAVHtR-v-ClzvSfK5.js.map → editor-CAVHtR-v-D33T9vW0.js.map} +1 -1
- package/dist/connect/assets/{editor-CVCLxUhe-C6nP7EPN.js → editor-CVCLxUhe-C9Ftgu1S.js} +2 -2
- package/dist/connect/assets/{editor-CVCLxUhe-C6nP7EPN.js.map → editor-CVCLxUhe-C9Ftgu1S.js.map} +1 -1
- package/dist/connect/assets/{editor-DnG2Zzet-CRhirYbH.js → editor-DnG2Zzet-CQ38uSti.js} +2 -2
- package/dist/connect/assets/{editor-DnG2Zzet-CRhirYbH.js.map → editor-DnG2Zzet-CQ38uSti.js.map} +1 -1
- package/dist/connect/assets/{editor-mor7dV6n-DDigdbLM.js → editor-mor7dV6n-NTU9k1uj.js} +2 -2
- package/dist/connect/assets/{editor-mor7dV6n-DDigdbLM.js.map → editor-mor7dV6n-NTU9k1uj.js.map} +1 -1
- package/dist/connect/assets/{editor-xCnDas6c-CyHuSL7M.js → editor-xCnDas6c-DdGhx--5.js} +2 -2
- package/dist/connect/assets/{editor-xCnDas6c-CyHuSL7M.js.map → editor-xCnDas6c-DdGhx--5.js.map} +1 -1
- package/dist/connect/assets/esm-dD38MHAT.js +10 -0
- package/dist/connect/assets/esm-dD38MHAT.js.map +1 -0
- package/dist/connect/assets/{hooks-Btogj1f0-CMXQZV6d.js → hooks-Btogj1f0-BKAAmyt-.js} +2 -2
- package/dist/connect/assets/{hooks-Btogj1f0-CMXQZV6d.js.map → hooks-Btogj1f0-BKAAmyt-.js.map} +1 -1
- package/dist/connect/assets/index-NB86TKkT.js +3 -0
- package/dist/connect/assets/{index-DS7vbdaR.js.map → index-NB86TKkT.js.map} +1 -1
- package/dist/connect/assets/{load-BWibkoFV-BVilFVpD.js → load-BWibkoFV-CDRjWwYQ.js} +2 -2
- package/dist/connect/assets/{load-BWibkoFV-BVilFVpD.js.map → load-BWibkoFV-CDRjWwYQ.js.map} +1 -1
- package/dist/connect/assets/module-1hr_ne9w-CWAVsMzZ.js.map +1 -1
- package/dist/connect/assets/{module-DP3LMNU7.js → module-7zCQE1MC.js} +2 -2
- package/dist/connect/assets/{module-DP3LMNU7.js.map → module-7zCQE1MC.js.map} +1 -1
- package/dist/connect/assets/module-CRq_lUkG-D61oeRlC.js.map +1 -1
- package/dist/connect/assets/module-DP3bVbak-VbUPIBZP.js.map +1 -1
- package/dist/connect/assets/package-BZLLR0Ma-B7vswMvI.js.map +1 -1
- package/dist/connect/assets/{pglite-seed-BWk7yOwr-T-NGWlGh.js → pglite-seed-BWk7yOwr-b2F0oJiP.js} +2 -2
- package/dist/connect/assets/{pglite-seed-BWk7yOwr-T-NGWlGh.js.map → pglite-seed-BWk7yOwr-b2F0oJiP.js.map} +1 -1
- package/dist/connect/assets/pglite.worker-BuyZ0d7u.js.map +1 -1
- package/dist/connect/assets/pglite.worker.legacy-D5InEf0i.js.map +1 -1
- package/dist/connect/assets/{ph-clint-project-BZ5X7dVQ.js → ph-clint-project-p1zY6e17.js} +2 -2
- package/dist/connect/assets/{ph-clint-project-BZ5X7dVQ.js.map → ph-clint-project-p1zY6e17.js.map} +1 -1
- package/dist/connect/assets/{reactor-BxNvHOKC-DmVBqCt_.js → reactor-BxNvHOKC-CeMF1M2u.js} +4 -4
- package/dist/connect/assets/{reactor-BxNvHOKC-DmVBqCt_.js.map → reactor-BxNvHOKC-CeMF1M2u.js.map} +1 -1
- package/dist/connect/assets/{registerServiceWorker-D9l1kja7-oC4nicB2.js → registerServiceWorker-D9l1kja7-DG3DqQna.js} +2 -2
- package/dist/connect/assets/{registerServiceWorker-D9l1kja7-oC4nicB2.js.map → registerServiceWorker-D9l1kja7-DG3DqQna.js.map} +1 -1
- package/dist/connect/assets/reload-connect-toast-CwvSc6F--BQcqGaN_.js.map +1 -1
- package/dist/connect/assets/runtime-config-DL3QjcfM-D9g4VFtY.js.map +1 -1
- package/dist/connect/assets/toast-BEy42aYx-Dg_jZf6v.js.map +1 -1
- package/dist/connect/assets/{useRegistryPackages-B-gFECmd-CXOBKziY.js → useRegistryPackages-B-gFECmd-C8h2M5qM.js} +2 -2
- package/dist/connect/assets/{useRegistryPackages-B-gFECmd-CXOBKziY.js.map → useRegistryPackages-B-gFECmd-C8h2M5qM.js.map} +1 -1
- package/dist/connect/assets/{useVetraDocument-tpjMF571-DT5T1mNT.js → useVetraDocument-tpjMF571-DxT9GgCx.js} +2 -2
- package/dist/connect/assets/{useVetraDocument-tpjMF571-DT5T1mNT.js.map → useVetraDocument-tpjMF571-DxT9GgCx.js.map} +1 -1
- package/dist/connect/assets/utils-BiV3cs9Y-B7i9WJ1b.js.map +1 -1
- package/dist/connect/assets/{utils-CkWB3DRk-CxqNKFWP.js → utils-CkWB3DRk-BURJYofr.js} +2 -2
- package/dist/connect/assets/{utils-CkWB3DRk-CxqNKFWP.js.map → utils-CkWB3DRk-BURJYofr.js.map} +1 -1
- package/dist/connect/index.html +3 -3
- package/dist/connect/powerhouse.config.json +1 -1
- package/dist/node/{editor-Bev0bZuJ.mjs → editor-BC9t7D3T.mjs} +748 -517
- package/dist/node/editor-BC9t7D3T.mjs.map +1 -0
- package/dist/node/editors/ph-clint-project-editor/module.mjs +1 -1
- package/package.json +2 -2
- package/dist/browser/editor-BuHwuzRa.js.map +0 -1
- package/dist/connect/assets/editor-BrPMvNFl.js +0 -2
- package/dist/connect/assets/editor-BrPMvNFl.js.map +0 -1
- package/dist/connect/assets/esm-mbrYcWED.js +0 -10
- package/dist/connect/assets/esm-mbrYcWED.js.map +0 -1
- package/dist/connect/assets/index-DS7vbdaR.js +0 -3
- package/dist/node/editor-Bev0bZuJ.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/esm-DUjqbF8m.js","assets/esm-0nAQjFUV.js","assets/dist-ScMbe_zR.js","assets/chunk-3WWIVTCY-Dk4atnGX.js","assets/chunk-BNv3lrIs.js","assets/preload-helper-ca-nBW7U.js","assets/chunk-QY3QWFKW-Dw6-Hpdq.js","assets/dist-DC27BFRa.js","assets/chunk-F2DQ4FIK-B5wKwnbU.js","assets/chunk-VBDAOXYI-BWd303gi.js","assets/dist-PLXkZ7-H.js","assets/dist-DMXkjzve.js","assets/projection-shard-manager-_c7orNo5-CYmXImZA.js","assets/types-CxSpmNGK-BaNo7EHQ.js","assets/dist-Cb4AoJ-8.js","assets/__vite-browser-external-Bo8I1g8S.js","assets/transport-CuogVKN_-CmEFLNk5.js","assets/worker-handle-B1w03nRA-BHJaS5pO.js","assets/error-info-Cpu4OY3o-DJ8lg6ye.js","assets/errors-D3S6Eysd-DUmQAeoG.js","assets/transport-ByGviWdZ-zEKFyLfk.js","assets/worker-XYrQaEmt-Ce3Gpb8t.js","assets/worker-XYrQaEmt-w0FhumYk.js","assets/esm-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/esm-DUjqbF8m.js","assets/esm-0nAQjFUV.js","assets/dist-ScMbe_zR.js","assets/chunk-3WWIVTCY-Dk4atnGX.js","assets/chunk-BNv3lrIs.js","assets/preload-helper-ca-nBW7U.js","assets/chunk-QY3QWFKW-Dw6-Hpdq.js","assets/dist-DC27BFRa.js","assets/chunk-F2DQ4FIK-B5wKwnbU.js","assets/chunk-VBDAOXYI-BWd303gi.js","assets/dist-PLXkZ7-H.js","assets/dist-DMXkjzve.js","assets/projection-shard-manager-_c7orNo5-CYmXImZA.js","assets/types-CxSpmNGK-BaNo7EHQ.js","assets/dist-Cb4AoJ-8.js","assets/__vite-browser-external-Bo8I1g8S.js","assets/transport-CuogVKN_-CmEFLNk5.js","assets/worker-handle-B1w03nRA-BHJaS5pO.js","assets/error-info-Cpu4OY3o-DJ8lg6ye.js","assets/errors-D3S6Eysd-DUmQAeoG.js","assets/transport-ByGviWdZ-zEKFyLfk.js","assets/worker-XYrQaEmt-Ce3Gpb8t.js","assets/worker-XYrQaEmt-w0FhumYk.js","assets/esm-dD38MHAT.js","assets/secp256k1-DAbCo5Cm.js","assets/hmac-wnxCe4SN.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{a as e,r as t,t as n}from"./chunk-BNv3lrIs.js";import{t as r}from"./preload-helper-ca-nBW7U.js";import{$ as i,B as a,C as o,G as s,J as c,K as l,N as u,P as d,Q as f,S as p,V as m,W as h,X as g,Z as _,_ as v,at as y,b,et as x,f as ee,g as te,h as ne,i as S,it as C,m as re,n as w,nt as ie,o as ae,p as oe,q as se,r as ce,rt as T,x as le,y as ue,z as de}from"./types-CxSpmNGK-BaNo7EHQ.js";import{a as E,i as fe,r as pe,t as me}from"./dist-Cb4AoJ-8.js";import{C as he,D as ge,E as _e,O as D,S as ve,T as ye,_ as be,a as xe,b as Se,c as Ce,d as we,f as Te,g as Ee,h as De,i as Oe,k as ke,l as Ae,m as je,o as Me,p as Ne,r as Pe,s as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./worker-XYrQaEmt-w0FhumYk.js";import{m as Ve}from"./esm-0nAQjFUV.js";import{i as He,r as Ue,t as We}from"./errors-D3S6Eysd-DUmQAeoG.js";import{C as Ge,D as Ke,E as qe,O as Je,S as Ye,T as Xe,_ as Ze,a as Qe,b as $e,c as et,d as tt,f as nt,g as rt,h as it,i as at,k as ot,l as st,m as O,n as ct,o as lt,p as ut,r as dt,s as ft,t as pt,u as mt,v as ht,w as gt,x as _t,y as vt}from"./hmac-wnxCe4SN.js";import{jsx as yt,jsxs as bt}from"react/jsx-runtime";import{Children as xt,cloneElement as St,forwardRef as Ct,isValidElement as wt,use as Tt,useCallback as Et,useEffect as Dt,useMemo as Ot,useRef as kt,useState as At,useSyncExternalStore as jt}from"react";function Mt(e,t,n){let r=n=>e(n,...t);return n===void 0?r:Object.assign(r,{lazy:n,lazyArgs:t})}function Nt(e,t,n){let r=e.length-t.length;if(r===0)return e(...t);if(r===1)return Mt(e,t,n);throw Error(`Wrong number of arguments`)}function Pt(...e){return Nt(Ft,e)}var Ft=(e,t)=>t.every(t=>t(e)),It={done:!1,hasNext:!1};function Lt(e,...t){let n=e,r=t.map(e=>`lazy`in e?zt(e):void 0),i=0;for(;i<t.length;){if(r[i]===void 0||!Bt(n)){let e=t[i];n=e(n),i+=1;continue}let e=[];for(let n=i;n<t.length;n++){let t=r[n];if(t===void 0||(e.push(t),t.isSingle))break}let a=[];for(let t of n)if(Rt(t,a,e))break;let{isSingle:o}=e.at(-1);n=o?a[0]:a,i+=e.length}return n}function Rt(e,t,n){if(n.length===0)return t.push(e),!1;let r=e,i=It,a=!1;for(let[e,o]of n.entries()){let{index:s,items:c}=o;if(c.push(r),i=o(r,s,c),o.index+=1,i.hasNext){if(i.hasMany??!1){for(let r of i.next)if(Rt(r,t,n.slice(e+1)))return!0;return a}r=i.next}if(!i.hasNext)break;i.done&&(a=!0)}return i.hasNext&&t.push(r),a}function zt(e){let{lazy:t,lazyArgs:n}=e,r=t(...n);return Object.assign(r,{isSingle:t.single??!1,index:0,items:[]})}function Bt(e){return typeof e==`string`||typeof e==`object`&&!!e&&Symbol.iterator in e}function Vt(...e){return Nt(Ht,e)}var Ht=(e,t)=>e.length>=t;function Ut(...e){return Nt(Wt,e,Gt)}var Wt=(e,t)=>e.filter(t),Gt=e=>(t,n,r)=>e(t,n,r)?{done:!1,hasNext:!0,next:t}:It,Kt=e=>Object.assign(e,{single:!0});function qt(...e){return Nt(Jt,e,Kt(Yt))}var Jt=(e,t)=>e.find(t),Yt=e=>(t,n,r)=>e(t,n,r)?{done:!0,hasNext:!0,next:t}:It;function Xt(...e){return Nt(Zt,e)}function Zt(e,t){for(let[n,r]of Object.entries(e))t(r,n,e);return e}var Qt=Symbol(`funnel/voidReducer`),$t=()=>Qt;function en(e,{triggerAt:t=`end`,minQuietPeriodMs:n,maxBurstDurationMs:r,minGapMs:i,reducer:a=$t}){let o,s,c,l,u=()=>{let t=c;t!==void 0&&(c=void 0,t===Qt?e():e(t),i!==void 0&&(s=setTimeout(d,i)))},d=()=>{clearTimeout(s),s=void 0,o===void 0&&u()},f=()=>{clearTimeout(o),o=void 0,l=void 0,s===void 0&&u()};return{call:(...e)=>{let d=o===void 0&&s===void 0;if((t!==`start`||d)&&(c=a(c,...e)),!(o===void 0&&!d)){if(n!==void 0||r!==void 0||i===void 0){clearTimeout(o);let e=Date.now();l??=e;let t=r===void 0?n??0:Math.min(n??r,Math.max(0,r-(e-l)));o=setTimeout(f,t)}t!==`end`&&d&&u()}},cancel:()=>{clearTimeout(o),o=void 0,l=void 0,clearTimeout(s),s=void 0,c=void 0},flush:()=>{f(),d()},get isIdle(){return o===void 0&&s===void 0}}}function tn(e){return Array.isArray(e)}function nn(e){return e!==void 0}function rn(e,t){if(t===void 0){let t=new Set(e);return e=>t.has(e)}return t.includes(e)}function an(...e){return Nt(on,e)}var on=(e,t)=>e===t||Object.is(e,t);function sn(e){return!!e}function cn(...e){return Nt(ln,e)}var ln=e=>e.at(-1);function un(...e){return Nt(dn,e,fn)}var dn=(e,t)=>e.map(t),fn=e=>(t,n,r)=>({done:!1,hasNext:!0,next:e(t,n,r)});function pn(e){let t=!1,n;return()=>(t||=(n=e(),!0),n)}function mn(e,t,n){return typeof t==`number`||t===void 0?n=>n.split(e,t):e.split(t,n)}var hn=typeof window>`u`;function k(e){let t=`ph:set${se(e)}`,n=`ph:${e}Updated`;function r(n){if(hn)return;let r=new CustomEvent(t,{detail:{[e]:n}});window.dispatchEvent(r)}function i(){if(hn)return;let e=new CustomEvent(n);window.dispatchEvent(e)}function a(t){if(hn)return;let n=t.detail[e];window.ph||(window.ph={}),window.ph[e]=n,i()}function o(){hn||window.addEventListener(t,a)}function s(e){return hn?()=>{}:(window.addEventListener(n,e),()=>{window.removeEventListener(n,e)})}function c(){if(!hn)return window.ph?.[e]}function l(){}function u(){return jt(s,c,l)}return{useValue:u,setValue:r,addEventHandler:o}}var gn=class{lastOrdinal=0;name;constructor(e,t,n,r,i){this.db=e,this.operationIndex=t,this.writeCache=n,this.consistencyTracker=r,this.config=i,this.name=i.readModelId}async init(){let e=await this.loadState();if(e!==void 0){this.lastOrdinal=e;let t=await this.operationIndex.getSinceOrdinal(this.lastOrdinal);if(t.results.length>0){let e=this.config.rebuildStateOnInit?await this.rebuildStateForOperations(t.results):t.results;await this.indexOperations(e)}}else{await this.initializeState();let e=await this.operationIndex.getSinceOrdinal(0);if(e.results.length>0){let t=this.config.rebuildStateOnInit?await this.rebuildStateForOperations(e.results):e.results;await this.indexOperations(t)}}}async indexOperations(e){e.length!==0&&(await this.commitOperations(e),await this.db.transaction().execute(async t=>{await this.saveState(t,e)}),this.updateConsistencyTracker(e))}async waitForConsistency(e,t,n){e.coordinates.length!==0&&await this.consistencyTracker.waitFor(e.coordinates,t,n)}async commitOperations(e){}async rebuildStateForOperations(e){let t=[];for(let n of e){let{documentId:e,scope:r,branch:i}=n.context,a=n.operation.index,o=await this.writeCache.getState(e,r,i,a);t.push({operation:n.operation,context:{...n.context,resultingState:JSON.stringify(o)}})}return t}async loadState(){return(await this.db.selectFrom(`ViewState`).select(`lastOrdinal`).where(`readModelId`,`=`,this.config.readModelId).executeTakeFirst())?.lastOrdinal}async initializeState(){await this.db.insertInto(`ViewState`).values({readModelId:this.config.readModelId,lastOrdinal:0}).execute()}async saveState(e,t){let n=Math.max(...t.map(e=>e.context.ordinal));this.lastOrdinal=n,await e.updateTable(`ViewState`).set({lastOrdinal:n,lastOperationTimestamp:new Date}).where(`readModelId`,`=`,this.config.readModelId).execute()}updateConsistencyTracker(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];t.push({documentId:r.context.documentId,scope:r.context.scope,branch:r.context.branch,operationIndex:r.operation.index})}this.consistencyTracker.update(t)}},_n=class{unsubscribe;isRunning=!1;chains=new Map;logger;readModels;constructor(e,t,n){this.eventBus=e,this.preReady=t,this.postReady=n,this.readModels=[...t,...n],this.logger=pe([`reactor`,`read-model-coordinator`])}start(){this.isRunning||=(this.unsubscribe=this.eventBus.subscribe(w.JOB_WRITE_READY,(e,t)=>this.handleWriteReady(t)),!0)}stop(){this.isRunning&&=(this.unsubscribe&&=(this.unsubscribe(),void 0),!1)}async drain(){for(;this.chains.size>0;){let e=Array.from(this.chains.values());await Promise.allSettled(e)}}getChainDepth(){return this.chains.size}handleWriteReady(e){if(e.operations.length===0){this.emitEmptyReadReady(e);return}let t=performance.now(),n=this.queueKeyFor(e),r=(this.chains.get(n)??Promise.resolve()).then(()=>this.runChain(e,t));this.chains.set(n,r),r.finally(()=>{this.chains.get(n)===r&&this.chains.delete(n)})}async emitEmptyReadReady(e){let t={jobId:e.jobId,operations:e.operations};try{await this.eventBus.emit(w.JOB_READ_READY,t)}catch(t){this.logger.error(`JOB_READ_READY emit failed for job @jobId: @Error`,{jobId:e.jobId},t)}this.emitBatchCompleted({jobId:e.jobId,batchSize:0,chainWaitDurationMs:0,preReadyDurationMs:0,emitDurationMs:0,postReadyDurationMs:0})}async runChain(e,t){let n=performance.now()-t,r=performance.now();try{await Promise.all(this.preReady.map(t=>this.indexWithTiming(t,`pre_ready`,e)))}catch(t){this.logger.error(`Pre-ready read model indexing failed for job @jobId: @Error`,{jobId:e.jobId},t)}let i=performance.now()-r,a={jobId:e.jobId,operations:e.operations},o=performance.now();try{await this.eventBus.emit(w.JOB_READ_READY,a)}catch(t){this.logger.error(`JOB_READ_READY emit failed for job @jobId: @Error`,{jobId:e.jobId},t)}let s=performance.now()-o,c=performance.now();try{await Promise.all(this.postReady.map(t=>this.indexWithTiming(t,`post_ready`,e)))}catch(t){this.logger.error(`Post-ready read model indexing failed for job @jobId: @Error`,{jobId:e.jobId},t)}let l=performance.now()-c;this.emitBatchCompleted({jobId:e.jobId,batchSize:e.operations.length,chainWaitDurationMs:n,preReadyDurationMs:i,emitDurationMs:s,postReadyDurationMs:l})}async indexWithTiming(e,t,n){let r=performance.now(),i=!1;try{await e.indexOperations(n.operations),i=!0}finally{this.emitReadModelIndexed({jobId:n.jobId,readModelName:e.name,stage:t,durationMs:performance.now()-r,operationCount:n.operations.length,success:i})}}emitReadModelIndexed(e){this.eventBus.emit(w.READMODEL_INDEXED,e).catch(t=>this.logger.error(`READMODEL_INDEXED emit failed for job @jobId: @Error`,{jobId:e.jobId},t))}emitBatchCompleted(e){this.eventBus.emit(w.READMODEL_BATCH_COMPLETED,e).catch(t=>this.logger.error(`READMODEL_BATCH_COMPLETED emit failed for job @jobId: @Error`,{jobId:e.jobId},t))}queueKeyFor(e){let t=e.operations[0].context;return`${t.documentId}:${t.scope}:${t.branch}`}},vn=class extends gn{_db;constructor(e,t,n,r,i){super(e,n,r,i,{readModelId:`document-view`,rebuildStateOnInit:!0}),this.operationStore=t,this._db=e}async commitOperations(e){await this._db.transaction().execute(async t=>{for(let n of e){let{operation:e,context:r}=n,{documentId:i,scope:a,branch:o,documentType:s,resultingState:c}=r,{index:l,hash:u}=e;if(!c)throw Error(`Missing resultingState in context for operation ${e.id||`unknown`}. IDocumentView requires resultingState from upstream - it does not rebuild documents.`);let d;try{d=JSON.parse(c)}catch(t){throw Error(`Failed to parse resultingState for operation ${e.id||`unknown`}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}let f=e.action.type;if(f===`DELETE_DOCUMENT`){let e=new Date;await t.updateTable(`DocumentSnapshot`).set({isDeleted:!0,deletedAt:e,lastOperationIndex:l,lastOperationHash:u,lastUpdatedAt:e}).where(`documentId`,`=`,i).where(`branch`,`=`,o).execute(),await t.deleteFrom(`SlugMapping`).where(`documentId`,`=`,i).where(`branch`,`=`,o).execute();continue}let p;if(f===`CREATE_DOCUMENT`)p=Object.entries(d).filter(([e])=>e===`header`||e===`document`||e===`auth`);else if(f===`UPGRADE_DOCUMENT`){let e=[];for(let[n,r]of Object.entries(d)){if(n===`header`){e.push([n,r]);continue}if(n===a){e.push([n,r]);continue}await t.selectFrom(`DocumentSnapshot`).select(`scope`).where(`documentId`,`=`,i).where(`scope`,`=`,n).where(`branch`,`=`,o).executeTakeFirst()||e.push([n,r])}p=e}else p=[],d.header!==void 0&&p.push([`header`,d.header]),d[a]===void 0?p.push([a,{}]):p.push([a,d[a]]);for(let[e,n]of p){let r=await t.selectFrom(`DocumentSnapshot`).selectAll().where(`documentId`,`=`,i).where(`scope`,`=`,e).where(`branch`,`=`,o).executeTakeFirst(),a=typeof n==`object`&&n?n:{},c=r?.slug??null,d=r?.name??null;if(e===`header`){let n=a.slug,r=a.name;typeof n==`string`&&(c=n),typeof r==`string`&&(d=r),c&&c!==i&&await t.insertInto(`SlugMapping`).values({slug:c,documentId:i,scope:e,branch:o}).onConflict(t=>t.column(`slug`).doUpdateSet({documentId:i,scope:e,branch:o})).execute()}if(r)await t.updateTable(`DocumentSnapshot`).set({lastOperationIndex:l,lastOperationHash:u,lastUpdatedAt:new Date,snapshotVersion:r.snapshotVersion+1,content:a,slug:c,name:d}).where(`documentId`,`=`,i).where(`scope`,`=`,e).where(`branch`,`=`,o).execute();else{let n={id:ke(),documentId:i,slug:c,name:d,scope:e,branch:o,content:a,documentType:s,lastOperationIndex:l,lastOperationHash:u,identifiers:null,metadata:null,deletedAt:null};await t.insertInto(`DocumentSnapshot`).values(n).execute()}}}})}async exists(e,t,n){if(t&&await this.waitForConsistency(t,void 0,n),n?.aborted)throw Error(`Operation aborted`);if(e.length===0)return[];let r=await this._db.selectFrom(`DocumentSnapshot`).select([`documentId`]).where(`documentId`,`in`,e).where(`isDeleted`,`=`,!1).distinct().execute(),i=new Set(r.map(e=>e.documentId));return e.map(e=>i.has(e))}async get(e,t,n,r){if(n&&await this.waitForConsistency(n,void 0,r),r?.aborted)throw Error(`Operation aborted`);let i=t?.branch||`main`,a;a=t?.scopes&&t.scopes.length>0?[...new Set([`header`,`document`,...t.scopes])]:[];let o=this._db.selectFrom(`DocumentSnapshot`).selectAll().where(`documentId`,`=`,e).where(`branch`,`=`,i).where(`isDeleted`,`=`,!1);a.length>0&&(o=o.where(`scope`,`in`,a));let s=await o.execute();if(s.length===0)throw Error(`Document not found: ${e}`);if(r?.aborted)throw Error(`Operation aborted`);let c=s.find(e=>e.scope===`header`);if(!c)throw Error(`Document header not found: ${e}`);let l=c.content,u=await this.operationStore.getRevisions(e,i,r);l.revision=u.revision,l.lastModifiedAtUtcIso=u.latestTimestamp;let d={};for(let e of s)e.scope!==`header`&&(d[e.scope]=e.content);return{header:l,state:d,operations:{},initialState:d,clipboard:[]}}async getMany(e,t,n,r){if(e.length===0)return[];if(n&&await this.waitForConsistency(n,void 0,r),r?.aborted)throw Error(`Operation aborted`);let i=t?.branch||`main`,a;a=t?.scopes&&t.scopes.length>0?[...new Set([`header`,`document`,...t.scopes])]:[];let o=this._db.selectFrom(`DocumentSnapshot`).selectAll().where(`documentId`,`in`,e).where(`branch`,`=`,i).where(`isDeleted`,`=`,!1);a.length>0&&(o=o.where(`scope`,`in`,a));let s=await o.execute();if(r?.aborted)throw Error(`Operation aborted`);let c=new Map;for(let e of s){let t=c.get(e.documentId)||[];t.push(e),c.set(e.documentId,t)}let l=[...c.keys()],u=await Promise.all(l.map(e=>this.operationStore.getRevisions(e,i,r))),d=new Map;for(let e=0;e<l.length;e++)d.set(l[e],u[e]);if(r?.aborted)throw Error(`Operation aborted`);let f=[];for(let t of e){let e=c.get(t);if(!e||e.length===0)continue;let n=e.find(e=>e.scope===`header`);if(!n)continue;let r=n.content,i=d.get(t);i&&(r.revision=i.revision,r.lastModifiedAtUtcIso=i.latestTimestamp);let a={};for(let t of e)t.scope!==`header`&&(a[t.scope]=t.content);let o={header:r,state:a,operations:{},initialState:a,clipboard:[]};f.push(o)}return f}async getByIdOrSlug(e,t,n,r){let i=await this.resolveIdOrSlug(e,t,n,r);return this.get(i,t,void 0,r)}async findByType(e,t,n,r,i){if(r&&await this.waitForConsistency(r,void 0,i),i?.aborted)throw Error(`Operation aborted`);let a=t?.branch||`main`,o=n?.cursor?parseInt(n.cursor):0,s=n?.limit||100,c=[],l=new Set,u=[],d=await this._db.selectFrom(`DocumentSnapshot`).selectAll().where(`documentType`,`=`,e).where(`branch`,`=`,a).where(`isDeleted`,`=`,!1).orderBy(`lastUpdatedAt`,`desc`).execute();if(i?.aborted)throw Error(`Operation aborted`);for(let e of d)l.has(e.documentId)||(l.add(e.documentId),u.push(e.documentId));let f=u.slice(o,o+s);for(let e of f){if(i?.aborted)throw Error(`Operation aborted`);try{let n=await this.get(e,t,void 0,i);c.push(n)}catch{continue}}let p=u.length>o+s,m=p?String(o+s):void 0;return{results:c,options:n||{cursor:`0`,limit:100},nextCursor:m,totalCount:u.length,next:p?()=>this.findByType(e,t,{cursor:m,limit:s},r,i):void 0}}async resolveSlug(e,t,n,r){if(n&&await this.waitForConsistency(n,void 0,r),r?.aborted)throw Error(`Operation aborted`);let i=t?.branch||`main`,a=await this._db.selectFrom(`SlugMapping`).select(`documentId`).where(`slug`,`=`,e).where(`branch`,`=`,i).executeTakeFirst();if(a){if(r?.aborted)throw Error(`Operation aborted`);if(!(t?.scopes&&t.scopes.length>0&&!await this._db.selectFrom(`DocumentSnapshot`).select(`scope`).where(`documentId`,`=`,a.documentId).where(`branch`,`=`,i).where(`scope`,`in`,t.scopes).where(`isDeleted`,`=`,!1).executeTakeFirst()))return a.documentId}}async resolveSlugs(e,t,n,r){return(await Promise.all(e.map(e=>this.resolveSlug(e,t,n,r)))).filter(e=>e!==void 0)}async resolveIdOrSlug(e,t,n,r){if(n&&await this.waitForConsistency(n,void 0,r),r?.aborted)throw Error(`Operation aborted`);let i=t?.branch||`main`,a=this._db.selectFrom(`DocumentSnapshot`).select(`documentId`).where(`documentId`,`=`,e).where(`branch`,`=`,i).where(`isDeleted`,`=`,!1).executeTakeFirst(),o=this._db.selectFrom(`SlugMapping`).select(`documentId`).where(`slug`,`=`,e).where(`branch`,`=`,i).executeTakeFirst(),[s,c]=await Promise.all([a,o]);if(r?.aborted)throw Error(`Operation aborted`);let l=s?.documentId,u=c?.documentId;if(l&&u&&l!==u)throw Error(`Ambiguous identifier "${e}": matches both document ID "${l}" and slug for document ID "${u}". Please use get() for ID or resolveSlug() + get() for slug to be explicit.`);let d=l||u;if(!d)throw Error(`Document not found: ${e}`);return d}};function yn(e,t,n){return`${e}:${t}:${n}`}var bn=class{state=new Map;waiters=[];update(e){let t=this.deduplicateCoordinates(e);for(let e=0;e<t.length;e++){let n=t[e],r=yn(n.documentId,n.scope,n.branch),i=this.state.get(r);(i===void 0||n.operationIndex>i)&&this.state.set(r,n.operationIndex)}this.checkWaiters()}getLatest(e){return this.state.get(e)}waitFor(e,t,n){return n?.aborted?Promise.reject(Error(`Operation aborted`)):this.areCoordinatesSatisfied(e)?Promise.resolve():new Promise((r,i)=>{let a={coordinates:e,resolve:r,reject:i,signal:n};t!==void 0&&(a.timeoutId=setTimeout(()=>{this.removeWaiter(a),i(Error(`Consistency wait timed out after ${t}ms`))},t)),n&&n.addEventListener(`abort`,()=>{this.removeWaiter(a),i(Error(`Operation aborted`))},{once:!0}),this.waiters.push(a)})}serialize(){return Array.from(this.state.entries())}hydrate(e){this.state.clear();for(let[t,n]of e)this.state.set(t,n)}deduplicateCoordinates(e){let t=new Map;for(let n=0;n<e.length;n++){let r=e[n],i=yn(r.documentId,r.scope,r.branch),a=t.get(i);(!a||r.operationIndex>a.operationIndex)&&t.set(i,r)}return Array.from(t.values())}areCoordinatesSatisfied(e){for(let t=0;t<e.length;t++){let n=e[t],r=yn(n.documentId,n.scope,n.branch),i=this.state.get(r);if(i===void 0||i<n.operationIndex)return!1}return!0}checkWaiters(){let e=[],t=[];for(let n of this.waiters)n.signal?.aborted||(this.areCoordinatesSatisfied(n.coordinates)?e.push(n):t.push(n));this.waiters=t;for(let t of e)t.timeoutId!==void 0&&clearTimeout(t.timeoutId),t.resolve()}removeWaiter(e){let t=this.waiters.indexOf(e);t!==-1&&this.waiters.splice(t,1),e.timeoutId!==void 0&&clearTimeout(e.timeoutId)}};async function xn(e,t){let n=[...e.results],r=e;for(;r.next;){if(t?.aborted)throw Error(`Operation aborted`);r=await r.next(),n.push(...r.results)}return n}var Sn=class extends gn{_db;constructor(e,t,n,r){super(e,t,n,r,{readModelId:`document-indexer`,rebuildStateOnInit:!1}),this._db=e}async commitOperations(e){await this._db.transaction().execute(async t=>{for(let n of e){let{operation:e}=n,r=e.action.type;r===`ADD_RELATIONSHIP`?await this.handleAddRelationship(t,e):r===`REMOVE_RELATIONSHIP`?await this.handleRemoveRelationship(t,e):r===`UPDATE_RELATIONSHIP`&&await this.handleUpdateRelationship(t,e)}})}async getOutgoing(e,t,n,r,i){if(r&&await this.waitForConsistency(r,void 0,i),i?.aborted)throw Error(`Operation aborted`);let a=n?.cursor?parseInt(n.cursor):0,o=n?.limit||100,s=this._db.selectFrom(`DocumentRelationship`).selectAll().where(`sourceId`,`=`,e);t&&t.length>0&&(s=s.where(`relationshipType`,`in`,t));let c=await s.orderBy(`createdAt`,`asc`).orderBy(`id`,`asc`).offset(a).limit(o+1).execute(),l=c.length>o,u=l?c.slice(0,o):c,d=l?String(a+o):void 0;return{results:u.map(e=>({sourceId:e.sourceId,targetId:e.targetId,relationshipType:e.relationshipType,metadata:e.metadata?e.metadata:void 0,createdAt:e.createdAt,updatedAt:e.updatedAt})),options:n||{cursor:`0`,limit:100},nextCursor:d,next:l?()=>this.getOutgoing(e,t,{cursor:d,limit:o},r,i):void 0}}async getIncoming(e,t,n,r,i){if(r&&await this.waitForConsistency(r,void 0,i),i?.aborted)throw Error(`Operation aborted`);let a=n?.cursor?parseInt(n.cursor):0,o=n?.limit||100,s=this._db.selectFrom(`DocumentRelationship`).selectAll().where(`targetId`,`=`,e);t&&t.length>0&&(s=s.where(`relationshipType`,`in`,t));let c=await s.orderBy(`createdAt`,`asc`).orderBy(`id`,`asc`).offset(a).limit(o+1).execute(),l=c.length>o,u=l?c.slice(0,o):c,d=l?String(a+o):void 0;return{results:u.map(e=>({sourceId:e.sourceId,targetId:e.targetId,relationshipType:e.relationshipType,metadata:e.metadata?e.metadata:void 0,createdAt:e.createdAt,updatedAt:e.updatedAt})),options:n||{cursor:`0`,limit:100},nextCursor:d,next:l?()=>this.getIncoming(e,t,{cursor:d,limit:o},r,i):void 0}}async getOrphanedChildren(e,t,n){if(e.length===0)return[];if(n?.aborted)throw Error(`Operation aborted`);let r=this._db.selectFrom(`DocumentRelationship as r`).select(`r.targetId`).distinct().where(`r.sourceId`,`in`,e).where(t=>t.not(t.exists(t.selectFrom(`DocumentRelationship as other`).select(`other.id`).whereRef(`other.targetId`,`=`,`r.targetId`).where(`other.sourceId`,`not in`,e))));return t&&t.length>0&&(r=r.where(`r.relationshipType`,`in`,t)),(await r.execute()).map(e=>e.targetId)}async hasRelationship(e,t,n,r,i){if(r&&await this.waitForConsistency(r,void 0,i),i?.aborted)throw Error(`Operation aborted`);let a=this._db.selectFrom(`DocumentRelationship`).select(`id`).where(`sourceId`,`=`,e).where(`targetId`,`=`,t);return n&&n.length>0&&(a=a.where(`relationshipType`,`in`,n)),await a.executeTakeFirst()!==void 0}async getUndirectedRelationships(e,t,n,r,i,a){if(i&&await this.waitForConsistency(i,void 0,a),a?.aborted)throw Error(`Operation aborted`);let o=r?.cursor?parseInt(r.cursor):0,s=r?.limit||100,c=this._db.selectFrom(`DocumentRelationship`).selectAll().where(n=>n.or([n.and([n(`sourceId`,`=`,e),n(`targetId`,`=`,t)]),n.and([n(`sourceId`,`=`,t),n(`targetId`,`=`,e)])]));n&&n.length>0&&(c=c.where(`relationshipType`,`in`,n));let l=await c.orderBy(`createdAt`,`asc`).orderBy(`id`,`asc`).offset(o).limit(s+1).execute(),u=l.length>s,d=u?l.slice(0,s):l,f=u?String(o+s):void 0;return{results:d.map(e=>({sourceId:e.sourceId,targetId:e.targetId,relationshipType:e.relationshipType,metadata:e.metadata?e.metadata:void 0,createdAt:e.createdAt,updatedAt:e.updatedAt})),options:r||{cursor:`0`,limit:100},nextCursor:f,next:u?()=>this.getUndirectedRelationships(e,t,n,{cursor:f,limit:s},i,a):void 0}}async getDirectedRelationships(e,t,n,r,i,a){if(i&&await this.waitForConsistency(i,void 0,a),a?.aborted)throw Error(`Operation aborted`);let o=r?.cursor?parseInt(r.cursor):0,s=r?.limit||100,c=this._db.selectFrom(`DocumentRelationship`).selectAll().where(`sourceId`,`=`,e).where(`targetId`,`=`,t);n&&n.length>0&&(c=c.where(`relationshipType`,`in`,n));let l=await c.orderBy(`createdAt`,`asc`).orderBy(`id`,`asc`).offset(o).limit(s+1).execute(),u=l.length>s,d=u?l.slice(0,s):l,f=u?String(o+s):void 0;return{results:d.map(e=>({sourceId:e.sourceId,targetId:e.targetId,relationshipType:e.relationshipType,metadata:e.metadata?e.metadata:void 0,createdAt:e.createdAt,updatedAt:e.updatedAt})),options:r||{cursor:`0`,limit:100},nextCursor:f,next:u?()=>this.getDirectedRelationships(e,t,n,{cursor:f,limit:s},i,a):void 0}}async findPath(e,t,n,r,i){if(r&&await this.waitForConsistency(r,void 0,i),i?.aborted)throw Error(`Operation aborted`);if(e===t)return[e];let a=new Set,o=[{id:e,path:[e]}];for(;o.length>0;){let e=o.shift();if(e.id===t)return e.path;if(a.has(e.id))continue;a.add(e.id);let s=await xn(await this.getOutgoing(e.id,n,void 0,r,i),i);for(let t of s)a.has(t.targetId)||o.push({id:t.targetId,path:[...e.path,t.targetId]})}return null}async findAncestors(e,t,n,r){if(n&&await this.waitForConsistency(n,void 0,r),r?.aborted)throw Error(`Operation aborted`);let i=new Set([e]),a=[],o=[e],s=new Set;for(;o.length>0;){let e=o.shift();if(s.has(e))continue;s.add(e);let c=await xn(await this.getIncoming(e,t,void 0,n,r),r);for(let e of c)i.add(e.sourceId),a.push({from:e.sourceId,to:e.targetId,type:e.relationshipType}),s.has(e.sourceId)||o.push(e.sourceId)}return{nodes:Array.from(i),edges:a}}async getRelationshipTypes(e,t){if(e&&await this.waitForConsistency(e,void 0,t),t?.aborted)throw Error(`Operation aborted`);return(await this._db.selectFrom(`DocumentRelationship`).select(`relationshipType`).distinct().execute()).map(e=>e.relationshipType)}async handleAddRelationship(e,t){let n=t.action.input;if(await e.selectFrom(`Document`).select(`id`).where(`id`,`=`,n.sourceId).executeTakeFirst()||await e.insertInto(`Document`).values({id:n.sourceId}).execute(),await e.selectFrom(`Document`).select(`id`).where(`id`,`=`,n.targetId).executeTakeFirst()||await e.insertInto(`Document`).values({id:n.targetId}).execute(),!await e.selectFrom(`DocumentRelationship`).select(`id`).where(`sourceId`,`=`,n.sourceId).where(`targetId`,`=`,n.targetId).where(`relationshipType`,`=`,n.relationshipType).executeTakeFirst()){let t={id:ke(),sourceId:n.sourceId,targetId:n.targetId,relationshipType:n.relationshipType,metadata:n.metadata||null};await e.insertInto(`DocumentRelationship`).values(t).execute()}}async handleRemoveRelationship(e,t){let n=t.action.input;await e.deleteFrom(`DocumentRelationship`).where(`sourceId`,`=`,n.sourceId).where(`targetId`,`=`,n.targetId).where(`relationshipType`,`=`,n.relationshipType).execute()}async handleUpdateRelationship(e,t){let n=t.action.input;await e.updateTable(`DocumentRelationship`).set({metadata:n.metadata,updatedAt:new Date}).where(`sourceId`,`=`,n.sourceId).where(`targetId`,`=`,n.targetId).where(`relationshipType`,`=`,n.relationshipType).execute()}},Cn=Object.defineProperty,wn=(e,t)=>{let n={};for(var r in e)Cn(n,r,{get:e[r],enumerable:!0});return t||Cn(n,Symbol.toStringTag,{value:`Module`}),n},Tn=`phdd`,En=e=>e!=null;f().refine(e=>En(e));var Dn=_([`Internal`,`MatrixConnect`,`PullResponder`,`RESTWebhook`,`SecureConnect`,`SwitchboardPush`]),On=_([`PullResponder`]);function kn(){return T({documentType:C(),id:C(),name:C(),parentFolder:C().nullish()})}function An(){return T({id:C(),name:C(),parentFolder:C().nullish()})}function jn(){return T({listener:Bn()})}function Mn(){return T({trigger:nr()})}function Nn(){return T({srcId:C(),targetId:C(),targetName:C().nullish(),targetParentFolder:C().nullish()})}function Pn(){return T({id:C()})}function Fn(){return T({__typename:ie(`DocumentDriveLocalState`).optional(),availableOffline:x(),listeners:i(zn()),sharingType:C().nullable(),triggers:i(tr())})}function In(){return T({__typename:ie(`DocumentDriveState`).optional(),icon:C().nullable(),name:C(),nodes:i(Kn())})}function Ln(){return T({__typename:ie(`FileNode`).optional(),documentType:C(),id:C(),kind:C(),name:C(),parentFolder:C().nullable()})}function Rn(){return T({__typename:ie(`FolderNode`).optional(),id:C(),kind:C(),name:C(),parentFolder:C().nullable()})}function zn(){return T({__typename:ie(`Listener`).optional(),block:x(),callInfo:Vn().nullable(),filter:Un(),label:C().nullable(),listenerId:C(),system:x()})}function Bn(){return T({block:x(),callInfo:Hn().nullish(),filter:Wn(),label:C().nullish(),listenerId:C(),system:x()})}function Vn(){return T({__typename:ie(`ListenerCallInfo`).optional(),data:C().nullable(),name:C().nullable(),transmitterType:Dn.nullable()})}function Hn(){return T({data:C().nullish(),name:C().nullish(),transmitterType:Dn.nullish()})}function Un(){return T({__typename:ie(`ListenerFilter`).optional(),branch:i(C()).nullable(),documentId:i(C()).nullable(),documentType:i(C()),scope:i(C()).nullable()})}function Wn(){return T({branch:i(C()).nullish(),documentId:i(C()).nullish(),documentType:i(C()).nullish(),scope:i(C()).nullish()})}function Gn(){return T({srcFolder:C(),targetParentFolder:C().nullish()})}function Kn(){return y([Ln(),Rn()])}function qn(){return T({__typename:ie(`PullResponderTriggerData`).optional(),interval:C(),listenerId:C(),url:C()})}function Jn(){return T({interval:C(),listenerId:C(),url:C()})}function Yn(){return T({listenerId:C()})}function Xn(){return T({triggerId:C()})}function Zn(){return T({availableOffline:x()})}function Qn(){return T({icon:C()})}function $n(){return T({name:C()})}function er(){return T({type:C()})}function tr(){return T({__typename:ie(`Trigger`).optional(),data:rr().nullable(),id:C(),type:On})}function nr(){return T({data:Jn().nullish(),id:C(),type:On})}function rr(){return qn()}function ir(){return T({documentType:C().nullish(),id:C(),name:C().nullish(),parentFolder:C().nullish()})}function ar(){return T({id:C(),name:C().nullish(),parentFolder:C().nullish()})}function or(e){return e&&typeof e==`object`&&`synchronizationUnits`in e?v(`ADD_FILE`,{...e},void 0,void 0,`global`):v(`ADD_FILE`,{...e},void 0,kn,`global`)}var sr=e=>v(`ADD_FOLDER`,{...e},void 0,An,`global`),cr=e=>v(`DELETE_NODE`,{...e},void 0,Pn,`global`),lr=e=>v(`UPDATE_FILE`,{...e},void 0,ir,`global`),ur=e=>v(`UPDATE_NODE`,{...e},void 0,ar,`global`),dr=e=>v(`COPY_NODE`,{...e},void 0,Nn,`global`),fr=e=>v(`MOVE_NODE`,{...e},void 0,Gn,`global`),pr=e=>v(`SET_DRIVE_NAME`,{...e},void 0,$n,`global`),mr=e=>v(`SET_DRIVE_ICON`,{...e},void 0,Qn,`global`),hr=e=>v(`SET_SHARING_TYPE`,{...e},void 0,er,`local`),gr=e=>v(`SET_AVAILABLE_OFFLINE`,{...e},void 0,Zn,`local`),_r=e=>v(`ADD_LISTENER`,{...e},void 0,jn,`local`),vr=e=>v(`REMOVE_LISTENER`,{...e},void 0,Yn,`local`),yr=e=>v(`ADD_TRIGGER`,{...e},void 0,Mn,`local`),br=e=>v(`REMOVE_TRIGGER`,{...e},void 0,Xn,`local`),xr=wn({addFile:()=>or,addFolder:()=>sr,addListener:()=>_r,addTrigger:()=>yr,copyNode:()=>dr,deleteNode:()=>cr,moveNode:()=>fr,removeListener:()=>vr,removeTrigger:()=>br,setAvailableOffline:()=>gr,setDriveIcon:()=>mr,setDriveName:()=>pr,setSharingType:()=>hr,updateFile:()=>lr,updateNode:()=>ur}),Sr={id:`powerhouse/document-drive`,name:`DocumentDrive`,extension:`phdd`,description:``,author:{name:`Powerhouse Inc`,website:`https://www.powerhouse.inc/`},specifications:[{version:1,changeLog:[],state:{global:{schema:`type FolderNode {
|
|
3
3
|
id: String!
|
|
4
4
|
name: String!
|
|
@@ -232,7 +232,7 @@ input AddTriggerInput {
|
|
|
232
232
|
mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {
|
|
233
233
|
pushSyncEnvelopes(envelopes: $envelopes)
|
|
234
234
|
}
|
|
235
|
-
`,r)}async getAuthorizationHeader(){if(this.config.jwtHandler)try{let 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,t){let n={"Content-Type":`application/json`},r=await this.getAuthorizationHeader();r&&(n.Authorization=r);let i=e.match(/(?:query|mutation)\s+(\w+)/)?.[1]??`unknown`;this.logger.verbose(`GQL request @channelId @operation @url vars=@variables`,this.channelId,i,this.config.url,JSON.stringify(t));let a=this.config.fetchFn??fetch,o;try{o=await a(this.config.url,{method:`POST`,headers:n,body:JSON.stringify({query:e,variables:t}),signal:this.abortController.signal})}catch(e){throw new xa(`GraphQL request failed: ${e instanceof Error?e.message:String(e)}`,`network`)}if(!o.ok)throw new xa(`GraphQL request failed: ${o.status} ${o.statusText}`,`http`,o.status);let s;try{s=await o.json()}catch(e){throw new xa(`Failed to parse GraphQL response: ${e instanceof Error?e.message:String(e)}`,`parse`)}if(this.logger.verbose(`GQL response @channelId @operation status=@status data=@data errors=@errors`,this.channelId,i,o.status,JSON.stringify(s.data),s.errors?JSON.stringify(s.errors):`none`),s.errors)throw new xa(`GraphQL errors: ${JSON.stringify(s.errors,null,2)}`,`graphql`);if(!s.data)throw new xa(`GraphQL response missing data field`,`missing-data`);return s.data}get poller(){return this.pollTimer}},Ka=class{logger;jwtHandler;queue;constructor(e,t,n){this.logger=e,this.jwtHandler=t,this.queue=n}instance(e,t,n,r,i,a,o,s){let c=n.parameters.url;if(typeof c!=`string`||!c)throw Error(`GqlRequestChannelFactory requires "url" parameter in config.parameters`);let l={url:c,collectionId:i,filter:a,jwtHandler:this.jwtHandler,retryBaseDelayMs:1e3,retryMaxDelayMs:3e5},u=2e3;if(n.parameters.pollIntervalMs!==void 0){if(typeof n.parameters.pollIntervalMs!=`number`)throw Error(`"pollIntervalMs" parameter must be a number`);u=n.parameters.pollIntervalMs}let d;if(n.parameters.retryBaseDelayMs!==void 0){if(typeof n.parameters.retryBaseDelayMs!=`number`)throw Error(`"retryBaseDelayMs" parameter must be a number`);d=n.parameters.retryBaseDelayMs}let f;if(n.parameters.retryMaxDelayMs!==void 0){if(typeof n.parameters.retryMaxDelayMs!=`number`)throw Error(`"retryMaxDelayMs" parameter must be a number`);f=n.parameters.retryMaxDelayMs}if(n.parameters.fetchFn!==void 0){if(typeof n.parameters.fetchFn!=`function`)throw Error(`"fetchFn" parameter must be a function`);l.fetchFn=n.parameters.fetchFn}d!==void 0&&(l.retryBaseDelayMs=d),f!==void 0&&(l.retryMaxDelayMs=f);let p;if(n.parameters.maxQueueDepth!==void 0){if(typeof n.parameters.maxQueueDepth!=`number`)throw Error(`"maxQueueDepth" parameter must be a number`);p=n.parameters.maxQueueDepth}let m;if(n.parameters.backpressureCheckIntervalMs!==void 0){if(typeof n.parameters.backpressureCheckIntervalMs!=`number`)throw Error(`"backpressureCheckIntervalMs" parameter must be a number`);m=n.parameters.backpressureCheckIntervalMs}let h=new La(this.queue,{intervalMs:u,...d!==void 0&&{retryBaseDelayMs:d},...f!==void 0&&{retryMaxDelayMs:f},...p!==void 0&&{maxQueueDepth:p},...m!==void 0&&{backpressureCheckIntervalMs:m},startPaused:s?.pollBehavior===ma.Manual});return new Ga(this.logger,e,t,r,l,o,h)}},qa=class{inbox;outbox;deadLetter;channelId;remoteName;cursorStorage;isShutdown;lastPersistedInboxOrdinal=0;lastPersistedOutboxOrdinal=0;connectionState=`connecting`;connectionStateCallbacks=new Set;constructor(e,t,n,r){this.logger=e,this.channelId=t,this.remoteName=n,this.cursorStorage=r,this.isShutdown=!1,this.inbox=new ya,this.outbox=new ya,this.deadLetter=new ya,this.outbox.onRemoved(e=>{let t=Wa(e);t>this.lastPersistedOutboxOrdinal&&(this.lastPersistedOutboxOrdinal=t,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:`outbox`,cursorOrdinal:t,lastSyncedAtUtcMs:Date.now()}).catch(e=>{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,e)}))}),this.inbox.onRemoved(e=>{let t=Wa(e);t>this.lastPersistedInboxOrdinal&&(this.lastPersistedInboxOrdinal=t,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:`inbox`,cursorOrdinal:t,lastSyncedAtUtcMs:Date.now()}).catch(e=>{this.logger.error(`Failed to update inbox cursor for @ChannelId! This is unlikely to cause a problem, but not-optimal: @Error`,this.channelId,e)}))})}shutdown(){return this.isShutdown=!0,this.transitionConnectionState(`disconnected`),Promise.resolve()}getConnectionState(){return{state:this.connectionState,failureCount:0,lastSuccessUtcMs:0,lastFailureUtcMs:0,pushBlocked:!1,pushFailureCount:0,receivingPages:!1}}onConnectionStateChange(e){return this.connectionStateCallbacks.add(e),()=>{this.connectionStateCallbacks.delete(e)}}triggerPull(){}transitionConnectionState(e){if(this.connectionState===e)return;this.connectionState=e;let t=this.getConnectionState();for(let e of this.connectionStateCallbacks)try{e(t)}catch(e){this.logger.error(`Connection state change callback error: @Error`,e)}}async init(){let e=await this.cursorStorage.list(this.remoteName),t=e.find(e=>e.cursorType===`inbox`)?.cursorOrdinal??0,n=e.find(e=>e.cursorType===`outbox`)?.cursorOrdinal??0;this.inbox.init(t),this.outbox.init(n),this.lastPersistedInboxOrdinal=t,this.lastPersistedOutboxOrdinal=n,this.transitionConnectionState(`connected`)}},Ja=class{logger;constructor(e){this.logger=e}instance(e,t,n,r){return new qa(this.logger,e,t,r)}};function Ya(e){return{remoteName:e.remote_name,cursorType:e.cursor_type,cursorOrdinal:Number(e.cursor_ordinal),lastSyncedAtUtcMs:e.last_synced_at_utc_ms?new Date(e.last_synced_at_utc_ms).getTime():void 0}}function Xa(e){return{remote_name:e.remoteName,cursor_type:e.cursorType,cursor_ordinal:BigInt(e.cursorOrdinal),last_synced_at_utc_ms:e.lastSyncedAtUtcMs?new Date(e.lastSyncedAtUtcMs).toISOString():null}}var Za=class{constructor(e){this.db=e}async list(e,t){if(t?.aborted)throw Error(`Operation aborted`);let n=await this.db.selectFrom(`sync_cursors`).selectAll().where(`remote_name`,`=`,e).execute();if(t?.aborted)throw Error(`Operation aborted`);return n.map(Ya)}async get(e,t,n){if(n?.aborted)throw Error(`Operation aborted`);let r=await this.db.selectFrom(`sync_cursors`).selectAll().where(`remote_name`,`=`,e).where(`cursor_type`,`=`,t).executeTakeFirst();if(n?.aborted)throw Error(`Operation aborted`);return r?Ya(r):{remoteName:e,cursorType:t,cursorOrdinal:0}}async upsert(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{let n=Xa(e);await t.insertInto(`sync_cursors`).values(n).onConflict(e=>e.columns([`remote_name`,`cursor_type`]).doUpdateSet({...n,updated_at:Ve`NOW()`})).execute()}),t?.aborted))throw Error(`Operation aborted`)}async remove(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_cursors`).where(`remote_name`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}};function Qa(e){return{id:e.id,jobId:e.job_id,jobDependencies:e.job_dependencies,remoteName:e.remote_name,documentId:e.document_id,scopes:e.scopes,branch:e.branch,operations:e.operations,errorSource:e.error_source,errorMessage:e.error_message}}function $a(e){return{id:e.id,job_id:e.jobId,job_dependencies:JSON.stringify(e.jobDependencies),remote_name:e.remoteName,document_id:e.documentId,scopes:JSON.stringify(e.scopes),branch:e.branch,operations:JSON.stringify(e.operations),error_source:e.errorSource,error_message:e.errorMessage}}var eo=class{constructor(e){this.db=e}async list(e,t,n){if(n?.aborted)throw Error(`Operation aborted`);let r=t?.cursor?parseInt(t.cursor):0,i=t?.limit||100,a=await this.db.selectFrom(`sync_dead_letters`).selectAll().where(`remote_name`,`=`,e).orderBy(`ordinal`,`desc`).offset(r).limit(i+1).execute(),o=!1,s=a;t?.limit&&a.length>i&&(o=!0,s=a.slice(0,i));let c=o?String(r+i):void 0,l=t?.cursor||`0`;if(n?.aborted)throw Error(`Operation aborted`);return{results:s.map(Qa),options:{cursor:l,limit:i},nextCursor:c}}async add(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{let n=$a(e);await t.insertInto(`sync_dead_letters`).values(n).onConflict(e=>e.column(`id`).doNothing()).execute()}),t?.aborted))throw Error(`Operation aborted`)}async remove(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_dead_letters`).where(`id`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}async removeByRemote(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_dead_letters`).where(`remote_name`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}async listQuarantinedDocumentIds(e){if(e?.aborted)throw Error(`Operation aborted`);let t=await this.db.selectFrom(`sync_dead_letters`).select(`document_id`).distinct().execute();if(e?.aborted)throw Error(`Operation aborted`);return t.map(e=>e.document_id)}};function to(e){return{id:e.channel_id,name:e.name,collectionId:Ae.fromKey(e.collection_id),channelConfig:{type:e.channel_type,parameters:e.channel_parameters??{}},filter:{documentId:e.filter_document_ids??[],scope:e.filter_scopes??[],branch:e.filter_branch},options:{sinceTimestampUtcMs:`0`},status:{push:{state:e.push_state,lastSuccessUtcMs:e.push_last_success_utc_ms?new Date(e.push_last_success_utc_ms).getTime():void 0,lastFailureUtcMs:e.push_last_failure_utc_ms?new Date(e.push_last_failure_utc_ms).getTime():void 0,failureCount:e.push_failure_count},pull:{state:e.pull_state,lastSuccessUtcMs:e.pull_last_success_utc_ms?new Date(e.pull_last_success_utc_ms).getTime():void 0,lastFailureUtcMs:e.pull_last_failure_utc_ms?new Date(e.pull_last_failure_utc_ms).getTime():void 0,failureCount:e.pull_failure_count}}}}function no(e){return{name:e.name,collection_id:e.collectionId.key,channel_type:e.channelConfig.type,channel_id:e.id,remote_name:e.name,channel_parameters:e.channelConfig.parameters,filter_document_ids:e.filter.documentId.length>0?e.filter.documentId:null,filter_scopes:e.filter.scope.length>0?e.filter.scope:null,filter_branch:e.filter.branch,push_state:e.status.push.state,push_last_success_utc_ms:e.status.push.lastSuccessUtcMs?new Date(e.status.push.lastSuccessUtcMs).toISOString():null,push_last_failure_utc_ms:e.status.push.lastFailureUtcMs?new Date(e.status.push.lastFailureUtcMs).toISOString():null,push_failure_count:e.status.push.failureCount,pull_state:e.status.pull.state,pull_last_success_utc_ms:e.status.pull.lastSuccessUtcMs?new Date(e.status.pull.lastSuccessUtcMs).toISOString():null,pull_last_failure_utc_ms:e.status.pull.lastFailureUtcMs?new Date(e.status.pull.lastFailureUtcMs).toISOString():null,pull_failure_count:e.status.pull.failureCount}}var ro=class{constructor(e){this.db=e}async list(e){if(e?.aborted)throw Error(`Operation aborted`);let t=await this.db.selectFrom(`sync_remotes`).selectAll().execute();if(e?.aborted)throw Error(`Operation aborted`);return t.map(to)}async get(e,t){if(t?.aborted)throw Error(`Operation aborted`);let n=await this.db.selectFrom(`sync_remotes`).selectAll().where(`name`,`=`,e).executeTakeFirst();if(t?.aborted)throw Error(`Operation aborted`);if(!n)throw Error(`Remote not found: ${e}`);return to(n)}async upsert(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{let n=no(e);await t.insertInto(`sync_remotes`).values(n).onConflict(e=>e.column(`name`).doUpdateSet({...n,updated_at:Ve`NOW()`})).execute()}),t?.aborted))throw Error(`Operation aborted`)}async remove(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_remotes`).where(`name`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}},io=class{logger;driveContainerTypes;onBatchReady;queue=[];processing=!1;pendingBatches=new Map;constructor(e,t,n){this.logger=e,this.driveContainerTypes=t,this.onBatchReady=n}async enqueueWriteReady(e){this.queue.push(e),await this.processQueue()}async handleJobFailed(e){let t=e.job?.meta.batchId;if(!t)return;let n=this.pendingBatches.get(t);n&&(this.pendingBatches.delete(t),n.events.length>0&&await this.onBatchReady(this.prepareBatch(n.events)))}clear(){this.queue=[],this.pendingBatches.clear()}async processQueue(){if(!this.processing){this.processing=!0;try{for(;this.queue.length>0;){let e=this.queue.shift();try{await this.handleWriteReady(e)}catch(t){let n=t instanceof Error?t:Error(String(t));this.logger.error(`Failed to process write-ready event (@jobId, @error)`,e.jobId,n.message)}}}finally{this.processing=!1}}}async handleWriteReady(e){let{batchId:t,batchJobIds:n}=e.jobMeta;if(n.length<=1){await this.onBatchReady(this.prepareBatch([e]));return}let r=this.pendingBatches.get(t);r||(r={expectedJobIds:new Set(n),arrivedJobIds:new Set,events:[]},this.pendingBatches.set(t,r)),r.arrivedJobIds.add(e.jobId),r.events.push(e),r.arrivedJobIds.size>=r.expectedJobIds.size&&(this.pendingBatches.delete(t),await this.onBatchReady(this.prepareBatch(r.events)))}prepareBatch(e){let t=this.mergeCollectionMemberships(e),n=e.length>1,r=[],i=[];for(let t of e)i.push({event:t,jobDependencies:n?[...r]:[]}),n&&t.jobId&&r.push(t.jobId);return{collectionMemberships:t,entries:i}}mergeCollectionMemberships(e){let t={};for(let n of e){if(n.collectionMemberships)for(let[e,r]of Object.entries(n.collectionMemberships)){e in t||(t[e]=[]);for(let n of r)t[e].includes(n)||t[e].push(n)}for(let e of n.operations){let n=e.operation.action;if(n.type!==`ADD_RELATIONSHIP`||!this.driveContainerTypes.has(e.context.documentType))continue;let r=n.input;if(!r?.sourceId||!r.targetId)continue;let i=Ae.forDrive(r.sourceId,e.context.branch).key;r.targetId in t||(t[r.targetId]=[]),t[r.targetId].includes(i)||t[r.targetId].push(i)}}return t}},ao=class{completedResults=new Map;pendingWaiters=new Map;unsubscribers=[];isShutdown=!1;constructor(e){this.eventBus=e,this.subscribeToEvents()}waitForSync(e,t){if(t?.aborted)return Promise.reject(Error(`Operation aborted`));if(this.isShutdown)return Promise.reject(Error(`SyncAwaiter is shutdown`));let n=this.completedResults.get(e);return n?Promise.resolve(n):new Promise((n,r)=>{let i={resolve:n,reject:r,signal:t},a=this.pendingWaiters.get(e)||[];a.push(i),this.pendingWaiters.set(e,a),t&&t.addEventListener(`abort`,()=>{let t=this.pendingWaiters.get(e);if(t){let n=t.indexOf(i);n!==-1&&(t.splice(n,1),t.length===0&&this.pendingWaiters.delete(e),i.reject(Error(`Operation aborted`)))}},{once:!0})})}shutdown(){this.isShutdown=!0;for(let e of this.unsubscribers)e();this.unsubscribers.length=0;for(let[,e]of this.pendingWaiters)for(let t of e)t.reject(Error(`SyncAwaiter shutdown`));this.pendingWaiters.clear()}subscribeToEvents(){this.unsubscribers.push(this.eventBus.subscribe(_a.SYNC_SUCCEEDED,(e,t)=>{this.handleSyncSucceeded(t)})),this.unsubscribers.push(this.eventBus.subscribe(_a.SYNC_FAILED,(e,t)=>{this.handleSyncFailed(t)}))}handleSyncSucceeded(e){let t={jobId:e.jobId,status:`succeeded`,syncOperationCount:e.syncOperationCount,successCount:e.syncOperationCount,failureCount:0,errors:[]};this.completedResults.set(e.jobId,t),this.resolveWaiters(e.jobId,t)}handleSyncFailed(e){let t={jobId:e.jobId,status:`failed`,syncOperationCount:e.successCount+e.failureCount,successCount:e.successCount,failureCount:e.failureCount,errors:e.errors};this.completedResults.set(e.jobId,t),this.resolveWaiters(e.jobId,t)}resolveWaiters(e,t){let n=this.pendingWaiters.get(e);if(!(!n||n.length===0)){this.pendingWaiters.delete(e);for(let e of n)e.signal?.aborted?e.reject(Error(`Operation aborted`)):e.resolve(t)}}},oo=function(e){return e.Synced=`SYNCED`,e.Outgoing=`OUTGOING`,e.Incoming=`INCOMING`,e.OutgoingAndIncoming=`OUTGOING_AND_INCOMING`,e.Error=`ERROR`,e}({}),so=class{remotes=new Map;seen=new Set;callbacks=new Set;getStatus(e){if(!this.seen.has(e))return;let t=0,n=0,r=0;for(let i of this.remotes.values()){let a=i.get(e);a&&(t+=a.inboxCount,n+=a.outboxCount,r+=a.errorCount)}return co(t,n,r)}onChange(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e)}}trackRemote(e,t){this.remotes.set(e,new Map),t.inbox.onAdded(t=>this.handleAdded(e,`inbox`,t)),t.inbox.onRemoved(t=>this.handleRemoved(e,`inbox`,t)),t.outbox.onAdded(t=>this.handleAdded(e,`outbox`,t)),t.outbox.onRemoved(t=>this.handleRemoved(e,`outbox`,t)),t.deadLetter.onAdded(t=>this.handleAdded(e,`deadLetter`,t))}untrackRemote(e){let t=this.remotes.get(e);if(!t)return;let n=[...t.keys()];this.remotes.delete(e);for(let e of n)this.notifyChange(e)}clear(){this.remotes.clear(),this.seen.clear(),this.callbacks.clear()}handleAdded(e,t,n){let r=new Set;for(let i of n){if(t===`inbox`&&!i.remoteName)continue;let n=this.getOrCreateCounts(e,i.documentId);this.seen.add(i.documentId),t===`inbox`?n.inboxCount++:t===`outbox`?n.outboxCount++:n.errorCount++,r.add(i.documentId)}for(let e of r)this.notifyChange(e)}handleRemoved(e,t,n){let r=new Set;for(let i of n){let n=this.getOrCreateCounts(e,i.documentId);t===`inbox`?n.inboxCount=Math.max(0,n.inboxCount-1):t===`outbox`&&(n.outboxCount=Math.max(0,n.outboxCount-1)),r.add(i.documentId)}for(let e of r)this.notifyChange(e)}getOrCreateCounts(e,t){let n=this.remotes.get(e);n||(n=new Map,this.remotes.set(e,n));let r=n.get(t);return r||(r={inboxCount:0,outboxCount:0,errorCount:0},n.set(t,r)),r}notifyChange(e){let t=this.getStatus(e);if(t!==void 0)for(let n of[...this.callbacks])n(e,t)}};function co(e,t,n){return n>0?oo.Error:e>0&&t>0?oo.OutgoingAndIncoming:e>0?oo.Incoming:t>0?oo.Outgoing:oo.Synced}var lo=function(e){return e.Backfill=`backfill`,e.BatchTriggered=`batch-triggered`,e}(lo||{}),uo={maxDeadLettersPerRemote:100,maxInboxBatchSize:32},fo=1e4,po=class{logger;remoteStorage;cursorStorage;deadLetterStorage;channelFactory;operationIndex;reactor;eventBus;remotes;awaiter;syncAwaiter;abortController=new AbortController;isShutdown;eventUnsubscribe;failedEventUnsubscribe;batchAggregator;syncStatusTracker;config;connectionStateUnsubscribes=new Map;quarantinedDocumentIds=new Set;backfillAbortControllers=new Map;planKeyToJobUuid=new Map;lastEnqueuedJobIdByKey=new Map;inboxChunkChain=Promise.resolve();constructor(e,t,n,r,i,a,o,s,c,l={}){this.logger=e,this.remoteStorage=t,this.cursorStorage=n,this.deadLetterStorage=r,this.channelFactory=i,this.operationIndex=a,this.reactor=o,this.eventBus=s,this.config={...uo,...l},this.remotes=new Map,this.awaiter=new ji(s,(e,t)=>o.getJobStatus(e,t)),this.syncAwaiter=new ao(s),this.isShutdown=!1,this.batchAggregator=new io(e,c,e=>this.processCompleteBatch(e)),this.syncStatusTracker=new so}async startup(){if(this.isShutdown)throw Error(`SyncManager is already shutdown and cannot be started`);try{let e=await this.deadLetterStorage.listQuarantinedDocumentIds();for(let t of e)this.quarantinedDocumentIds.add(t)}catch(e){this.logger.error(`Failed to load quarantined document IDs (@error)`,e instanceof Error?e.message:String(e))}let e=await this.remoteStorage.list();for(let t of e){let e=this.channelFactory.instance(t.id,t.name,t.channelConfig,this.cursorStorage,t.collectionId,t.filter,this.operationIndex,t.options),n={id:t.id,name:t.name,collectionId:t.collectionId,filter:t.filter,options:t.options,channel:e};this.remotes.set(t.name,n),await this.loadDeadLetters(n),this.wireChannelCallbacks(n);try{await e.init()}catch(e){this.logger.error(`Error initializing channel for remote (@name, @error)`,t.name,e instanceof Error?e.message:String(e)),this.remotes.delete(t.name);continue}let r=n.channel.outbox.ackOrdinal;if(r>0){let e=new AbortController;this.backfillAbortControllers.set(t.name,e),this.updateOutbox(n,r,lo.Backfill,e.signal).catch(t=>{e.signal.aborted||this.logger.error(`Backfill failed for remote @RemoteName: @Error`,n.name,t instanceof Error?t:Error(String(t)))}).finally(()=>{this.backfillAbortControllers.delete(t.name)})}}this.eventUnsubscribe=this.eventBus.subscribe(w.JOB_WRITE_READY,async(e,t)=>this.batchAggregator.enqueueWriteReady(t)),this.failedEventUnsubscribe=this.eventBus.subscribe(w.JOB_FAILED,async(e,t)=>this.batchAggregator.handleJobFailed(t))}shutdown(){this.isShutdown=!0,this.abortController.abort();for(let e of this.backfillAbortControllers.values())e.abort();this.backfillAbortControllers.clear(),this.planKeyToJobUuid.clear(),this.lastEnqueuedJobIdByKey.clear(),this.batchAggregator.clear(),this.eventUnsubscribe&&=(this.eventUnsubscribe(),void 0),this.failedEventUnsubscribe&&=(this.failedEventUnsubscribe(),void 0),this.awaiter.shutdown(),this.syncAwaiter.shutdown(),this.syncStatusTracker.clear();for(let e of this.connectionStateUnsubscribes.values())e();this.connectionStateUnsubscribes.clear();let e=[];for(let t of this.remotes.values())e.push(t.channel.shutdown());return this.remotes.clear(),{isShutdown:!0,completed:Promise.all(e).then(()=>void 0)}}getByName(e){let t=this.remotes.get(e);if(!t)throw Error(`Remote with name '${e}' does not exist`);return t}getById(e){for(let t of this.remotes.values())if(t.id===e)return t;throw Error(`Remote with id '${e}' does not exist`)}async add(e,t,n,r={documentId:[],scope:[],branch:``},i={sinceTimestampUtcMs:`0`},a){if(this.isShutdown)throw Error(`SyncManager is shutdown and cannot add remotes`);if(this.remotes.has(e))throw Error(`Remote with name '${e}' already exists`);this.logger.debug(`Adding remote (@name, @collectionId, @channelConfig, @filter, @options, @id)`,e,t.key,n,r,i,a);let o=a??crypto.randomUUID(),s={id:o,name:e,collectionId:t,channelConfig:n,filter:r,options:i,status:{push:Oa(),pull:Oa()}};await this.remoteStorage.upsert(s);let c=this.channelFactory.instance(o,e,n,this.cursorStorage,t,r,this.operationIndex,i),l={id:o,name:e,collectionId:t,filter:r,options:i,channel:c};this.remotes.set(e,l),await this.loadDeadLetters(l),this.wireChannelCallbacks(l);try{await c.init()}catch(t){throw this.remotes.delete(e),await this.remoteStorage.remove(e),t}let u=new AbortController;return this.backfillAbortControllers.set(e,u),this.updateOutbox(l,0,lo.Backfill,u.signal).catch(e=>{u.signal.aborted||this.logger.error(`Backfill failed for remote @RemoteName: @Error`,l.name,e instanceof Error?e:Error(String(e)))}).finally(()=>{this.backfillAbortControllers.delete(e)}),l}triggerPull(e){let t=this.remotes.get(e);if(!t)throw Error(`Remote with name '${e}' does not exist`);t.channel.triggerPull()}async remove(e){let t=this.remotes.get(e);if(!t)throw Error(`Remote with name '${e}' does not exist`);let n=this.backfillAbortControllers.get(e);n&&(n.abort(),this.backfillAbortControllers.delete(e)),await t.channel.shutdown(),await this.remoteStorage.remove(e),await this.cursorStorage.remove(e),this.syncStatusTracker.untrackRemote(e);let r=this.connectionStateUnsubscribes.get(e);r&&(r(),this.connectionStateUnsubscribes.delete(e)),this.remotes.delete(e)}list(){return Array.from(this.remotes.values())}waitForSync(e,t){return this.syncAwaiter.waitForSync(e,t)}getSyncStatus(e){return this.syncStatusTracker.getStatus(e)}onSyncStatusChange(e){return this.syncStatusTracker.onChange(e)}recordPlanKeyMapping(e,t){if(!this.planKeyToJobUuid.has(e)&&this.planKeyToJobUuid.size>=fo){let e=this.planKeyToJobUuid.keys().next().value;e!==void 0&&this.planKeyToJobUuid.delete(e)}this.planKeyToJobUuid.set(e,t)}wireChannelCallbacks(e){e.channel.inbox.onAdded(t=>this.handleInboxAdded(e,t)),this.syncStatusTracker.trackRemote(e.name,e.channel);let t=e.channel.onConnectionStateChange(t=>{this.eventBus.emit(_a.CONNECTION_STATE_CHANGED,{remoteName:e.name,remoteId:e.id,previous:t.state,current:t.state,snapshot:t}).catch(()=>{})});this.connectionStateUnsubscribes.set(e.name,t),e.channel.deadLetter.onAdded(t=>{for(let n of t){this.logger.error(`Dead letter (@remote, @documentId, @jobId, @error, @dependencies)`,e.name,n.documentId,n.jobId,n.error?.message??`unknown`,n.jobDependencies),this.quarantinedDocumentIds.add(n.documentId);let t={id:n.id,jobId:n.jobId,jobDependencies:n.jobDependencies,remoteName:n.remoteName,documentId:n.documentId,scopes:n.scopes,branch:n.branch,operations:n.operations,errorSource:n.error?.source??ga.None,errorMessage:n.error?.error.message??`unknown`};this.deadLetterStorage.add(t).catch(e=>{this.logger.error(`Failed to persist dead letter (@id, @error)`,t.id,e instanceof Error?e.message:String(e))}),this.eventBus.emit(_a.DEAD_LETTER_ADDED,{id:t.id,jobId:t.jobId,remoteName:t.remoteName,documentId:t.documentId,errorSource:t.errorSource}).catch(()=>{})}let n=e.channel.deadLetter.items;if(n.length>this.config.maxDeadLettersPerRemote){let t=n.length-this.config.maxDeadLettersPerRemote,r=n.slice(0,t);e.channel.deadLetter.remove(...r)}})}async loadDeadLetters(e){let t;try{t=(await this.deadLetterStorage.list(e.name,{cursor:`0`,limit:this.config.maxDeadLettersPerRemote})).results}catch(t){this.logger.error(`Failed to load dead letters for remote (@name, @error)`,e.name,t instanceof Error?t.message:String(t));return}if(t.length===0)return;t.reverse();let n=[];for(let e of t){let t=new wa(e.id,e.jobId,e.jobDependencies,e.remoteName,e.documentId,e.scopes,e.branch,e.operations);t.failed(new Sa(e.errorSource,Error(e.errorMessage))),n.push(t)}e.channel.deadLetter.add(...n),this.logger.debug(`Loaded @count persisted dead letters for remote @name`,t.length,e.name)}getRemotesForCollection(e){return Array.from(this.remotes.values()).filter(t=>t.collectionId.key===e)}async processCompleteBatch(e){if(this.isShutdown)return;let t=[...new Set(Object.values(e.collectionMemberships).flatMap(e=>e))],n=[];for(let e of t){let t=this.getRemotesForCollection(e);for(let e of t)n.includes(e)||n.push(e)}for(let t of n)Ta(t.channel.inbox,e);for(let e of n)await this.updateOutbox(e,e.channel.outbox.latestOrdinal,lo.BatchTriggered)}handleInboxAdded(e,t){if(this.isShutdown)return;let n=t.filter(e=>!this.quarantinedDocumentIds.has(e.documentId));if(n.length===0)return;let r=[],i=[];for(let e of n)e.jobId?r.push(e):i.push(e);for(let t of i)this.applyInboxJob(e,t);if(r.length>0){let t=Na(r.map(t=>({remote:e,syncOp:t})),this.config.maxInboxBatchSize);this.processInboxChunks(t)}}processInboxChunks(e){let t=this.inboxChunkChain.then(async()=>{for(let t of e){if(this.isShutdown)return;await this.applyInboxBatch(t)}});return this.inboxChunkChain=t.catch(e=>{this.logger.error(`Inbox chunk processing failed (@error)`,e instanceof Error?e.message:String(e))}),t}async applyInboxJob(e,t){let n=t.operations.map(e=>e.operation),r;try{r=await this.reactor.load(t.documentId,t.branch,n,this.abortController.signal,{sourceRemote:e.name})}catch(n){if(this.isShutdown)return;let r=n instanceof Error?n:Error(String(n));this.logger.error(`Failed to load operations from inbox (@remote, @documentId, @error)`,e.name,t.documentId,r.message);let i=new Sa(ga.Inbox,r);t.failed(i),e.channel.deadLetter.add(t),e.channel.inbox.remove(t);return}let i;try{i=await this.awaiter.waitForJob(r.id,this.abortController.signal)}catch(n){if(this.isShutdown)return;let i=n instanceof Error?n:Error(String(n));this.logger.error(`Failed to wait for job completion (@remote, @documentId, @jobId, @error)`,e.name,t.documentId,r.id,i.message);let a=new Sa(ga.Inbox,i);t.failed(a),e.channel.deadLetter.add(t),e.channel.inbox.remove(t);return}if(!this.isShutdown){if(i.status===A.FAILED){let n=i.error?.message||`Unknown error`;this.logger.error(`Failed to apply operations from inbox (@remote, @documentId, @jobId, @error)`,e.name,t.documentId,i.id,n);let r=new Sa(ga.Inbox,Error(`Failed to apply operations: ${n}`));t.failed(r),e.channel.deadLetter.add(t)}else t.executed();e.channel.inbox.remove(t)}}async applyInboxBatch(e){let t=e[0].remote.name,n=new Set(e.map(({syncOp:e})=>e.jobId)),r=e.map(({syncOp:e})=>{let t=[],r=[];for(let i of e.jobDependencies)if(i)if(n.has(i))t.push(i);else{let e=this.planKeyToJobUuid.get(i);e!==void 0&&r.push(e)}let i=`${e.documentId}:${e.scopes[0]}:${e.branch}`,a=this.lastEnqueuedJobIdByKey.get(i);return a!==void 0&&r.push(a),{key:e.jobId,documentId:e.documentId,scope:e.scopes[0],branch:e.branch,operations:e.operations.map(e=>e.operation),dependsOn:t,externalDeps:r}}),i={jobs:r},a;try{a=await this.reactor.loadBatch(i,this.abortController.signal,{sourceRemote:t})}catch(t){if(this.isShutdown)return;for(let{remote:n,syncOp:r}of e){let e=t instanceof Error?t:Error(String(t));r.failed(new Sa(ga.Inbox,e)),n.channel.deadLetter.add(r),n.channel.inbox.remove(r)}return}if(!this.isShutdown){for(let e of r){if(!(e.key in a.jobs))continue;let t=a.jobs[e.key];this.recordPlanKeyMapping(e.key,t.id);let n=`${e.documentId}:${e.scope}:${e.branch}`;this.lastEnqueuedJobIdByKey.set(n,t.id)}for(let{remote:t,syncOp:n}of e){if(!(n.jobId in a.jobs)){this.logger.error(`Job key missing from batch load result (@remote, @documentId, @jobId)`,t.name,n.documentId,n.jobId);let e=new Sa(ga.Inbox,Error(`Job key '${n.jobId}' missing from batch load result`));n.failed(e),t.channel.deadLetter.add(n),t.channel.inbox.remove(n);continue}let e=a.jobs[n.jobId],r;try{r=await this.awaiter.waitForJob(e.id,this.abortController.signal)}catch(e){if(this.isShutdown)continue;let r=e instanceof Error?e:Error(String(e));n.failed(new Sa(ga.Inbox,r)),t.channel.deadLetter.add(n),t.channel.inbox.remove(n);continue}if(this.isShutdown)return;if(r.status===A.FAILED){let e=r.error?.message||`Unknown error`,i=new Sa(ga.Inbox,Error(`Failed to apply operations: ${e}`));n.failed(i),t.channel.deadLetter.add(n)}else n.executed();t.channel.inbox.remove(n)}}}async updateOutbox(e,t,n=lo.Backfill,r){let i=r?AbortSignal.any([r,this.abortController.signal]):this.abortController.signal,a=t,o=new Map,s,c=e.options.sinceTimestampUtcMs,l=t=>{if(t.length===0)return;let r=ka(t),i=[];for(let t of r){let r=crypto.randomUUID(),a=o.get(t.documentId),c=[];a&&c.push(a),n===lo.BatchTriggered&&s&&s!==a&&c.push(s);let l=new wa(crypto.randomUUID(),r,c,e.name,t.documentId,[t.scope],t.branch,t.operations);i.push(l),o.set(t.documentId,r),n===lo.BatchTriggered&&(s=r)}e.channel.outbox.add(...i)},u=await this.operationIndex.find(e.collectionId.key,t,{excludeSourceRemote:e.name},void 0,i),d=[],f;do{if(i.aborted)return;for(let e of u.results)a=Math.max(a,e.ordinal??0);let t=u.results.map(e=>ja(e));if(d.length>0&&(t=[...d,...t],d=[]),c&&c!==`0`&&(t=t.filter(e=>e.operation.timestampUtcMs>=c)),t=Da(t,e.filter),t=t.filter(e=>!this.quarantinedDocumentIds.has(e.context.documentId)),f=!!u.next,t.length>0)if(t.sort((e,t)=>e.context.documentId===t.context.documentId?e.context.scope===t.context.scope?e.context.ordinal-t.context.ordinal:e.context.scope<t.context.scope?-1:1:e.context.documentId<t.context.documentId?-1:1),f){let e=Aa(t);d=e.carry,l(e.emit)}else l(t);f&&(u=await u.next())}while(f);d.length>0&&l(d),e.channel.outbox.advanceOrdinal(a)}},mo=class{channelFactory;remoteStorage;cursorStorage;deadLetterStorage;config={};withChannelFactory(e){return this.channelFactory=e,this}withRemoteStorage(e){return this.remoteStorage=e,this}withCursorStorage(e){return this.cursorStorage=e,this}withDeadLetterStorage(e){return this.deadLetterStorage=e,this}withMaxDeadLettersPerRemote(e){return this.config.maxDeadLettersPerRemote=e,this}withMaxInboxBatchSize(e){return this.config.maxInboxBatchSize=e,this}build(e,t,n,r,i,a){return this.buildModule(e,t,n,r,i,a).syncManager}buildModule(e,t,n,r,i,a){if(!this.channelFactory)throw Error(`Channel factory is required`);let o=this.remoteStorage??new ro(i),s=this.cursorStorage??new Za(i),c=this.deadLetterStorage??new eo(i),l=new po(t,o,s,c,this.channelFactory,n,e,r,a,this.config);return{remoteStorage:o,cursorStorage:s,deadLetterStorage:c,channelFactory:this.channelFactory,syncManager:l}}};async function ho(){let{Kysely:e}=await r(async()=>{let{Kysely:e}=await import(`./esm-DUjqbF8m.js`);return{Kysely:e}},__vite__mapDeps([0,1])),{PGlite:t}=await r(async()=>{let{PGlite:e}=await import(`./dist-ScMbe_zR.js`);return{PGlite:e}},__vite__mapDeps([2,3,4,5,6,7,8,9])),{PGliteDialect:n}=await r(async()=>{let{PGliteDialect:e}=await import(`./dist-PLXkZ7-H.js`);return{PGliteDialect:e}},__vite__mapDeps([10,11,1]));return new e({dialect:new n(new t)})}function go(e=!1){let t=e,n=Promise.resolve();return[{get isShutdown(){return t},get completed(){return n}},e=>{t=e},e=>{n=e}]}var j=class extends Error{constructor(e){super(e||`Aborted`),this.name=`AbortError`}},_o=class{logger;documentModelRegistry;shutdownStatus;setShutdown;setCompleted;queue;jobTracker;readModelCoordinator;features;documentView;documentIndexer;operationStore;eventBus;executorManager;constructor(e,t,n,r,i,a,o,s,c,l,u){this.logger=e,this.documentModelRegistry=t,this.queue=n,this.jobTracker=r,this.readModelCoordinator=i,this.features=a,this.documentView=o,this.documentIndexer=s,this.operationStore=c,this.eventBus=l,this.executorManager=u;let[d,f,p]=go(!1);this.shutdownStatus=d,this.setShutdown=f,this.setCompleted=p,this.eventBus.subscribe(w.JOB_FAILED,(e,t)=>{this.logger.error(`Job @JobId failed with @Message: @Job`,t.jobId,t.error.message,t.job)}),this.readModelCoordinator.start()}kill(){return this.logger.verbose(`kill()`),this.shutdownStatus.isShutdown?this.shutdownStatus:(this.setShutdown(!0),this.setCompleted((async()=>{await this.executorManager.stop(!0),this.readModelCoordinator.stop(),this.jobTracker.shutdown()})()),this.shutdownStatus)}getDocumentModels(e,t,n){this.logger.verbose(`getDocumentModels(@namespace, @paging)`,e,t),D(n,()=>new j);let r=this.documentModelRegistry.getAllModules().filter(t=>!e||t.documentModel.global.id.startsWith(e)),i=t&&parseInt(t.cursor)||0,a=t?.limit||r.length,o=r.slice(i,i+a),s=i+a<r.length,c=s?String(i+a):void 0;return Promise.resolve({results:o,options:t||{cursor:`0`,limit:r.length},nextCursor:c,next:s?()=>this.getDocumentModels(e,{cursor:c,limit:a},n):void 0})}async get(e,t,n,r){return this.logger.verbose(`get(@id, @view)`,e,t),await this.documentView.get(e,t,n,r)}async getBySlug(e,t,n,r){this.logger.verbose(`getBySlug(@slug, @view)`,e,t);let i=await this.documentView.resolveSlug(e,t,n,r);if(!i)throw Error(`Document not found with slug: ${e}`);return await this.get(i,t,n,r)}async getByIdOrSlug(e,t,n,r){return this.logger.verbose(`getByIdOrSlug(@identifier, @view)`,e,t),await this.documentView.getByIdOrSlug(e,t,n,r)}async getOutgoingRelationships(e,t,n,r){let i=await this.documentIndexer.getOutgoing(e,[t],void 0,n,r);return D(r,()=>new j),i.results.map(e=>e.targetId)}async getIncomingRelationships(e,t,n,r){let i=await this.documentIndexer.getIncoming(e,[t],void 0,n,r);return D(r,()=>new j),i.results.map(e=>e.sourceId)}async getOperations(e,t,n,r,i,a){this.logger.verbose(`getOperations(@documentId, @view, @filter, @paging)`,e,t,n,r);let o=t?.branch||`main`,s=await this.operationStore.getRevisions(e,o,a);D(a,()=>new j);let c=Object.keys(s.revision),l={};for(let s of c){if(!ye(t,s))continue;D(a,()=>new j);let c=await this.operationStore.getSince(e,s,o,-1,n,r,a);l[s]={results:c.results,options:c.options,nextCursor:c.nextCursor,next:c.next?async()=>(await this.getOperations(e,t,n,{cursor:c.nextCursor,limit:c.options.limit},i,a))[s]:void 0}}return l}async find(e,t,n,r,i){this.logger.verbose(`find(@search, @view, @paging)`,e,t,n);let a;if(e.ids){if(e.slugs&&e.slugs.length>0)throw Error(`Cannot use both ids and slugs in the same search`);a=await this.findByIds(e.ids,t,n,r,i),e.type&&(a=xi(a,e.type))}else if(e.slugs)a=await this.findBySlugs(e.slugs,t,n,r,i),e.type&&(a=xi(a,e.type));else if(e.parentId)a=await this.findByParentId(e.parentId,t,n,r,i),e.type&&(a=xi(a,e.type));else if(e.type)a=await this.findByType(e.type,t,n,r,i);else throw Error(`No search criteria provided`);return D(i,()=>new j),a}async create(e,t,n,r){this.logger.verbose(`create(@id, @type, @slug)`,e.header.id,e.header.documentType,e.header.slug);let i=new Date().toISOString();D(n,()=>new j);let a=[li({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}}),ui({documentId:e.header.id,model:e.header.documentType,fromVersion:0,toVersion:e.state.document.version,initialState:e.state})];t&&(a=await Ti(a,t,n));let o=ke(),s=Ei(o,r),c={id:o,kind:`mutation`,documentId:e.header.id,scope:`document`,branch:`main`,actions:a,operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:s},l={id:o,documentId:c.documentId,status:A.PENDING,createdAtUtcIso:i,consistencyToken:{version:1,createdAtUtcIso:i,coordinates:[]},meta:s};return this.jobTracker.registerJob(l),this.emitJobPending(l.id,s),await this.queue.enqueue(c),l}async deleteDocument(e,t,n,r){this.logger.verbose(`deleteDocument(@id)`,e);let i=new Date().toISOString();D(n,()=>new j);let a=di(e);t&&(a=await wi(a,t,n));let o=ke(),s=Ei(o,r),c={id:o,kind:`mutation`,documentId:e,scope:`document`,branch:`main`,actions:[a],operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:s},l={id:o,documentId:c.documentId,status:A.PENDING,createdAtUtcIso:i,consistencyToken:{version:1,createdAtUtcIso:i,coordinates:[]},meta:s};return this.jobTracker.registerJob(l),this.emitJobPending(l.id,s),await this.queue.enqueue(c),l}async execute(e,t,n,r,i){this.logger.verbose(`execute(@docId, @branch, @actions)`,e,t,n),D(r,()=>new j);let a=new Date().toISOString(),o=Ci(n),s=ke(),c=Ei(s,i),l={id:s,kind:`mutation`,documentId:e,scope:o,branch:t,actions:n,operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:c},u={id:s,documentId:l.documentId,status:A.PENDING,createdAtUtcIso:a,consistencyToken:{version:1,createdAtUtcIso:a,coordinates:[]},meta:c};return this.jobTracker.registerJob(u),this.emitJobPending(u.id,c),await this.queue.enqueue(l),D(r,()=>new j),u}async load(e,t,n,r,i){if(this.logger.verbose(`load(@docId, @branch, @count, @operations)`,e,t,n.length,n),D(r,()=>new j),n.length===0)throw Error(`load requires at least one operation`);let a=Si(n),o=new Date().toISOString(),s=ke(),c=Ei(s,i),l={id:s,kind:`load`,documentId:e,scope:a,branch:t,actions:[],operations:n,createdAt:o,queueHint:[],maxRetries:3,errorHistory:[],meta:c},u={id:s,documentId:l.documentId,status:A.PENDING,createdAtUtcIso:o,consistencyToken:{version:1,createdAtUtcIso:o,coordinates:[]},meta:c};return this.jobTracker.registerJob(u),this.emitJobPending(u.id,c),await this.queue.enqueue(l),D(r,()=>new j),u}async executeBatch(e,t,n){this.logger.verbose(`executeBatch(@count jobs)`,e.jobs.length),D(t,()=>new j),hi(e.jobs);for(let t of e.jobs)_i(t);let r=new Date().toISOString(),i=new Map;for(let t of e.jobs)i.set(t.key,ke());let a=ke(),o=[...i.values()],s={...n,batchId:a,batchJobIds:o},c=new Map;for(let t of e.jobs){let e={id:i.get(t.key),documentId:t.documentId,status:A.PENDING,createdAtUtcIso:r,consistencyToken:{version:1,createdAtUtcIso:r,coordinates:[]},meta:s};this.jobTracker.registerJob(e),this.emitJobPending(e.id,s),c.set(t.key,e)}let l=yi(e.jobs),u=[];try{for(let n of l){D(t,()=>new j);let a=e.jobs.find(e=>e.key===n),o=i.get(n),c=a.dependsOn.map(e=>i.get(e)),l={id:o,kind:`mutation`,documentId:a.documentId,scope:a.scope,branch:a.branch,actions:a.actions,operations:[],createdAt:r,queueHint:c,maxRetries:3,errorHistory:[],meta:s};await this.queue.enqueue(l),u.push(n)}}catch(e){for(let e of u){let t=i.get(e);try{await this.queue.remove(t)}catch{}}for(let e of c.values())this.jobTracker.markFailed(e.id,bi(`Batch enqueue failed`));throw e}return{jobs:Object.fromEntries(c)}}async loadBatch(e,t,n){this.logger.verbose(`loadBatch(@count jobs)`,e.jobs.length),D(t,()=>new j),gi(e.jobs);for(let t of e.jobs)vi(t);let r=new Date().toISOString(),i=new Map;for(let t of e.jobs)i.set(t.key,ke());let a=ke(),o=[...i.values()],s={...n,batchId:a,batchJobIds:o},c=new Map;for(let t of e.jobs){let e={id:i.get(t.key),documentId:t.documentId,status:A.PENDING,createdAtUtcIso:r,consistencyToken:{version:1,createdAtUtcIso:r,coordinates:[]},meta:s};this.jobTracker.registerJob(e),this.emitJobPending(e.id,s),c.set(t.key,e)}let l=yi(e.jobs),u=[];try{for(let n of l){D(t,()=>new j);let a=e.jobs.find(e=>e.key===n),o=i.get(n),c=[...a.dependsOn.map(e=>i.get(e)),...a.externalDeps],l={id:o,kind:`load`,documentId:a.documentId,scope:a.scope,branch:a.branch,actions:[],operations:a.operations,createdAt:r,queueHint:c,maxRetries:3,errorHistory:[],meta:s};await this.queue.enqueue(l),u.push(n)}}catch(e){for(let e of u){let t=i.get(e);try{await this.queue.remove(t)}catch{}}for(let e of c.values())this.jobTracker.markFailed(e.id,bi(`Batch enqueue failed`));throw e}return{jobs:Object.fromEntries(c)}}async addRelationship(e,t,n,r=`main`,i,a){this.logger.verbose(`addRelationship(@sourceId, @targetId, @relationshipType, @branch)`,e,t,n,r),D(a,()=>new j);let o=[fi(e,t,n)];return i&&(o=await Ti(o,i,a)),await this.execute(e,r,o,a)}async removeRelationship(e,t,n,r=`main`,i,a){this.logger.verbose(`removeRelationship(@sourceId, @targetId, @relationshipType, @branch)`,e,t,n,r),D(a,()=>new j);let o=[pi(e,t,n)];return i&&(o=await Ti(o,i,a)),await this.execute(e,r,o,a)}getJobStatus(e,t){this.logger.verbose(`getJobStatus(@jobId)`,e),D(t,()=>new j);let n=this.jobTracker.getJobStatus(e);if(!n){let t=new Date().toISOString();return Promise.resolve({id:e,documentId:``,status:A.FAILED,createdAtUtcIso:t,completedAtUtcIso:t,error:bi(`Job not found`),consistencyToken:{version:1,createdAtUtcIso:t,coordinates:[]},meta:{batchId:e,batchJobIds:[e]}})}return Promise.resolve(n)}async findByIds(e,t,n,r,i){this.logger.verbose(`findByIds(@count ids)`,e.length);let a=n?.cursor&&parseInt(n.cursor)||0,o=n?.limit||e.length,s=e.slice(a,a+o),c=await this.documentView.getMany(s,t,r,i),l=a+o<e.length?String(a+o):void 0;return{results:c,options:n||{cursor:`0`,limit:e.length},nextCursor:l}}async findBySlugs(e,t,n,r,i){this.logger.verbose(`findBySlugs(@count slugs)`,e.length);let a=await this.documentView.resolveSlugs(e,t,r,i);return await this.findByIds(a,t,n,r,i)}async findByParentId(e,t,n,r,i){this.logger.verbose(`findByParentId(@parentId)`,e);let a=(await this.documentIndexer.getOutgoing(e,[`child`],n,r,i)).results.map(e=>e.targetId);return await this.findByIds(a,t,n,void 0,i)}async findByType(e,t,n,r,i){return this.logger.verbose(`findByType(@type)`,e),await this.documentView.findByType(e,t,n,r,i)}emitJobPending(e,t){let n={jobId:e,jobMeta:t};this.eventBus.emit(w.JOB_PENDING,n).catch(()=>{})}},vo=class{logger;documentModels=[];upgradeManifests=[];features={legacyStorageEnabled:!1};readModels=[];readModelFactories=[];executorManager;executorConfig={};writeCacheConfig;migrationStrategy=`auto`;syncBuilder;eventBus;readModelCoordinator;signatureVerifier;kyselyInstance;signalHandlersEnabled=!1;queueInstance;channelScheme;jwtHandler;documentModelLoader;shutdownHooks=[];driveContainerTypes=Oe;documentModelSpecs=[];workerPoolConfig;resolvedModelManifest;workerDbConfig;workerSignatureVerifierSpec;workerFactory;projectionShardConfig;projectionWorkerFactory;instrumentedPools=[];withLogger(e){return this.logger=e,this}withDocumentModels(e){return this.documentModels=e,this}withUpgradeManifests(e){return this.upgradeManifests=e,this}withFeatures(e){return this.features={...this.features,...e},this}withReadModel(e){return this.readModels.push(e),this}withReadModelFactory(e){return this.readModelFactories.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}withDriveContainerTypes(e){return this.driveContainerTypes=new Set(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}withInstrumentedPool(e){return this.instrumentedPools.push(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}withShutdownHook(e){return this.shutdownHooks.push(e),this}withDocumentModelSpecs(e){return this.documentModelSpecs=e,this}withWorkerPool(e){return this.workerPoolConfig=e,this}withWorkerDbConfig(e){return this.workerDbConfig=e,this}withWorkerSignatureVerifierSpec(e){return this.workerSignatureVerifierSpec=e,this}withWorkerFactory(e){return this.workerFactory=e,this}withProjectionShards(e){return this.projectionShardConfig=e,this}withProjectionWorkerFactory(e){return this.projectionWorkerFactory=e,this}getResolvedModelManifest(){return this.resolvedModelManifest}async build(){return(await this.buildModule()).reactor}async buildModule(){if(this.logger||=new me([`reactor`]),this.workerPoolConfig?.enabled){if(this.documentModels.length>0)throw Error(`workerPool.enabled requires withDocumentModelSpecs; remove withDocumentModels() in worker-pool mode.`);if(this.documentModelSpecs.length===0)throw Error(`workerPool.enabled requires at least one spec registered via withDocumentModelSpecs.`);let e=!this.executorManager&&!this.workerFactory;if(e&&!this.workerDbConfig)throw Error(`workerPool.enabled requires withWorkerDbConfig (or a custom withWorkerFactory / withExecutor).`);if(e&&!this.workerSignatureVerifierSpec)throw Error(`workerPool.enabled requires withWorkerSignatureVerifierSpec (or a custom withWorkerFactory / withExecutor).`)}this.documentModelSpecs.length>0&&(this.resolvedModelManifest=this.documentModelSpecs.map(e=>`filePath`in e?{documentType:`<unresolved>`,version:`<unresolved>`,spec:{module:{filePath:e.filePath,exportName:`documentModel`}}}:{documentType:`<unresolved>`,version:e.version,spec:{module:{packageName:e.packageName,exportName:`documentModel`}}}));let e=new Fe;if(this.upgradeManifests.length>0){let t=e.registerUpgradeManifests(...this.upgradeManifests);for(let e of t)e.status===`error`&&this.logger.error(`Failed to register upgrade manifest: @error`,e.error.message)}if(this.documentModels.length>0){let t=e.registerModules(...this.documentModels);for(let e of t)e.status===`error`&&this.logger.error(`Failed to register document model: @error`,e.error.message)}let t=this.kyselyInstance??(this.workerPoolConfig?.enabled&&this.workerDbConfig?await this.createPostgresDatabase(this.workerDbConfig):await ho());if(this.migrationStrategy===`auto`){let e=await ge(t,Be);if(!e.success&&e.error)throw Error(`Database migration failed: ${e.error.message}`)}let n=t.withSchema(Be),r=new Ee(n),i=new je(n),a=this.eventBus||new Te,o=this.documentModelLoader?new ca(e,this.documentModelLoader):new la(e),s=this.queueInstance??new sa(a,o),c=new $i(a),l=new be(i,r,e,{maxDocuments:this.writeCacheConfig?.maxDocuments??100,ringBufferSize:this.writeCacheConfig?.ringBufferSize??10,keyframeInterval:this.writeCacheConfig?.keyframeInterval??10});await l.startup();let u=new De(n),d=new Me(r,{maxDocuments:1e3});await d.startup();let f=new Pe(u),p=new Ne(n,r,u,i,l,d,f),m=this.executorManager,h=this.executorConfig.maxConcurrency??1;if(!m)if(this.workerPoolConfig?.enabled){let e=new Ji(this.workerFactory??await this.createDefaultWorkerFactory(this.workerPoolConfig),a,s,c,this.logger,o,f,this.executorConfig.jobTimeoutMs);m=e,h=this.workerPoolConfig.numWorkers,o instanceof ca&&o.setBroadcastHook(t=>e.loadModel(t))}else m=new Qi(()=>new Se(this.logger,e,r,a,l,u,d,f,this.driveContainerTypes,this.executorConfig,this.signatureVerifier,p),a,s,c,this.logger,o,this.executorConfig.jobTimeoutMs);await m.start(h);let g=Array.from(new Set([...this.readModels])),_=new bn,v=new vn(n,r,u,l,_);try{await v.init()}catch(e){console.error(`Error initializing document view`,e)}g.push(v);let y=new bn,b=new Sn(n,u,l,y);try{await b.init()}catch(e){console.error(`Error initializing document indexer`,e)}g.push(b);let x=new da(new ua),ee=new fa(x,v),te=new bn,ne=new aa(n,u,l,te,this.logger,this.driveContainerTypes);try{await ne.init()}catch(e){console.error(`Error initializing processor manager`,e)}for(let e of this.readModelFactories){let t=await e({operationIndex:u,writeCache:l,processorManagerConsistencyTracker:te});g.push(t)}let S=this.readModelCoordinator?this.readModelCoordinator:this.projectionShardConfig?await this.createProjectionShardManager(this.projectionShardConfig,a):new _n(a,g,[ee,ne]),C=new _o(this.logger,e,s,c,S,this.features,v,b,r,a,m),re;if(this.channelScheme){let e=this.channelScheme===pa.CONNECT?new Ka(this.logger,this.jwtHandler,s):new Ja(this.logger);re=new mo().withChannelFactory(e).buildModule(C,this.logger,u,a,n,this.driveContainerTypes),await re.syncManager.startup()}else this.syncBuilder&&(re=this.syncBuilder.buildModule(C,this.logger,u,a,n,this.driveContainerTypes),await re.syncManager.startup());let w={eventBus:a,documentModelRegistry:e,queue:s,jobTracker:c,executorManager:m,database:n,operationStore:r,keyframeStore:i,writeCache:l,operationIndex:u,documentView:v,documentViewConsistencyTracker:_,documentIndexer:b,documentIndexerConsistencyTracker:y,readModelCoordinator:S,subscriptionManager:x,processorManager:ne,processorManagerConsistencyTracker:te,syncModule:re,reactor:C,pools:this.instrumentedPools};return this.signalHandlersEnabled&&this.attachSignalHandlers(w),w}async createProjectionShardManager(e,t){if(!this.workerDbConfig)throw Error(`withProjectionShards requires withWorkerDbConfig; projection workers need connection info to open their own pools.`);let n=this.resolvedModelManifest??[],i={...this.workerDbConfig,poolSize:e.poolSize??this.workerDbConfig.poolSize,applicationName:`reactor-projection-shard`},a=this.projectionWorkerFactory??await this.createDefaultProjectionWorkerFactory(),o=[];for(let t=0;t<e.shardCount;t++){let e=he(`projection-shard-${t}`);o.push(e),this.instrumentedPools.push(e)}let{ProjectionShardManager:s}=await r(async()=>{let{ProjectionShardManager:e}=await import(`./projection-shard-manager-_c7orNo5-CYmXImZA.js`);return{ProjectionShardManager:e}},__vite__mapDeps([12,4,13,14,15])),c=new s({shardCount:e.shardCount,db:i,models:n,preReadyKinds:e.preReadyKinds,postReadyKinds:e.postReadyKinds,factory:a,logger:this.logger,hostBus:t,initTimeoutMs:e.initTimeoutMs,shutdownGraceMs:e.shutdownGraceMs,drainTimeoutMs:e.drainTimeoutMs,chainDepthReportIntervalMs:e.chainDepthReportIntervalMs,poolInstrumentations:o});return await c.startup(),this.shutdownHooks.push(()=>c.shutdown()),c}async createDefaultProjectionWorkerFactory(){let[{createProjectionThreadTransport:e},{projectionWorkerEntryPath:t}]=await Promise.all([r(()=>import(`./transport-CuogVKN_-CmEFLNk5.js`),__vite__mapDeps([16,4,15])),r(()=>import(`./projection-worker-wI4PwcV2-DKlb7c3l.js`),[])]);return()=>e(t)}async createDefaultWorkerFactory(e){let[{WorkerHandle:t},{createThreadTransport:n},{workerEntryPath:i}]=await Promise.all([r(()=>import(`./worker-handle-B1w03nRA-BHJaS5pO.js`),__vite__mapDeps([17,4,18,19,15])),r(()=>import(`./transport-ByGviWdZ-zEKFyLfk.js`),__vite__mapDeps([20,4,15])),r(()=>import(`./worker-XYrQaEmt-Ce3Gpb8t.js`).then(e=>e.n),__vite__mapDeps([21,22,18,13,4,1]))]),a=this.workerDbConfig,o=this.workerSignatureVerifierSpec,s=this.resolvedModelManifest??[],c=this.logger;return r=>{let l=`reactor-worker-${r}`,u=he(l);return this.instrumentedPools.push(u),new t({workerId:l,index:r,transport:n(i),initPayload:{poolConfig:e,db:a,signatureVerifier:o,models:s},logger:c,poolInstrumentation:u})}}async createPostgresDatabase(e){let{Kysely:t,PostgresDialect:n}=await r(async()=>{let{Kysely:e,PostgresDialect:t}=await import(`./esm-DUjqbF8m.js`);return{Kysely:e,PostgresDialect:t}},__vite__mapDeps([0,1])),i=(await r(async()=>{let{default:e}=await import(`./esm-mbrYcWED.js`);return{default:e}},__vite__mapDeps([23,4,15]))).default.Pool,a=new i({host:e.host,port:e.port,database:e.database,user:e.user,password:e.password,ssl:e.ssl?{rejectUnauthorized:!1}:void 0,application_name:e.applicationName,max:e.poolSize,connectionTimeoutMillis:e.connectionTimeoutMillis,idleTimeoutMillis:e.idleTimeoutMillis});return this.instrumentedPools.push(Re(a,e.applicationName??`reactor-host`)),new t({dialect:new n({pool:a})})}attachSignalHandlers(e){if(typeof globalThis>`u`||!(`process`in globalThis)||typeof globalThis.process.on!=`function`)return;let t=globalThis.process,n=t.exit.bind(t),r=!1,i,a=async a=>{if(r){this.logger.warn(`Received ${a} again, continuing graceful shutdown...`);return}r=!0,t.exit=(e=>{i??=e??0}),this.logger.info(`Received ${a}, starting graceful shutdown...`);let o=e.reactor.kill();try{await o.completed}catch(e){this.logger.error(`Shutdown failed waiting for reactor:`,e),t.exit=n,n(1);return}for(let e of this.shutdownHooks)try{await e()}catch(e){this.logger.error(`Shutdown hook failed:`,e)}try{await e.database.destroy()}catch(e){this.logger.error(`Shutdown failed destroying database:`,e),t.exit=n,n(1);return}this.logger.info(`Shutdown complete`),t.exit=n,n(i??0)};t.prependListener(`SIGINT`,()=>void a(`SIGINT`)),t.prependListener(`SIGTERM`,()=>void a(`SIGTERM`))}},yo=class{publicKey={};sign(){return Promise.resolve(new Uint8Array)}verify(){return Promise.resolve()}signAction(){return Promise.resolve([``,``,``,``,``])}},bo=class{logger;reactorBuilder;reactor;eventBus;documentIndexer;documentView;signer;signatureVerifier;subscriptionManager;jobAwaiter;documentModelLoader;withLogger(e){return this.logger=e,this}withReactorBuilder(e){if(this.reactor)throw Error(`Reactor is already set`);return this.reactorBuilder=e,this}withReactor(e,t,n,r){if(this.reactorBuilder)throw Error(`ReactorBuilder is already set`);return this.reactor=e,this.eventBus=t,this.documentIndexer=n,this.documentView=r,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}withDocumentModelLoader(e){return this.documentModelLoader=e,this}async build(){return(await this.buildModule()).client}async buildModule(){this.logger||=new me([`reactor-client`]);let e,t,n,r,i;if(this.reactorBuilder)this.signatureVerifier&&this.reactorBuilder.withSignatureVerifier(this.signatureVerifier),this.documentModelLoader&&this.reactorBuilder.withDocumentModelLoader(this.documentModelLoader),i=await this.reactorBuilder.buildModule(),e=i.reactor,t=i.eventBus,n=i.documentIndexer,r=i.documentView;else if(this.reactor&&this.eventBus&&this.documentIndexer&&this.documentView)e=this.reactor,t=this.eventBus,n=this.documentIndexer,r=this.documentView,i=void 0;else throw Error(`Either ReactorBuilder or (Reactor + EventBus + DocumentIndexer + DocumentView) is required`);let a=this.signer??new yo,o=this.subscriptionManager??i?.subscriptionManager??new da(new ua),s=this.jobAwaiter??new ji(t,(t,n)=>e.getJobStatus(t,n));return{client:new Li(this.logger,e,a,o,s,n,r),reactor:e,eventBus:t,documentIndexer:n,documentView:r,signer:a,subscriptionManager:o,jobAwaiter:s,reactorModule:i}}},xo={putKeyframe:()=>Promise.resolve(),findNearestKeyframe:()=>Promise.resolve(void 0),listKeyframes:()=>Promise.resolve([]),deleteKeyframes:()=>Promise.resolve(0)},So=class{keyframeStore;operationStore;writeCache;documentView;documentModelRegistry;constructor(e,t,n,r,i){this.keyframeStore=e,this.operationStore=t,this.writeCache=n,this.documentView=r,this.documentModelRegistry=i}async validateDocument(e,t=`main`,n){let r=[],i=[],a=new be(xo,this.operationStore,this.documentModelRegistry,{maxDocuments:1,ringBufferSize:1,keyframeInterval:2**53-1}),o=await this.keyframeStore.listKeyframes(e,void 0,t,n);for(let i of o){D(n),a.invalidate(e,i.scope,t);let o=await a.getState(e,i.scope,t,i.revision,n),s=u(i.document,i.scope),c=u(o,i.scope);s!==c&&r.push({scope:i.scope,branch:t,revision:i.revision,keyframeHash:s,replayedHash:c})}let s;try{s=await this.documentView.get(e)}catch{return{documentId:e,isConsistent:r.length===0,keyframeIssues:r,snapshotIssues:i}}let c=await this.operationStore.getRevisions(e,t,n),l=Object.keys(c.revision);for(let r of l){if(r===`document`)continue;a.invalidate(e,r,t);let o;try{o=await a.getState(e,r,t,void 0,n)}catch{D(n);continue}let c=u(s,r),l=u(o,r);c!==l&&i.push({scope:r,branch:t,snapshotHash:c,replayedHash:l})}return{documentId:e,isConsistent:r.length===0&&i.length===0,keyframeIssues:r,snapshotIssues:i}}async rebuildKeyframes(e,t=`main`,n){return{documentId:e,keyframesDeleted:await this.keyframeStore.deleteKeyframes(e,void 0,t,n),scopesInvalidated:0}}async rebuildSnapshots(e,t=`main`,n){let r=await this.discoverScopes(e,t,n);for(let i of r)D(n),this.writeCache.invalidate(e,i,t);return{documentId:e,keyframesDeleted:0,scopesInvalidated:r.length}}async discoverScopes(e,t,n){let r=await this.operationStore.getRevisions(e,t,n);return Object.keys(r.revision)}},Co=function(e){return e[e.AnalyticsPath=0]=`AnalyticsPath`,e[e.AnalyticsPathSegment=1]=`AnalyticsPathSegment`,e[e.AnalyticsPeriod=2]=`AnalyticsPeriod`,e}({}),wo=function(e){return e[e.VectorAdd=0]=`VectorAdd`,e[e.VectorSubtract=1]=`VectorSubtract`,e[e.ScalarMultiply=2]=`ScalarMultiply`,e[e.ScalarDivide=3]=`ScalarDivide`,e}({}),To=function(e){return e[e.Total=0]=`Total`,e[e.Annual=1]=`Annual`,e[e.SemiAnnual=2]=`SemiAnnual`,e[e.Quarterly=3]=`Quarterly`,e[e.Monthly=4]=`Monthly`,e[e.Weekly=5]=`Weekly`,e[e.Daily=6]=`Daily`,e[e.Hourly=7]=`Hourly`,e}({}),Eo=class e{get segments(){return this._segments}_segments;static fromString(t){return new e(ko(t,`/`).map(e=>Do.fromString(e)))}static fromStringArray(t){return new e(t.map(e=>Do.fromString(e)))}static fromArray(t){return new e(t)}static fromJSON(t){return new e(t._v.split(`/`).map(e=>Do.fromString(e)))}constructor(e){this._segments=e}toJSON(){return{_t:Co.AnalyticsPath,_v:this.toString()}}toString(e=``){return this._segments.map(e=>e.toString()).join(`/`)+e}firstSegment(){return this._segments.length>0?this._segments[0]:new Do}reduce(){let t=this._segments.slice(1);return t.length<1&&t.push(new Do),new e(t)}applyLod(t){let n=[...this._segments];for(;n.length<t;)n.push(new Do);return new e(n.slice(0,t))}},Do=class e{get filters(){return this._filters}get groups(){return this._groups}_filters=null;_groups=null;static fromString(t){let n=ko(t,`:`),r;r=n[0]===`*`?null:ko(n[0],`,`).map(t=>e.unescape(t));let i;return i=n[1]===void 0||n[1].length<1?[]:n[1]===`*`?null:ko(n[1],`,`).map(t=>e.unescape(t)),new e(r,i)}static escape(e){return e.replace(/(\\|:|\/|,)/gi,`\\$1`)}static unescape(e){return e.replace(/\\(.)/gi,`$1`)}constructor(e=null,t=[]){this._filters=e,this._groups=t}toJSON(){return{_t:Co.AnalyticsPathSegment,_v:this.toString()}}toString(){let t=``;return this._filters===null?t+=`*`:t+=this._filters.map(t=>e.escape(t)).join(`,`),this._groups===null?t+=`:*`:this._groups.length>0&&(t+=`:`+this._groups.map(t=>e.escape(t)).join(`,`)),t}},Oo={":":/(?<!\\):/,",":/(?<!\\),/,"/":/(?<!\\)\//};function ko(e,t){let n=`@@`;for(;e.indexOf(n)>-1;)n+=`@`;return e.replaceAll(`\\\\`,n).split(Oo[t]).map(e=>e.replaceAll(n,`\\\\`))}var Ao=class extends Error{},jo=class extends Ao{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Mo=class extends Ao{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},No=class extends Ao{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},Po=class extends Ao{},Fo=class extends Ao{constructor(e){super(`Invalid unit ${e}`)}},Io=class extends Ao{},Lo=class extends Ao{constructor(){super(`Zone is an abstract class`)}},M=`numeric`,Ro=`short`,zo=`long`,Bo={year:M,month:M,day:M},Vo={year:M,month:Ro,day:M},Ho={year:M,month:Ro,day:M,weekday:Ro},Uo={year:M,month:zo,day:M},Wo={year:M,month:zo,day:M,weekday:zo},Go={hour:M,minute:M},Ko={hour:M,minute:M,second:M},qo={hour:M,minute:M,second:M,timeZoneName:Ro},Jo={hour:M,minute:M,second:M,timeZoneName:zo},Yo={hour:M,minute:M,hourCycle:`h23`},Xo={hour:M,minute:M,second:M,hourCycle:`h23`},Zo={hour:M,minute:M,second:M,hourCycle:`h23`,timeZoneName:Ro},Qo={hour:M,minute:M,second:M,hourCycle:`h23`,timeZoneName:zo},$o={year:M,month:M,day:M,hour:M,minute:M},es={year:M,month:M,day:M,hour:M,minute:M,second:M},ts={year:M,month:Ro,day:M,hour:M,minute:M},ns={year:M,month:Ro,day:M,hour:M,minute:M,second:M},rs={year:M,month:Ro,day:M,weekday:Ro,hour:M,minute:M},is={year:M,month:zo,day:M,hour:M,minute:M,timeZoneName:Ro},as={year:M,month:zo,day:M,hour:M,minute:M,second:M,timeZoneName:Ro},os={year:M,month:zo,day:M,weekday:zo,hour:M,minute:M,timeZoneName:zo},ss={year:M,month:zo,day:M,weekday:zo,hour:M,minute:M,second:M,timeZoneName:zo},cs=class{get type(){throw new Lo}get name(){throw new Lo}get ianaName(){return this.name}get isUniversal(){throw new Lo}offsetName(e,t){throw new Lo}formatOffset(e,t){throw new Lo}offset(e){throw new Lo}equals(e){throw new Lo}get isValid(){throw new Lo}},ls=null,us=class e extends cs{static get instance(){return ls===null&&(ls=new e),ls}get type(){return`system`}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return Jc(e,t,n)}formatOffset(e,t){return Qc(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type===`system`}get isValid(){return!0}},ds=new Map;function fs(e){let t=ds.get(e);return t===void 0&&(t=new Intl.DateTimeFormat(`en-US`,{hour12:!1,timeZone:e,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,era:`short`}),ds.set(e,t)),t}var ps={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ms(e,t){let n=e.format(t).replace(/\u200E/g,``),[,r,i,a,o,s,c,l]=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n);return[a,r,i,o,s,c,l]}function hs(e,t){let n=e.formatToParts(t),r=[];for(let e=0;e<n.length;e++){let{type:t,value:i}=n[e],a=ps[t];t===`era`?r[a]=i:F(a)||(r[a]=parseInt(i,10))}return r}var gs=new Map,_s=class e extends cs{static create(t){let n=gs.get(t);return n===void 0&&gs.set(t,n=new e(t)),n}static resetCache(){gs.clear(),ds.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(t){super(),this.zoneName=t,this.valid=e.isValidZone(t)}get type(){return`iana`}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return Jc(e,t,n,this.name)}formatOffset(e,t){return Qc(this.offset(e),t)}offset(e){if(!this.valid)return NaN;let t=new Date(e);if(isNaN(t))return NaN;let n=fs(this.name),[r,i,a,o,s,c,l]=n.formatToParts?hs(n,t):ms(n,t);o===`BC`&&(r=-Math.abs(r)+1);let u=Wc({year:r,month:i,day:a,hour:s===24?0:s,minute:c,second:l,millisecond:0}),d=+t,f=d%1e3;return d-=f>=0?f:1e3+f,(u-d)/(60*1e3)}equals(e){return e.type===`iana`&&e.name===this.name}get isValid(){return this.valid}},vs={};function ys(e,t={}){let n=JSON.stringify([e,t]),r=vs[n];return r||(r=new Intl.ListFormat(e,t),vs[n]=r),r}var bs=new Map;function xs(e,t={}){let n=JSON.stringify([e,t]),r=bs.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),bs.set(n,r)),r}var Ss=new Map;function Cs(e,t={}){let n=JSON.stringify([e,t]),r=Ss.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),Ss.set(n,r)),r}var ws=new Map;function Ts(e,t={}){let{base:n,...r}=t,i=JSON.stringify([e,r]),a=ws.get(i);return a===void 0&&(a=new Intl.RelativeTimeFormat(e,t),ws.set(i,a)),a}var Es=null;function Ds(){return Es||(Es=new Intl.DateTimeFormat().resolvedOptions().locale,Es)}var Os=new Map;function ks(e){let t=Os.get(e);return t===void 0&&(t=new Intl.DateTimeFormat(e).resolvedOptions(),Os.set(e,t)),t}var As=new Map;function js(e){let t=As.get(e);if(!t){let n=new Intl.Locale(e);t=`getWeekInfo`in n?n.getWeekInfo():n.weekInfo,`minimalDays`in t||(t={...Vs,...t}),As.set(e,t)}return t}function Ms(e){let t=e.indexOf(`-x-`);t!==-1&&(e=e.substring(0,t));let n=e.indexOf(`-u-`);if(n===-1)return[e];{let t,r;try{t=xs(e).resolvedOptions(),r=e}catch{let i=e.substring(0,n);t=xs(i).resolvedOptions(),r=i}let{numberingSystem:i,calendar:a}=t;return[r,i,a]}}function Ns(e,t,n){return n||t?(e.includes(`-u-`)||(e+=`-u`),n&&(e+=`-ca-${n}`),t&&(e+=`-nu-${t}`),e):e}function Ps(e){let t=[];for(let n=1;n<=12;n++){let r=R.utc(2009,n,1);t.push(e(r))}return t}function Fs(e){let t=[];for(let n=1;n<=7;n++){let r=R.utc(2016,11,13+n);t.push(e(r))}return t}function Is(e,t,n,r){let i=e.listingMode();return i===`error`?null:i===`en`?n(t):r(t)}function Ls(e){return e.numberingSystem&&e.numberingSystem!==`latn`?!1:e.numberingSystem===`latn`||!e.locale||e.locale.startsWith(`en`)||ks(e.locale).numberingSystem===`latn`}var Rs=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:r,floor:i,...a}=n;if(!t||Object.keys(a).length>0){let t={useGrouping:!1,...n};n.padTo>0&&(t.minimumIntegerDigits=n.padTo),this.inf=Cs(e,t)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else return I(this.floor?Math.floor(e):Bc(e,3),this.padTo)}},zs=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type===`fixed`){let t=-1*(e.offset/60),n=t>=0?`Etc/GMT+${t}`:`Etc/GMT${t}`;e.offset!==0&&_s.create(n).valid?(r=n,this.dt=e):(r=`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,r=e.zone.name):(r=`UTC`,this.dt=e.setZone(`UTC`).plus({minutes:e.offset}),this.originalZone=e.zone);let i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=xs(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(``):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(e=>{if(e.type===`timeZoneName`){let t=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...e,value:t}}else return e}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Bs=class{constructor(e,t,n){this.opts={style:`long`,...n},!t&&Oc()&&(this.rtf=Ts(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):_l(t,e,this.opts.numeric,this.opts.style!==`long`)}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},Vs={firstDay:1,minimalDays:4,weekend:[6,7]},N=class e{static fromOpts(t){return e.create(t.locale,t.numberingSystem,t.outputCalendar,t.weekSettings,t.defaultToEN)}static create(t,n,r,i,a=!1){let o=t||P.defaultLocale;return new e(o||(a?`en-US`:Ds()),n||P.defaultNumberingSystem,r||P.defaultOutputCalendar,Pc(i)||P.defaultWeekSettings,o)}static resetCache(){Es=null,bs.clear(),Ss.clear(),ws.clear(),Os.clear(),As.clear()}static fromObject({locale:t,numberingSystem:n,outputCalendar:r,weekSettings:i}={}){return e.create(t,n,r,i)}constructor(e,t,n,r,i){let[a,o,s]=Ms(e);this.locale=a,this.numberingSystem=t||o||null,this.outputCalendar=n||s||null,this.weekSettings=r,this.intl=Ns(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached??=Ls(this),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem===`latn`)&&(this.outputCalendar===null||this.outputCalendar===`gregory`);return e&&t?`en`:`intl`}clone(t){return!t||Object.getOwnPropertyNames(t).length===0?this:e.create(t.locale||this.specifiedLocale,t.numberingSystem||this.numberingSystem,t.outputCalendar||this.outputCalendar,Pc(t.weekSettings)||this.weekSettings,t.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return Is(this,e,rl,()=>{let n=this.intl===`ja`||this.intl.startsWith(`ja-`);t&=!n;let r=t?{month:e,day:`numeric`}:{month:e},i=t?`format`:`standalone`;if(!this.monthsCache[i][e]){let t=n?e=>this.dtFormatter(e,r).format():e=>this.extract(e,r,`month`);this.monthsCache[i][e]=Ps(t)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return Is(this,e,sl,()=>{let n=t?{weekday:e,year:`numeric`,month:`long`,day:`numeric`}:{weekday:e},r=t?`format`:`standalone`;return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=Fs(e=>this.extract(e,n,`weekday`))),this.weekdaysCache[r][e]})}meridiems(){return Is(this,void 0,()=>cl,()=>{if(!this.meridiemCache){let e={hour:`numeric`,hourCycle:`h12`};this.meridiemCache=[R.utc(2016,11,13,9),R.utc(2016,11,13,19)].map(t=>this.extract(t,e,`dayperiod`))}return this.meridiemCache})}eras(e){return Is(this,e,fl,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[R.utc(-40,1,1),R.utc(2017,1,1)].map(e=>this.extract(e,t,`era`))),this.eraCache[e]})}extract(e,t,n){let r=this.dtFormatter(e,t).formatToParts().find(e=>e.type.toLowerCase()===n);return r?r.value:null}numberFormatter(e={}){return new Rs(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new zs(e,this.intl,t)}relFormatter(e={}){return new Bs(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ys(this.intl,e)}isEnglish(){return this.locale===`en`||this.locale.toLowerCase()===`en-us`||ks(this.intl).locale.startsWith(`en-us`)}getWeekSettings(){return this.weekSettings?this.weekSettings:kc()?js(this.locale):Vs}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})`}},Hs=null,Us=class e extends cs{static get utcInstance(){return Hs===null&&(Hs=new e(0)),Hs}static instance(t){return t===0?e.utcInstance:new e(t)}static parseSpecifier(t){if(t){let n=t.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new e(Yc(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return`fixed`}get name(){return this.fixed===0?`UTC`:`UTC${Qc(this.fixed,`narrow`)}`}get ianaName(){return this.fixed===0?`Etc/UTC`:`Etc/GMT${Qc(-this.fixed,`narrow`)}`}offsetName(){return this.name}formatOffset(e,t){return Qc(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type===`fixed`&&e.fixed===this.fixed}get isValid(){return!0}},Ws=class extends cs{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 Gs(e,t){if(F(e)||e===null)return t;if(e instanceof cs)return e;if(Ec(e)){let n=e.toLowerCase();return n===`default`?t:n===`local`||n===`system`?us.instance:n===`utc`||n===`gmt`?Us.utcInstance:Us.parseSpecifier(n)||_s.create(e)}else if(wc(e))return Us.instance(e);else if(typeof e==`object`&&`offset`in e&&typeof e.offset==`function`)return e;else return new Ws(e)}var Ks={arab:`[٠-٩]`,arabext:`[۰-۹]`,bali:`[᭐-᭙]`,beng:`[০-৯]`,deva:`[०-९]`,fullwide:`[0-9]`,gujr:`[૦-૯]`,hanidec:`[〇|一|二|三|四|五|六|七|八|九]`,khmr:`[០-៩]`,knda:`[೦-೯]`,laoo:`[໐-໙]`,limb:`[᥆-᥏]`,mlym:`[൦-൯]`,mong:`[᠐-᠙]`,mymr:`[၀-၉]`,orya:`[୦-୯]`,tamldec:`[௦-௯]`,telu:`[౦-౯]`,thai:`[๐-๙]`,tibt:`[༠-༩]`,latn:`\\d`},qs={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]},Js=Ks.hanidec.replace(/[\[|\]]/g,``).split(``);function Ys(e){let t=parseInt(e,10);if(isNaN(t)){t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(e[n].search(Ks.hanidec)!==-1)t+=Js.indexOf(e[n]);else for(let e in qs){let[n,i]=qs[e];r>=n&&r<=i&&(t+=r-n)}}return parseInt(t,10)}else return t}var Xs=new Map;function Zs(){Xs.clear()}function Qs({numberingSystem:e},t=``){let n=e||`latn`,r=Xs.get(n);r===void 0&&(r=new Map,Xs.set(n,r));let i=r.get(t);return i===void 0&&(i=RegExp(`${Ks[n]}${t}`),r.set(t,i)),i}var $s=()=>Date.now(),ec=`system`,tc=null,nc=null,rc=null,ic=60,ac,oc=null,P=class{static get now(){return $s}static set now(e){$s=e}static set defaultZone(e){ec=e}static get defaultZone(){return Gs(ec,us.instance)}static get defaultLocale(){return tc}static set defaultLocale(e){tc=e}static get defaultNumberingSystem(){return nc}static set defaultNumberingSystem(e){nc=e}static get defaultOutputCalendar(){return rc}static set defaultOutputCalendar(e){rc=e}static get defaultWeekSettings(){return oc}static set defaultWeekSettings(e){oc=Pc(e)}static get twoDigitCutoffYear(){return ic}static set twoDigitCutoffYear(e){ic=e%100}static get throwOnInvalid(){return ac}static set throwOnInvalid(e){ac=e}static resetCaches(){N.resetCache(),_s.resetCache(),R.resetCache(),Zs()}},sc=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},cc=[0,31,59,90,120,151,181,212,243,273,304,334],lc=[0,31,60,91,121,152,182,213,244,274,305,335];function uc(e,t){return new sc(`unit out of range`,`you specified ${t} (of type ${typeof t}) as a ${e}, which is invalid`)}function dc(e,t,n){let r=new Date(Date.UTC(e,t-1,n));e<100&&e>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let i=r.getUTCDay();return i===0?7:i}function fc(e,t,n){return n+(Vc(e)?lc:cc)[t-1]}function pc(e,t){let n=Vc(e)?lc:cc,r=n.findIndex(e=>e<t),i=t-n[r];return{month:r+1,day:i}}function mc(e,t){return(e-t+7)%7+1}function hc(e,t=4,n=1){let{year:r,month:i,day:a}=e,o=fc(r,i,a),s=mc(dc(r,i,a),n),c=Math.floor((o-s+14-t)/7),l;return c<1?(l=r-1,c=Kc(l,t,n)):c>Kc(r,t,n)?(l=r+1,c=1):l=r,{weekYear:l,weekNumber:c,weekday:s,...$c(e)}}function gc(e,t=4,n=1){let{weekYear:r,weekNumber:i,weekday:a}=e,o=mc(dc(r,1,t),n),s=Hc(r),c=i*7+a-o-7+t,l;c<1?(l=r-1,c+=Hc(l)):c>s?(l=r+1,c-=Hc(r)):l=r;let{month:u,day:d}=pc(l,c);return{year:l,month:u,day:d,...$c(e)}}function _c(e){let{year:t,month:n,day:r}=e;return{year:t,ordinal:fc(t,n,r),...$c(e)}}function vc(e){let{year:t,ordinal:n}=e,{month:r,day:i}=pc(t,n);return{year:t,month:r,day:i,...$c(e)}}function yc(e,t){if(!F(e.localWeekday)||!F(e.localWeekNumber)||!F(e.localWeekYear)){if(!F(e.weekday)||!F(e.weekNumber)||!F(e.weekYear))throw new Po(`Cannot mix locale-based week fields with ISO-based week fields`);return F(e.localWeekday)||(e.weekday=e.localWeekday),F(e.localWeekNumber)||(e.weekNumber=e.localWeekNumber),F(e.localWeekYear)||(e.weekYear=e.localWeekYear),delete e.localWeekday,delete e.localWeekNumber,delete e.localWeekYear,{minDaysInFirstWeek:t.getMinDaysInFirstWeek(),startOfWeek:t.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function bc(e,t=4,n=1){let r=Tc(e.weekYear),i=Fc(e.weekNumber,1,Kc(e.weekYear,t,n)),a=Fc(e.weekday,1,7);return r?i?a?!1:uc(`weekday`,e.weekday):uc(`week`,e.weekNumber):uc(`weekYear`,e.weekYear)}function xc(e){let t=Tc(e.year),n=Fc(e.ordinal,1,Hc(e.year));return t?n?!1:uc(`ordinal`,e.ordinal):uc(`year`,e.year)}function Sc(e){let t=Tc(e.year),n=Fc(e.month,1,12),r=Fc(e.day,1,Uc(e.year,e.month));return t?n?r?!1:uc(`day`,e.day):uc(`month`,e.month):uc(`year`,e.year)}function Cc(e){let{hour:t,minute:n,second:r,millisecond:i}=e,a=Fc(t,0,23)||t===24&&n===0&&r===0&&i===0,o=Fc(n,0,59),s=Fc(r,0,59),c=Fc(i,0,999);return a?o?s?c?!1:uc(`millisecond`,i):uc(`second`,r):uc(`minute`,n):uc(`hour`,t)}function F(e){return e===void 0}function wc(e){return typeof e==`number`}function Tc(e){return typeof e==`number`&&e%1==0}function Ec(e){return typeof e==`string`}function Dc(e){return Object.prototype.toString.call(e)===`[object Date]`}function Oc(){try{return typeof Intl<`u`&&!!Intl.RelativeTimeFormat}catch{return!1}}function kc(){try{return typeof Intl<`u`&&!!Intl.Locale&&(`weekInfo`in Intl.Locale.prototype||`getWeekInfo`in Intl.Locale.prototype)}catch{return!1}}function Ac(e){return Array.isArray(e)?e:[e]}function jc(e,t,n){if(e.length!==0)return e.reduce((e,r)=>{let i=[t(r),r];return e&&n(e[0],i[0])===e[0]?e:i},null)[1]}function Mc(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function Nc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Pc(e){if(e==null)return null;if(typeof e!=`object`)throw new Io(`Week settings must be an object`);if(!Fc(e.firstDay,1,7)||!Fc(e.minimalDays,1,7)||!Array.isArray(e.weekend)||e.weekend.some(e=>!Fc(e,1,7)))throw new Io(`Invalid week settings`);return{firstDay:e.firstDay,minimalDays:e.minimalDays,weekend:Array.from(e.weekend)}}function Fc(e,t,n){return Tc(e)&&e>=t&&e<=n}function Ic(e,t){return e-t*Math.floor(e/t)}function I(e,t=2){let n=e<0,r;return r=n?`-`+(``+-e).padStart(t,`0`):(``+e).padStart(t,`0`),r}function Lc(e){if(!(F(e)||e===null||e===``))return parseInt(e,10)}function Rc(e){if(!(F(e)||e===null||e===``))return parseFloat(e)}function zc(e){if(!(F(e)||e===null||e===``)){let t=parseFloat(`0.`+e)*1e3;return Math.floor(t)}}function Bc(e,t,n=`round`){let r=10**t;switch(n){case`expand`:return e>0?Math.ceil(e*r)/r:Math.floor(e*r)/r;case`trunc`:return Math.trunc(e*r)/r;case`round`:return Math.round(e*r)/r;case`floor`:return Math.floor(e*r)/r;case`ceil`:return Math.ceil(e*r)/r;default:throw RangeError(`Value rounding ${n} is out of range`)}}function Vc(e){return e%4==0&&(e%100!=0||e%400==0)}function Hc(e){return Vc(e)?366:365}function Uc(e,t){let n=Ic(t-1,12)+1,r=e+(t-n)/12;return n===2?Vc(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function Wc(e){let t=Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute,e.second,e.millisecond);return e.year<100&&e.year>=0&&(t=new Date(t),t.setUTCFullYear(e.year,e.month-1,e.day)),+t}function Gc(e,t,n){return-mc(dc(e,1,t),n)+t-1}function Kc(e,t=4,n=1){let r=Gc(e,t,n),i=Gc(e+1,t,n);return(Hc(e)-r+i)/7}function qc(e){return e>99?e:e>P.twoDigitCutoffYear?1900+e:2e3+e}function Jc(e,t,n,r=null){let i=new Date(e),a={hourCycle:`h23`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`};r&&(a.timeZone=r);let o={timeZoneName:t,...a},s=new Intl.DateTimeFormat(n,o).formatToParts(i).find(e=>e.type.toLowerCase()===`timezonename`);return s?s.value:null}function Yc(e,t){let n=parseInt(e,10);Number.isNaN(n)&&(n=0);let r=parseInt(t,10)||0,i=n<0||Object.is(n,-0)?-r:r;return n*60+i}function Xc(e){let t=Number(e);if(typeof e==`boolean`||e===``||!Number.isFinite(t))throw new Io(`Invalid unit value ${e}`);return t}function Zc(e,t){let n={};for(let r in e)if(Nc(e,r)){let i=e[r];if(i==null)continue;n[t(r)]=Xc(i)}return n}function Qc(e,t){let n=Math.trunc(Math.abs(e/60)),r=Math.trunc(Math.abs(e%60)),i=e>=0?`+`:`-`;switch(t){case`short`:return`${i}${I(n,2)}:${I(r,2)}`;case`narrow`:return`${i}${n}${r>0?`:${r}`:``}`;case`techie`:return`${i}${I(n,2)}${I(r,2)}`;default:throw RangeError(`Value format ${t} is out of range for property format`)}}function $c(e){return Mc(e,[`hour`,`minute`,`second`,`millisecond`])}var el=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],tl=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],nl=[`J`,`F`,`M`,`A`,`M`,`J`,`J`,`A`,`S`,`O`,`N`,`D`];function rl(e){switch(e){case`narrow`:return[...nl];case`short`:return[...tl];case`long`:return[...el];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}}var il=[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`],al=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],ol=[`M`,`T`,`W`,`T`,`F`,`S`,`S`];function sl(e){switch(e){case`narrow`:return[...ol];case`short`:return[...al];case`long`:return[...il];case`numeric`:return[`1`,`2`,`3`,`4`,`5`,`6`,`7`];default:return null}}var cl=[`AM`,`PM`],ll=[`Before Christ`,`Anno Domini`],ul=[`BC`,`AD`],dl=[`B`,`A`];function fl(e){switch(e){case`narrow`:return[...dl];case`short`:return[...ul];case`long`:return[...ll];default:return null}}function pl(e){return cl[e.hour<12?0:1]}function ml(e,t){return sl(t)[e.weekday-1]}function hl(e,t){return rl(t)[e.month-1]}function gl(e,t){return fl(t)[e.year<0?0:1]}function _l(e,t,n=`always`,r=!1){let i={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.`]},a=[`hours`,`minutes`,`seconds`].indexOf(e)===-1;if(n===`auto`&&a){let n=e===`days`;switch(t){case 1:return n?`tomorrow`:`next ${i[e][0]}`;case-1:return n?`yesterday`:`last ${i[e][0]}`;case 0:return n?`today`:`this ${i[e][0]}`}}let o=Object.is(t,-0)||t<0,s=Math.abs(t),c=s===1,l=i[e],u=r?c?l[1]:l[2]||l[1]:c?i[e][0]:e;return o?`${s} ${u} ago`:`in ${s} ${u}`}function vl(e,t){let n=``;for(let r of e)r.literal?n+=r.val:n+=t(r.val);return n}var yl={D:Bo,DD:Vo,DDD:Uo,DDDD:Wo,t:Go,tt:Ko,ttt:qo,tttt:Jo,T:Yo,TT:Xo,TTT:Zo,TTTT:Qo,f:$o,ff:ts,fff:is,ffff:os,F:es,FF:ns,FFF:as,FFFF:ss},bl=class e{static create(t,n={}){return new e(t,n)}static parseFormat(e){let t=null,n=``,r=!1,i=[];for(let a=0;a<e.length;a++){let o=e.charAt(a);o===`'`?((n.length>0||r)&&i.push({literal:r||/^\s+$/.test(n),val:n===``?`'`:n}),t=null,n=``,r=!r):r||o===t?n+=o:(n.length>0&&i.push({literal:/^\s+$/.test(n),val:n}),n=o,t=o)}return n.length>0&&i.push({literal:r||/^\s+$/.test(n),val:n}),i}static macroTokenToFormatOpts(e){return yl[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,n=void 0){if(this.opts.forceSimple)return I(e,t);let r={...this.opts};return t>0&&(r.padTo=t),n&&(r.signDisplay=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(t,n){let r=this.loc.listingMode()===`en`,i=this.loc.outputCalendar&&this.loc.outputCalendar!==`gregory`,a=(e,n)=>this.loc.extract(t,e,n),o=e=>t.isOffsetFixed&&t.offset===0&&e.allowZ?`Z`:t.isValid?t.zone.formatOffset(t.ts,e.format):``,s=()=>r?pl(t):a({hour:`numeric`,hourCycle:`h12`},`dayperiod`),c=(e,n)=>r?hl(t,e):a(n?{month:e}:{month:e,day:`numeric`},`month`),l=(e,n)=>r?ml(t,e):a(n?{weekday:e}:{weekday:e,month:`long`,day:`numeric`},`weekday`),u=n=>{let r=e.macroTokenToFormatOpts(n);return r?this.formatWithSystemDefault(t,r):n},d=e=>r?gl(t,e):a({era:e},`era`);return vl(e.parseFormat(n),e=>{switch(e){case`S`:return this.num(t.millisecond);case`u`:case`SSS`:return this.num(t.millisecond,3);case`s`:return this.num(t.second);case`ss`:return this.num(t.second,2);case`uu`:return this.num(Math.floor(t.millisecond/10),2);case`uuu`:return this.num(Math.floor(t.millisecond/100));case`m`:return this.num(t.minute);case`mm`:return this.num(t.minute,2);case`h`:return this.num(t.hour%12==0?12:t.hour%12);case`hh`:return this.num(t.hour%12==0?12:t.hour%12,2);case`H`:return this.num(t.hour);case`HH`:return this.num(t.hour,2);case`Z`:return o({format:`narrow`,allowZ:this.opts.allowZ});case`ZZ`:return o({format:`short`,allowZ:this.opts.allowZ});case`ZZZ`:return o({format:`techie`,allowZ:this.opts.allowZ});case`ZZZZ`:return t.zone.offsetName(t.ts,{format:`short`,locale:this.loc.locale});case`ZZZZZ`:return t.zone.offsetName(t.ts,{format:`long`,locale:this.loc.locale});case`z`:return t.zoneName;case`a`:return s();case`d`:return i?a({day:`numeric`},`day`):this.num(t.day);case`dd`:return i?a({day:`2-digit`},`day`):this.num(t.day,2);case`c`:return this.num(t.weekday);case`ccc`:return l(`short`,!0);case`cccc`:return l(`long`,!0);case`ccccc`:return l(`narrow`,!0);case`E`:return this.num(t.weekday);case`EEE`:return l(`short`,!1);case`EEEE`:return l(`long`,!1);case`EEEEE`:return l(`narrow`,!1);case`L`:return i?a({month:`numeric`,day:`numeric`},`month`):this.num(t.month);case`LL`:return i?a({month:`2-digit`,day:`numeric`},`month`):this.num(t.month,2);case`LLL`:return c(`short`,!0);case`LLLL`:return c(`long`,!0);case`LLLLL`:return c(`narrow`,!0);case`M`:return i?a({month:`numeric`},`month`):this.num(t.month);case`MM`:return i?a({month:`2-digit`},`month`):this.num(t.month,2);case`MMM`:return c(`short`,!1);case`MMMM`:return c(`long`,!1);case`MMMMM`:return c(`narrow`,!1);case`y`:return i?a({year:`numeric`},`year`):this.num(t.year);case`yy`:return i?a({year:`2-digit`},`year`):this.num(t.year.toString().slice(-2),2);case`yyyy`:return i?a({year:`numeric`},`year`):this.num(t.year,4);case`yyyyyy`:return i?a({year:`numeric`},`year`):this.num(t.year,6);case`G`:return d(`short`);case`GG`:return d(`long`);case`GGGGG`:return d(`narrow`);case`kk`:return this.num(t.weekYear.toString().slice(-2),2);case`kkkk`:return this.num(t.weekYear,4);case`W`:return this.num(t.weekNumber);case`WW`:return this.num(t.weekNumber,2);case`n`:return this.num(t.localWeekNumber);case`nn`:return this.num(t.localWeekNumber,2);case`ii`:return this.num(t.localWeekYear.toString().slice(-2),2);case`iiii`:return this.num(t.localWeekYear,4);case`o`:return this.num(t.ordinal);case`ooo`:return this.num(t.ordinal,3);case`q`:return this.num(t.quarter);case`qq`:return this.num(t.quarter,2);case`X`:return this.num(Math.floor(t.ts/1e3));case`x`:return this.num(t.ts);default:return u(e)}})}formatDurationFromString(t,n){let r=this.opts.signMode===`negativeLargestOnly`?-1:1,i=e=>{switch(e[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}},a=(e,t)=>n=>{let a=i(n);if(a){let i=t.isNegativeDuration&&a!==t.largestUnit?r:1,o;return o=this.opts.signMode===`negativeLargestOnly`&&a!==t.largestUnit?`never`:this.opts.signMode===`all`?`always`:`auto`,this.num(e.get(a)*i,n.length,o)}else return n},o=e.parseFormat(n),s=o.reduce((e,{literal:t,val:n})=>t?e:e.concat(n),[]),c=t.shiftTo(...s.map(i).filter(e=>e));return vl(o,a(c,{isNegativeDuration:c<0,largestUnit:Object.keys(c.values)[0]}))}},xl=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Sl(...e){let t=e.reduce((e,t)=>e+t.source,``);return RegExp(`^${t}$`)}function Cl(...e){return t=>e.reduce(([e,n,r],i)=>{let[a,o,s]=i(t,r);return[{...e,...a},o||n,s]},[{},null,1]).slice(0,2)}function wl(e,...t){if(e==null)return[null,null];for(let[n,r]of t){let t=n.exec(e);if(t)return r(t)}return[null,null]}function Tl(...e){return(t,n)=>{let r={},i;for(i=0;i<e.length;i++)r[e[i]]=Lc(t[n+i]);return[r,null,n+i]}}var El=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Dl=`(?:${El.source}?(?:\\[(${xl.source})\\])?)?`,Ol=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,kl=RegExp(`${Ol.source}${Dl}`),Al=RegExp(`(?:[Tt]${kl.source})?`),jl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Ml=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Nl=/(\d{4})-?(\d{3})/,Pl=Tl(`weekYear`,`weekNumber`,`weekDay`),Fl=Tl(`year`,`ordinal`),Il=/(\d{4})-(\d\d)-(\d\d)/,Ll=RegExp(`${Ol.source} ?(?:${El.source}|(${xl.source}))?`),Rl=RegExp(`(?: ${Ll.source})?`);function zl(e,t,n){let r=e[t];return F(r)?n:Lc(r)}function Bl(e,t){return[{year:zl(e,t),month:zl(e,t+1,1),day:zl(e,t+2,1)},null,t+3]}function Vl(e,t){return[{hours:zl(e,t,0),minutes:zl(e,t+1,0),seconds:zl(e,t+2,0),milliseconds:zc(e[t+3])},null,t+4]}function Hl(e,t){let n=!e[t]&&!e[t+1],r=Yc(e[t+1],e[t+2]);return[{},n?null:Us.instance(r),t+3]}function Ul(e,t){return[{},e[t]?_s.create(e[t]):null,t+1]}var Wl=RegExp(`^T?${Ol.source}$`),Gl=/^-?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 Kl(e){let[t,n,r,i,a,o,s,c,l]=e,u=t[0]===`-`,d=c&&c[0]===`-`,f=(e,t=!1)=>e!==void 0&&(t||e&&u)?-e:e;return[{years:f(Rc(n)),months:f(Rc(r)),weeks:f(Rc(i)),days:f(Rc(a)),hours:f(Rc(o)),minutes:f(Rc(s)),seconds:f(Rc(c),c===`-0`),milliseconds:f(zc(l),d)}]}var ql={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Jl(e,t,n,r,i,a,o){let s={year:t.length===2?qc(Lc(t)):Lc(t),month:tl.indexOf(n)+1,day:Lc(r),hour:Lc(i),minute:Lc(a)};return o&&(s.second=Lc(o)),e&&(s.weekday=e.length>3?il.indexOf(e)+1:al.indexOf(e)+1),s}var Yl=/^(?:(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 Xl(e){let[,t,n,r,i,a,o,s,c,l,u,d]=e,f=Jl(t,i,r,n,a,o,s),p;return p=c?ql[c]:l?0:Yc(u,d),[f,new Us(p)]}function Zl(e){return e.replace(/\([^()]*\)|[\n\t]/g,` `).replace(/(\s\s+)/g,` `).trim()}var Ql=/^(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$/,$l=/^(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$/,eu=/^(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 tu(e){let[,t,n,r,i,a,o,s]=e;return[Jl(t,i,r,n,a,o,s),Us.utcInstance]}function nu(e){let[,t,n,r,i,a,o,s]=e;return[Jl(t,s,n,r,i,a,o),Us.utcInstance]}var ru=Sl(jl,Al),iu=Sl(Ml,Al),au=Sl(Nl,Al),ou=Sl(kl),su=Cl(Bl,Vl,Hl,Ul),cu=Cl(Pl,Vl,Hl,Ul),lu=Cl(Fl,Vl,Hl,Ul),uu=Cl(Vl,Hl,Ul);function du(e){return wl(e,[ru,su],[iu,cu],[au,lu],[ou,uu])}function fu(e){return wl(Zl(e),[Yl,Xl])}function pu(e){return wl(e,[Ql,tu],[$l,tu],[eu,nu])}function mu(e){return wl(e,[Gl,Kl])}var hu=Cl(Vl);function gu(e){return wl(e,[Wl,hu])}var _u=Sl(Il,Rl),vu=Sl(Ll),yu=Cl(Vl,Hl,Ul);function bu(e){return wl(e,[_u,su],[vu,yu])}var xu=`Invalid Duration`,Su={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}},Cu={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},...Su},wu=146097/400,Tu=146097/4800,Eu={years:{quarters:4,months:12,weeks:wu/7,days:wu,hours:wu*24,minutes:wu*24*60,seconds:wu*24*60*60,milliseconds:wu*24*60*60*1e3},quarters:{months:3,weeks:wu/28,days:wu/4,hours:wu*24/4,minutes:wu*24*60/4,seconds:wu*24*60*60/4,milliseconds:wu*24*60*60*1e3/4},months:{weeks:Tu/7,days:Tu,hours:Tu*24,minutes:Tu*24*60,seconds:Tu*24*60*60,milliseconds:Tu*24*60*60*1e3},...Su},Du=[`years`,`quarters`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`],Ou=Du.slice(0).reverse();function ku(e,t,n=!1){return new Nu({values:n?t.values:{...e.values,...t.values||{}},loc:e.loc.clone(t.loc),conversionAccuracy:t.conversionAccuracy||e.conversionAccuracy,matrix:t.matrix||e.matrix})}function Au(e,t){let n=t.milliseconds??0;for(let r of Ou.slice(1))t[r]&&(n+=t[r]*e[r].milliseconds);return n}function ju(e,t){let n=Au(e,t)<0?-1:1;Du.reduceRight((r,i)=>{if(F(t[i]))return r;if(r){let a=t[r]*n,o=e[i][r],s=Math.floor(a/o);t[i]+=s*n,t[r]-=s*o*n}return i},null),Du.reduce((n,r)=>{if(F(t[r]))return n;if(n){let i=t[n]%1;t[n]-=i,t[r]+=i*e[n][r]}return r},null)}function Mu(e){let t={};for(let[n,r]of Object.entries(e))r!==0&&(t[n]=r);return t}var Nu=class e{constructor(e){let t=e.conversionAccuracy===`longterm`||!1,n=t?Eu:Cu;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||N.create(),this.conversionAccuracy=t?`longterm`:`casual`,this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(t,n){return e.fromObject({milliseconds:t},n)}static fromObject(t,n={}){if(typeof t!=`object`||!t)throw new Io(`Duration.fromObject: argument expected to be an object, got ${t===null?`null`:typeof t}`);return new e({values:Zc(t,e.normalizeUnit),loc:N.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(t){if(wc(t))return e.fromMillis(t);if(e.isDuration(t))return t;if(typeof t==`object`)return e.fromObject(t);throw new Io(`Unknown duration argument ${t} of type ${typeof t}`)}static fromISO(t,n){let[r]=mu(t);return r?e.fromObject(r,n):e.invalid(`unparsable`,`the input "${t}" can't be parsed as ISO 8601`)}static fromISOTime(t,n){let[r]=gu(t);return r?e.fromObject(r,n):e.invalid(`unparsable`,`the input "${t}" can't be parsed as ISO 8601`)}static invalid(t,n=null){if(!t)throw new Io(`need to specify a reason the Duration is invalid`);let r=t instanceof sc?t:new sc(t,n);if(P.throwOnInvalid)throw new No(r);return new e({invalid:r})}static normalizeUnit(e){let t={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(!t)throw new Fo(e);return t}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,t={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?bl.create(this.loc,n).formatDurationFromString(this,e):xu}toHuman(e={}){if(!this.isValid)return xu;let t=e.showZeros!==!1,n=Du.map(n=>{let r=this.values[n];return F(r)||r===0&&!t?null:this.loc.numberFormatter({style:`unit`,unitDisplay:`long`,...e,unit:n.slice(0,-1)}).format(r)}).filter(e=>e);return this.loc.listFormatter({type:`conjunction`,style:e.listStyle||`narrow`,...e}).format(n)}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+=Bc(this.seconds+this.milliseconds/1e3,3)+`S`),e===`P`&&(e+=`T0S`),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:`extended`,...e,includeOffset:!1},R.fromMillis(t,{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?Au(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(t){if(!this.isValid)return this;let n=e.fromDurationLike(t),r={};for(let e of Du)(Nc(n.values,e)||Nc(this.values,e))&&(r[e]=n.get(e)+this.get(e));return ku(this,{values:r},!0)}minus(t){if(!this.isValid)return this;let n=e.fromDurationLike(t);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=Xc(e(this.values[n],n));return ku(this,{values:t},!0)}get(t){return this[e.normalizeUnit(t)]}set(t){if(!this.isValid)return this;let n={...this.values,...Zc(t,e.normalizeUnit)};return ku(this,{values:n})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:r}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:r,conversionAccuracy:n};return ku(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return ju(this.matrix,e),ku(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Mu(this.normalize().shiftToAll().toObject());return ku(this,{values:e},!0)}shiftTo(...t){if(!this.isValid||t.length===0)return this;t=t.map(t=>e.normalizeUnit(t));let n={},r={},i=this.toObject(),a;for(let e of Du)if(t.indexOf(e)>=0){a=e;let t=0;for(let n in r)t+=this.matrix[n][e]*r[n],r[n]=0;wc(i[e])&&(t+=i[e]);let o=Math.trunc(t);n[e]=o,r[e]=(t*1e3-o*1e3)/1e3}else wc(i[e])&&(r[e]=i[e]);for(let e in r)r[e]!==0&&(n[a]+=e===a?r[e]:r[e]/this.matrix[a][e]);return ju(this.matrix,n),ku(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo(`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return ku(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;let e=Mu(this.values);return ku(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 t(e,t){return e===void 0||e===0?t===void 0||t===0:e===t}for(let n of Du)if(!t(this.values[n],e.values[n]))return!1;return!0}},Pu=`Invalid Interval`;function Fu(e,t){return!e||!e.isValid?Iu.invalid(`missing or invalid start`):!t||!t.isValid?Iu.invalid(`missing or invalid end`):t<e?Iu.invalid(`end before start`,`The end of an interval must be after its start, but you had start=${e.toISO()} and end=${t.toISO()}`):null}var Iu=class e{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(t,n=null){if(!t)throw new Io(`need to specify a reason the Interval is invalid`);let r=t instanceof sc?t:new sc(t,n);if(P.throwOnInvalid)throw new Mo(r);return new e({invalid:r})}static fromDateTimes(t,n){let r=Rd(t),i=Rd(n);return Fu(r,i)??new e({start:r,end:i})}static after(t,n){let r=Nu.fromDurationLike(n),i=Rd(t);return e.fromDateTimes(i,i.plus(r))}static before(t,n){let r=Nu.fromDurationLike(n),i=Rd(t);return e.fromDateTimes(i.minus(r),i)}static fromISO(t,n){let[r,i]=(t||``).split(`/`,2);if(r&&i){let t,a;try{t=R.fromISO(r,n),a=t.isValid}catch{a=!1}let o,s;try{o=R.fromISO(i,n),s=o.isValid}catch{s=!1}if(a&&s)return e.fromDateTimes(t,o);if(a){let r=Nu.fromISO(i,n);if(r.isValid)return e.after(t,r)}else if(s){let t=Nu.fromISO(r,n);if(t.isValid)return e.before(o,t)}}return e.invalid(`unparsable`,`the input "${t}" 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`,t){if(!this.isValid)return NaN;let n=this.start.startOf(e,t),r;return r=t?.useLocaleWeeks?this.end.reconfigure({locale:n.locale}):this.end,r=r.startOf(e,t),Math.floor(r.diff(n,e).get(e))+(r.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:t,end:n}={}){return this.isValid?e.fromDateTimes(t||this.s,n||this.e):this}splitAt(...t){if(!this.isValid)return[];let n=t.map(Rd).filter(e=>this.contains(e)).sort((e,t)=>e.toMillis()-t.toMillis()),r=[],{s:i}=this,a=0;for(;i<this.e;){let t=n[a]||this.e,o=+t>+this.e?this.e:t;r.push(e.fromDateTimes(i,o)),i=o,a+=1}return r}splitBy(t){let n=Nu.fromDurationLike(t);if(!this.isValid||!n.isValid||n.as(`milliseconds`)===0)return[];let{s:r}=this,i=1,a,o=[];for(;r<this.e;){let t=this.start.plus(n.mapUnits(e=>e*i));a=+t>+this.e?this.e:t,o.push(e.fromDateTimes(r,a)),r=a,i+=1}return o}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(t){if(!this.isValid)return this;let n=this.s>t.s?this.s:t.s,r=this.e<t.e?this.e:t.e;return n>=r?null:e.fromDateTimes(n,r)}union(t){if(!this.isValid)return this;let n=this.s<t.s?this.s:t.s,r=this.e>t.e?this.e:t.e;return e.fromDateTimes(n,r)}static merge(e){let[t,n]=e.sort((e,t)=>e.s-t.s).reduce(([e,t],n)=>t?t.overlaps(n)||t.abutsStart(n)?[e,t.union(n)]:[e.concat([t]),n]:[e,n],[[],null]);return n&&t.push(n),t}static xor(t){let n=null,r=0,i=[],a=t.map(e=>[{time:e.s,type:`s`},{time:e.e,type:`e`}]),o=Array.prototype.concat(...a).sort((e,t)=>e.time-t.time);for(let t of o)r+=t.type===`s`?1:-1,r===1?n=t.time:(n&&+n!=+t.time&&i.push(e.fromDateTimes(n,t.time)),n=null);return e.merge(i)}difference(...t){return e.xor([this].concat(t)).map(e=>this.intersection(e)).filter(e=>e&&!e.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Pu}[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=Bo,t={}){return this.isValid?bl.create(this.s.loc.clone(t),e).formatInterval(this):Pu}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Pu}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Pu}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Pu}toFormat(e,{separator:t=` – `}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Pu}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):Nu.invalid(this.invalidReason)}mapEndpoints(t){return e.fromDateTimes(t(this.s),t(this.e))}},Lu=class{static hasDST(e=P.defaultZone){let t=R.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return _s.isValidZone(e)}static normalizeZone(e){return Gs(e,P.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||N.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||N.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||N.create(e)).getWeekendDays().slice()}static months(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null,outputCalendar:i=`gregory`}={}){return(r||N.create(t,n,i)).months(e)}static monthsFormat(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null,outputCalendar:i=`gregory`}={}){return(r||N.create(t,n,i)).months(e,!0)}static weekdays(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null}={}){return(r||N.create(t,n,null)).weekdays(e)}static weekdaysFormat(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null}={}){return(r||N.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return N.create(e).meridiems()}static eras(e=`short`,{locale:t=null}={}){return N.create(t,null,`gregory`).eras(e)}static features(){return{relative:Oc(),localeWeek:kc()}}};function Ru(e,t){let n=e=>e.toUTC(0,{keepLocalTime:!0}).startOf(`day`).valueOf(),r=n(t)-n(e);return Math.floor(Nu.fromMillis(r).as(`days`))}function zu(e,t,n){let r=[[`years`,(e,t)=>t.year-e.year],[`quarters`,(e,t)=>t.quarter-e.quarter+(t.year-e.year)*4],[`months`,(e,t)=>t.month-e.month+(t.year-e.year)*12],[`weeks`,(e,t)=>{let n=Ru(e,t);return(n-n%7)/7}],[`days`,Ru]],i={},a=e,o,s;for(let[c,l]of r)n.indexOf(c)>=0&&(o=c,i[c]=l(e,t),s=a.plus(i),s>t?(i[c]--,e=a.plus(i),e>t&&(s=e,i[c]--,e=a.plus(i))):e=s);return[e,i,s,o]}function Bu(e,t,n,r){let[i,a,o,s]=zu(e,t,n),c=t-i,l=n.filter(e=>[`hours`,`minutes`,`seconds`,`milliseconds`].indexOf(e)>=0);l.length===0&&(o<t&&(o=i.plus({[s]:1})),o!==i&&(a[s]=(a[s]||0)+c/(o-i)));let u=Nu.fromObject(a,r);return l.length>0?Nu.fromMillis(c,r).shiftTo(...l).plus(u):u}var Vu=`missing Intl.DateTimeFormat.formatToParts support`;function L(e,t=e=>e){return{regex:e,deser:([e])=>t(Ys(e))}}var Hu=`[ \xA0]`,Uu=new RegExp(Hu,`g`);function Wu(e){return e.replace(/\./g,`\\.?`).replace(Uu,Hu)}function Gu(e){return e.replace(/\./g,``).replace(Uu,` `).toLowerCase()}function Ku(e,t){return e===null?null:{regex:RegExp(e.map(Wu).join(`|`)),deser:([n])=>e.findIndex(e=>Gu(n)===Gu(e))+t}}function qu(e,t){return{regex:e,deser:([,e,t])=>Yc(e,t),groups:t}}function Ju(e){return{regex:e,deser:([e])=>e}}function Yu(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function Xu(e,t){let n=Qs(t),r=Qs(t,`{2}`),i=Qs(t,`{3}`),a=Qs(t,`{4}`),o=Qs(t,`{6}`),s=Qs(t,`{1,2}`),c=Qs(t,`{1,3}`),l=Qs(t,`{1,6}`),u=Qs(t,`{1,9}`),d=Qs(t,`{2,4}`),f=Qs(t,`{4,6}`),p=e=>({regex:RegExp(Yu(e.val)),deser:([e])=>e,literal:!0}),m=(m=>{if(e.literal)return p(m);switch(m.val){case`G`:return Ku(t.eras(`short`),0);case`GG`:return Ku(t.eras(`long`),0);case`y`:return L(l);case`yy`:return L(d,qc);case`yyyy`:return L(a);case`yyyyy`:return L(f);case`yyyyyy`:return L(o);case`M`:return L(s);case`MM`:return L(r);case`MMM`:return Ku(t.months(`short`,!0),1);case`MMMM`:return Ku(t.months(`long`,!0),1);case`L`:return L(s);case`LL`:return L(r);case`LLL`:return Ku(t.months(`short`,!1),1);case`LLLL`:return Ku(t.months(`long`,!1),1);case`d`:return L(s);case`dd`:return L(r);case`o`:return L(c);case`ooo`:return L(i);case`HH`:return L(r);case`H`:return L(s);case`hh`:return L(r);case`h`:return L(s);case`mm`:return L(r);case`m`:return L(s);case`q`:return L(s);case`qq`:return L(r);case`s`:return L(s);case`ss`:return L(r);case`S`:return L(c);case`SSS`:return L(i);case`u`:return Ju(u);case`uu`:return Ju(s);case`uuu`:return L(n);case`a`:return Ku(t.meridiems(),0);case`kkkk`:return L(a);case`kk`:return L(d,qc);case`W`:return L(s);case`WW`:return L(r);case`E`:case`c`:return L(n);case`EEE`:return Ku(t.weekdays(`short`,!1),1);case`EEEE`:return Ku(t.weekdays(`long`,!1),1);case`ccc`:return Ku(t.weekdays(`short`,!0),1);case`cccc`:return Ku(t.weekdays(`long`,!0),1);case`Z`:case`ZZ`:return qu(RegExp(`([+-]${s.source})(?::(${r.source}))?`),2);case`ZZZ`:return qu(RegExp(`([+-]${s.source})(${r.source})?`),2);case`z`:return Ju(/[a-z_+-/]{1,256}?/i);case` `:return Ju(/[^\S\n\r]/);default:return p(m)}})(e)||{invalidReason:Vu};return m.token=e,m}var Zu={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 Qu(e,t,n){let{type:r,value:i}=e;if(r===`literal`){let e=/^\s+$/.test(i);return{literal:!e,val:e?` `:i}}let a=t[r],o=r;r===`hour`&&(o=t.hour12==null?t.hourCycle==null?n.hour12?`hour12`:`hour24`:t.hourCycle===`h11`||t.hourCycle===`h12`?`hour12`:`hour24`:t.hour12?`hour12`:`hour24`);let s=Zu[o];if(typeof s==`object`&&(s=s[a]),s)return{literal:!1,val:s}}function $u(e){return[`^${e.map(e=>e.regex).reduce((e,t)=>`${e}(${t.source})`,``)}$`,e]}function ed(e,t,n){let r=e.match(t);if(r){let e={},t=1;for(let i in n)if(Nc(n,i)){let a=n[i],o=a.groups?a.groups+1:1;!a.literal&&a.token&&(e[a.token.val[0]]=a.deser(r.slice(t,t+o))),t+=o}return[r,e]}else return[r,{}]}function td(e){let t=e=>{switch(e){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}},n=null,r;return F(e.z)||(n=_s.create(e.z)),F(e.Z)||(n||=new Us(e.Z),r=e.Z),F(e.q)||(e.M=(e.q-1)*3+1),F(e.h)||(e.h<12&&e.a===1?e.h+=12:e.h===12&&e.a===0&&(e.h=0)),e.G===0&&e.y&&(e.y=-e.y),F(e.u)||(e.S=zc(e.u)),[Object.keys(e).reduce((n,r)=>{let i=t(r);return i&&(n[i]=e[r]),n},{}),n,r]}var nd=null;function rd(){return nd||=R.fromMillis(1555555555555),nd}function id(e,t){if(e.literal)return e;let n=ld(bl.macroTokenToFormatOpts(e.val),t);return n==null||n.includes(void 0)?e:n}function ad(e,t){return Array.prototype.concat(...e.map(e=>id(e,t)))}var od=class{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=ad(bl.parseFormat(t),e),this.units=this.tokens.map(t=>Xu(t,e)),this.disqualifyingUnit=this.units.find(e=>e.invalidReason),!this.disqualifyingUnit){let[e,t]=$u(this.units);this.regex=RegExp(e,`i`),this.handlers=t}}explainFromTokens(e){if(this.isValid){let[t,n]=ed(e,this.regex,this.handlers),[r,i,a]=n?td(n):[null,null,void 0];if(Nc(n,`a`)&&Nc(n,`H`))throw new Po(`Can't include meridiem when specifying 24-hour format`);return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:n,result:r,zone:i,specificOffset:a}}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 sd(e,t,n){return new od(e,n).explainFromTokens(t)}function cd(e,t,n){let{result:r,zone:i,specificOffset:a,invalidReason:o}=sd(e,t,n);return[r,i,a,o]}function ld(e,t){if(!e)return null;let n=bl.create(t,e).dtFormatter(rd()),r=n.formatToParts(),i=n.resolvedOptions();return r.map(t=>Qu(t,e,i))}var ud=`Invalid DateTime`,dd=864e13;function fd(e){return new sc(`unsupported zone`,`the zone "${e.name}" is not supported`)}function pd(e){return e.weekData===null&&(e.weekData=hc(e.c)),e.weekData}function md(e){return e.localWeekData===null&&(e.localWeekData=hc(e.c,e.loc.getMinDaysInFirstWeek(),e.loc.getStartOfWeek())),e.localWeekData}function hd(e,t){let n={ts:e.ts,zone:e.zone,c:e.c,o:e.o,loc:e.loc,invalid:e.invalid};return new R({...n,...t,old:n})}function gd(e,t,n){let r=e-t*60*1e3,i=n.offset(r);if(t===i)return[r,t];r-=(i-t)*60*1e3;let a=n.offset(r);return i===a?[r,i]:[e-Math.min(i,a)*60*1e3,Math.max(i,a)]}function _d(e,t){e+=t*60*1e3;let n=new Date(e);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function vd(e,t,n){return gd(Wc(e),t,n)}function yd(e,t){let n=e.o,r=e.c.year+Math.trunc(t.years),i=e.c.month+Math.trunc(t.months)+Math.trunc(t.quarters)*3,a={...e.c,year:r,month:i,day:Math.min(e.c.day,Uc(r,i))+Math.trunc(t.days)+Math.trunc(t.weeks)*7},o=Nu.fromObject({years:t.years-Math.trunc(t.years),quarters:t.quarters-Math.trunc(t.quarters),months:t.months-Math.trunc(t.months),weeks:t.weeks-Math.trunc(t.weeks),days:t.days-Math.trunc(t.days),hours:t.hours,minutes:t.minutes,seconds:t.seconds,milliseconds:t.milliseconds}).as(`milliseconds`),[s,c]=gd(Wc(a),n,e.zone);return o!==0&&(s+=o,c=e.zone.offset(s)),{ts:s,o:c}}function bd(e,t,n,r,i,a){let{setZone:o,zone:s}=n;if(e&&Object.keys(e).length!==0||t){let r=t||s,i=R.fromObject(e,{...n,zone:r,specificOffset:a});return o?i:i.setZone(s)}else return R.invalid(new sc(`unparsable`,`the input "${i}" can't be parsed as ${r}`))}function xd(e,t,n=!0){return e.isValid?bl.create(N.create(`en-US`),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(e,t):null}function Sd(e,t,n){let r=e.c.year>9999||e.c.year<0,i=``;if(r&&e.c.year>=0&&(i+=`+`),i+=I(e.c.year,r?6:4),n===`year`)return i;if(t){if(i+=`-`,i+=I(e.c.month),n===`month`)return i;i+=`-`}else if(i+=I(e.c.month),n===`month`)return i;return i+=I(e.c.day),i}function Cd(e,t,n,r,i,a,o){let s=!n||e.c.millisecond!==0||e.c.second!==0,c=``;switch(o){case`day`:case`month`:case`year`:break;default:if(c+=I(e.c.hour),o===`hour`)break;if(t){if(c+=`:`,c+=I(e.c.minute),o===`minute`)break;s&&(c+=`:`,c+=I(e.c.second))}else{if(c+=I(e.c.minute),o===`minute`)break;s&&(c+=I(e.c.second))}if(o===`second`)break;s&&(!r||e.c.millisecond!==0)&&(c+=`.`,c+=I(e.c.millisecond,3))}return i&&(e.isOffsetFixed&&e.offset===0&&!a?c+=`Z`:e.o<0?(c+=`-`,c+=I(Math.trunc(-e.o/60)),c+=`:`,c+=I(Math.trunc(-e.o%60))):(c+=`+`,c+=I(Math.trunc(e.o/60)),c+=`:`,c+=I(Math.trunc(e.o%60)))),a&&(c+=`[`+e.zone.ianaName+`]`),c}var wd={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Td={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Ed={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Dd=[`year`,`month`,`day`,`hour`,`minute`,`second`,`millisecond`],Od=[`weekYear`,`weekNumber`,`weekday`,`hour`,`minute`,`second`,`millisecond`],kd=[`year`,`ordinal`,`hour`,`minute`,`second`,`millisecond`];function Ad(e){let t={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`}[e.toLowerCase()];if(!t)throw new Fo(e);return t}function jd(e){switch(e.toLowerCase()){case`localweekday`:case`localweekdays`:return`localWeekday`;case`localweeknumber`:case`localweeknumbers`:return`localWeekNumber`;case`localweekyear`:case`localweekyears`:return`localWeekYear`;default:return Ad(e)}}function Md(e){if(Id===void 0&&(Id=P.now()),e.type!==`iana`)return e.offset(Id);let t=e.name,n=Ld.get(t);return n===void 0&&(n=e.offset(Id),Ld.set(t,n)),n}function Nd(e,t){let n=Gs(t.zone,P.defaultZone);if(!n.isValid)return R.invalid(fd(n));let r=N.fromObject(t),i,a;if(F(e.year))i=P.now();else{for(let t of Dd)F(e[t])&&(e[t]=wd[t]);let t=Sc(e)||Cc(e);if(t)return R.invalid(t);let r=Md(n);[i,a]=vd(e,r,n)}return new R({ts:i,zone:n,loc:r,o:a})}function Pd(e,t,n){let r=F(n.round)?!0:n.round,i=F(n.rounding)?`trunc`:n.rounding,a=(e,a)=>(e=Bc(e,r||n.calendary?0:2,n.calendary?`round`:i),t.loc.clone(n).relFormatter(n).format(e,a)),o=r=>n.calendary?t.hasSame(e,r)?0:t.startOf(r).diff(e.startOf(r),r).get(r):t.diff(e,r).get(r);if(n.unit)return a(o(n.unit),n.unit);for(let e of n.units){let t=o(e);if(Math.abs(t)>=1)return a(t,e)}return a(e>t?-0:0,n.units[n.units.length-1])}function Fd(e){let t={},n;return e.length>0&&typeof e[e.length-1]==`object`?(t=e[e.length-1],n=Array.from(e).slice(0,e.length-1)):n=Array.from(e),[t,n]}var Id,Ld=new Map,R=class e{constructor(e){let t=e.zone||P.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new sc(`invalid input`):null)||(t.isValid?null:fd(t));this.ts=F(e.ts)?P.now():e.ts;let r=null,i=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[r,i]=[e.old.c,e.old.o];else{let a=wc(e.o)&&!e.old?e.o:t.offset(this.ts);r=_d(this.ts,a),n=Number.isNaN(r.year)?new sc(`invalid input`):null,r=n?null:r,i=n?null:a}this._zone=t,this.loc=e.loc||N.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new e({})}static local(){let[e,t]=Fd(arguments),[n,r,i,a,o,s,c]=t;return Nd({year:n,month:r,day:i,hour:a,minute:o,second:s,millisecond:c},e)}static utc(){let[e,t]=Fd(arguments),[n,r,i,a,o,s,c]=t;return e.zone=Us.utcInstance,Nd({year:n,month:r,day:i,hour:a,minute:o,second:s,millisecond:c},e)}static fromJSDate(t,n={}){let r=Dc(t)?t.valueOf():NaN;if(Number.isNaN(r))return e.invalid(`invalid input`);let i=Gs(n.zone,P.defaultZone);return i.isValid?new e({ts:r,zone:i,loc:N.fromObject(n)}):e.invalid(fd(i))}static fromMillis(t,n={}){if(!wc(t))throw new Io(`fromMillis requires a numerical input, but received a ${typeof t} with value ${t}`);return t<-dd||t>dd?e.invalid(`Timestamp out of range`):new e({ts:t,zone:Gs(n.zone,P.defaultZone),loc:N.fromObject(n)})}static fromSeconds(t,n={}){if(wc(t))return new e({ts:t*1e3,zone:Gs(n.zone,P.defaultZone),loc:N.fromObject(n)});throw new Io(`fromSeconds requires a numerical input`)}static fromObject(t,n={}){t||={};let r=Gs(n.zone,P.defaultZone);if(!r.isValid)return e.invalid(fd(r));let i=N.fromObject(n),a=Zc(t,jd),{minDaysInFirstWeek:o,startOfWeek:s}=yc(a,i),c=P.now(),l=F(n.specificOffset)?r.offset(c):n.specificOffset,u=!F(a.ordinal),d=!F(a.year),f=!F(a.month)||!F(a.day),p=d||f,m=a.weekYear||a.weekNumber;if((p||u)&&m)throw new Po(`Can't mix weekYear/weekNumber units with year/month/day or ordinals`);if(f&&u)throw new Po(`Can't mix ordinal dates with month/day`);let h=m||a.weekday&&!p,g,_,v=_d(c,l);h?(g=Od,_=Td,v=hc(v,o,s)):u?(g=kd,_=Ed,v=_c(v)):(g=Dd,_=wd);let y=!1;for(let e of g){let t=a[e];F(t)?y?a[e]=_[e]:a[e]=v[e]:y=!0}let b=(h?bc(a,o,s):u?xc(a):Sc(a))||Cc(a);if(b)return e.invalid(b);let[x,ee]=vd(h?gc(a,o,s):u?vc(a):a,l,r),te=new e({ts:x,zone:r,o:ee,loc:i});return a.weekday&&p&&t.weekday!==te.weekday?e.invalid(`mismatched weekday`,`you can't specify both a weekday of ${a.weekday} and a date of ${te.toISO()}`):te.isValid?te:e.invalid(te.invalid)}static fromISO(e,t={}){let[n,r]=du(e);return bd(n,r,t,`ISO 8601`,e)}static fromRFC2822(e,t={}){let[n,r]=fu(e);return bd(n,r,t,`RFC 2822`,e)}static fromHTTP(e,t={}){let[n,r]=pu(e);return bd(n,r,t,`HTTP`,t)}static fromFormat(t,n,r={}){if(F(t)||F(n))throw new Io(`fromFormat requires an input string and a format`);let{locale:i=null,numberingSystem:a=null}=r,[o,s,c,l]=cd(N.fromOpts({locale:i,numberingSystem:a,defaultToEN:!0}),t,n);return l?e.invalid(l):bd(o,s,r,`format ${n}`,t,c)}static fromString(t,n,r={}){return e.fromFormat(t,n,r)}static fromSQL(e,t={}){let[n,r]=bu(e);return bd(n,r,t,`SQL`,e)}static invalid(t,n=null){if(!t)throw new Io(`need to specify a reason the DateTime is invalid`);let r=t instanceof sc?t:new sc(t,n);if(P.throwOnInvalid)throw new jo(r);return new e({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=ld(e,N.fromObject(t));return n?n.map(e=>e?e.val:null).join(``):null}static expandFormat(e,t={}){return ad(bl.parseFormat(e),N.fromObject(t)).map(e=>e.val).join(``)}static resetCache(){Id=void 0,Ld.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?pd(this).weekYear:NaN}get weekNumber(){return this.isValid?pd(this).weekNumber:NaN}get weekday(){return this.isValid?pd(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?md(this).weekday:NaN}get localWeekNumber(){return this.isValid?md(this).weekNumber:NaN}get localWeekYear(){return this.isValid?md(this).weekYear:NaN}get ordinal(){return this.isValid?_c(this.c).ordinal:NaN}get monthShort(){return this.isValid?Lu.months(`short`,{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Lu.months(`long`,{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Lu.weekdays(`short`,{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Lu.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];let e=864e5,t=6e4,n=Wc(this.c),r=this.zone.offset(n-e),i=this.zone.offset(n+e),a=this.zone.offset(n-r*t),o=this.zone.offset(n-i*t);if(a===o)return[this];let s=n-a*t,c=n-o*t,l=_d(s,a),u=_d(c,o);return l.hour===u.hour&&l.minute===u.minute&&l.second===u.second&&l.millisecond===u.millisecond?[hd(this,{ts:s}),hd(this,{ts:c})]:[this]}get isInLeapYear(){return Vc(this.year)}get daysInMonth(){return Uc(this.year,this.month)}get daysInYear(){return this.isValid?Hc(this.year):NaN}get weeksInWeekYear(){return this.isValid?Kc(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Kc(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:r}=bl.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(Us.instance(e),t)}toLocal(){return this.setZone(P.defaultZone)}setZone(t,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(t=Gs(t,P.defaultZone),t.equals(this.zone))return this;if(t.isValid){let e=this.ts;if(n||r){let n=t.offset(this.ts),r=this.toObject();[e]=vd(r,n,t)}return hd(this,{ts:e,zone:t})}else return e.invalid(fd(t))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return hd(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=Zc(e,jd),{minDaysInFirstWeek:n,startOfWeek:r}=yc(t,this.loc),i=!F(t.weekYear)||!F(t.weekNumber)||!F(t.weekday),a=!F(t.ordinal),o=!F(t.year),s=!F(t.month)||!F(t.day),c=o||s,l=t.weekYear||t.weekNumber;if((c||a)&&l)throw new Po(`Can't mix weekYear/weekNumber units with year/month/day or ordinals`);if(s&&a)throw new Po(`Can't mix ordinal dates with month/day`);let u;i?u=gc({...hc(this.c,n,r),...t},n,r):F(t.ordinal)?(u={...this.toObject(),...t},F(t.day)&&(u.day=Math.min(Uc(u.year,u.month),u.day))):u=vc({..._c(this.c),...t});let[d,f]=vd(u,this.o,this.zone);return hd(this,{ts:d,o:f})}plus(e){if(!this.isValid)return this;let t=Nu.fromDurationLike(e);return hd(this,yd(this,t))}minus(e){if(!this.isValid)return this;let t=Nu.fromDurationLike(e).negate();return hd(this,yd(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let n={},r=Nu.normalizeUnit(e);switch(r){case`years`:n.month=1;case`quarters`:case`months`:n.day=1;case`weeks`:case`days`:n.hour=0;case`hours`:n.minute=0;case`minutes`:n.second=0;case`seconds`:n.millisecond=0;break}if(r===`weeks`)if(t){let e=this.loc.getStartOfWeek(),{weekday:t}=this;t<e&&(n.weekNumber=this.weekNumber-1),n.weekday=e}else n.weekday=1;return r===`quarters`&&(n.month=(Math.ceil(this.month/3)-1)*3+1),this.set(n)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?bl.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):ud}toLocaleString(e=Bo,t={}){return this.isValid?bl.create(this.loc.clone(t),e).formatDateTime(this):ud}toLocaleParts(e={}){return this.isValid?bl.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e=`extended`,suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:r=!0,extendedZone:i=!1,precision:a=`milliseconds`}={}){if(!this.isValid)return null;a=Ad(a);let o=e===`extended`,s=Sd(this,o,a);return Dd.indexOf(a)>=3&&(s+=`T`),s+=Cd(this,o,t,n,r,i,a),s}toISODate({format:e=`extended`,precision:t=`day`}={}){return this.isValid?Sd(this,e===`extended`,Ad(t)):null}toISOWeekDate(){return xd(this,`kkkk-'W'WW-c`)}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:r=!1,extendedZone:i=!1,format:a=`extended`,precision:o=`milliseconds`}={}){return this.isValid?(o=Ad(o),(r&&Dd.indexOf(o)>=3?`T`:``)+Cd(this,a===`extended`,t,e,n,i,o)):null}toRFC2822(){return xd(this,`EEE, dd LLL yyyy HH:mm:ss ZZZ`,!1)}toHTTP(){return xd(this.toUTC(),`EEE, dd LLL yyyy HH:mm:ss 'GMT'`)}toSQLDate(){return this.isValid?Sd(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let r=`HH:mm:ss.SSS`;return(t||e)&&(n&&(r+=` `),t?r+=`z`:e&&(r+=`ZZ`)),xd(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ud}[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{};let t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t=`milliseconds`,n={}){if(!this.isValid||!e.isValid)return Nu.invalid(`created by diffing an invalid DateTime`);let r={locale:this.locale,numberingSystem:this.numberingSystem,...n},i=Ac(t).map(Nu.normalizeUnit),a=e.valueOf()>this.valueOf(),o=Bu(a?this:e,a?e:this,i,r);return a?o.negate():o}diffNow(t=`milliseconds`,n={}){return this.diff(e.now(),t,n)}until(e){return this.isValid?Iu.fromDateTimes(this,e):this}hasSame(e,t,n){if(!this.isValid)return!1;let r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,n)<=r&&r<=i.endOf(t,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(t={}){if(!this.isValid)return null;let n=t.base||e.fromObject({},{zone:this.zone}),r=t.padding?this<n?-t.padding:t.padding:0,i=[`years`,`months`,`days`,`hours`,`minutes`,`seconds`],a=t.unit;return Array.isArray(t.unit)&&(i=t.unit,a=void 0),Pd(n,this.plus(r),{...t,numeric:`always`,units:i,unit:a})}toRelativeCalendar(t={}){return this.isValid?Pd(t.base||e.fromObject({},{zone:this.zone}),this,{...t,numeric:`auto`,units:[`years`,`months`,`days`],calendary:!0}):null}static min(...t){if(!t.every(e.isDateTime))throw new Io(`min requires all arguments be DateTimes`);return jc(t,e=>e.valueOf(),Math.min)}static max(...t){if(!t.every(e.isDateTime))throw new Io(`max requires all arguments be DateTimes`);return jc(t,e=>e.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:r=null,numberingSystem:i=null}=n;return sd(N.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),e,t)}static fromStringExplain(t,n,r={}){return e.fromFormatExplain(t,n,r)}static buildFormatParser(e,t={}){let{locale:n=null,numberingSystem:r=null}=t;return new od(N.fromOpts({locale:n,numberingSystem:r,defaultToEN:!0}),e)}static fromFormatParser(t,n,r={}){if(F(t)||F(n))throw new Io(`fromFormatParser requires an input string and a format parser`);let{locale:i=null,numberingSystem:a=null}=r,o=N.fromOpts({locale:i,numberingSystem:a,defaultToEN:!0});if(!o.equals(n.locale))throw new Io(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);let{result:s,zone:c,specificOffset:l,invalidReason:u}=n.explainFromTokens(t);return u?e.invalid(u):bd(s,c,r,`format ${n.format}`,t,l)}static get DATE_SHORT(){return Bo}static get DATE_MED(){return Vo}static get DATE_MED_WITH_WEEKDAY(){return Ho}static get DATE_FULL(){return Uo}static get DATE_HUGE(){return Wo}static get TIME_SIMPLE(){return Go}static get TIME_WITH_SECONDS(){return Ko}static get TIME_WITH_SHORT_OFFSET(){return qo}static get TIME_WITH_LONG_OFFSET(){return Jo}static get TIME_24_SIMPLE(){return Yo}static get TIME_24_WITH_SECONDS(){return Xo}static get TIME_24_WITH_SHORT_OFFSET(){return Zo}static get TIME_24_WITH_LONG_OFFSET(){return Qo}static get DATETIME_SHORT(){return $o}static get DATETIME_SHORT_WITH_SECONDS(){return es}static get DATETIME_MED(){return ts}static get DATETIME_MED_WITH_SECONDS(){return ns}static get DATETIME_MED_WITH_WEEKDAY(){return rs}static get DATETIME_FULL(){return is}static get DATETIME_FULL_WITH_SECONDS(){return as}static get DATETIME_HUGE(){return os}static get DATETIME_HUGE_WITH_SECONDS(){return ss}};function Rd(e){if(R.isDateTime(e))return e;if(e&&e.valueOf&&wc(e.valueOf()))return R.fromJSDate(e);if(e&&typeof e==`object`)return R.fromObject(e);throw new Io(`Unknown datetime argument: ${e}, of type ${typeof e}`)}var zd=class{get prefix(){return``}push(e){}pop(){}popAndReturn(e){return e}async record(e,t){return await t()}recordSync(e,t){return t()}},Bd=e=>{let t=[],n=Vd(e),r=n.next();for(;r;)t.push(r),r=n.next();return t},Vd=e=>({...e,next:Hd(e)}),Hd=e=>{let t=e.start;return()=>{if(t==null)return null;let n=null;switch(e.granularity){case To.Total:n=Ud(t,e.end);break;case To.Annual:n=Wd(t,e.end);break;case To.SemiAnnual:n=Gd(t,e.end);break;case To.Quarterly:n=Kd(t,e.end);break;case To.Monthly:n=qd(t,e.end);break;case To.Weekly:n=Jd(t,e.end);break;case To.Daily:n=Yd(t,e.end);break;case To.Hourly:n=Xd(t,e.end)}return t=n===null?null:n.end.plus({milliseconds:1}),n}},Ud=(e,t)=>t<=e?null:{period:`total`,start:e,end:t},Wd=(e,t)=>{if(t<=e)return null;let n=e.toUTC();return{period:`annual`,start:e,end:R.utc(n.year,n.month,n.day).plus({years:1})}},Gd=(e,t)=>{if(t<=e)return null;let n=R.utc(e.year,7,1),r=R.utc(e.year,12,31,23,59,59,999),i;return i=n>e?n:r,i>t&&(i=t),{period:`semiAnnual`,start:e,end:i}},Kd=(e,t)=>{if(t<=e)return null;let n,r=e.toUTC(),i=r.month;return n=i<3?R.utc(r.year,4,1):i<6?R.utc(r.year,7,1):i<9?R.utc(r.year,10,1):R.utc(r.year,12,31,23,59,59,999),n>t&&(n=t),{period:`quarterly`,start:e,end:n}},qd=(e,t)=>{if(t<=e)return null;let n=e.toUTC(),r=R.utc(n.year,n.month,n.day).plus({months:1}).startOf(`month`);return r>t&&(e.hasSame(t,`month`)||(r=t)),{period:`monthly`,start:e,end:r}},Jd=(e,t)=>{if(t<=e)return null;let n=e.toUTC(),r=R.utc(n.year,n.month,n.day).plus({weeks:1}).startOf(`week`);return r>t&&!r.hasSame(t,`day`)?{period:`weekly`,start:e,end:t}:{period:`weekly`,start:e,end:r}},Yd=(e,t)=>{if(t<=e)return null;let n=e.toUTC().plus({days:1}).startOf(`day`);return(n>t||n.hasSame(t,`day`))&&(n=t),{period:`daily`,start:e,end:n}},Xd=(e,t)=>{if(t<=e)return null;let n=e.toUTC().plus({hours:1});return n>t&&e.hour!==t.hour&&(n=t.toUTC()),{period:`hourly`,start:e,end:n}},Zd=e=>Math.floor((e.month-1)/3)+1,Qd=class e{static discretize(e,t,n,r,i){let a=this._buildIndex(e,t),o=Bd(this._calculateRange(n,r,i,e)),s=this._discretizeNode(a,{},t,o);return this._groupResultsByPeriod(o,s)}static _calculateRange(e,t,n,r){let i=e||null,a=t||null;if(i==null||a==null)for(let e of r){i??=e.start;let t=e.end||e.start;(a==null||a<t)&&(a=t)}if(i==null||a==null)throw Error(`Cannot determine query start and/or end.`);return{start:i,end:a,granularity:n}}static _groupResultsByPeriod(t,n){let r={};for(let n of t){let t=n.start.toISO()+`-`+n.period;r[t]={period:e._getPeriodString(n),start:n.start,end:n.end,rows:[]}}for(let e of n)for(let t of Object.keys(e.series))r[t].rows.push({dimensions:e.dimensions,metric:e.metric,unit:e.unit==`__NULL__`?null:e.unit,value:e.series[t].inc,sum:e.series[t].sum});return Object.values(r)}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${Zd(e.start)}`;case`monthly`:let t=e.start.toUTC().month,n=t<10?`0${t}`:`${t}`;return`${e.start.year}/${n}`;case`weekly`:return`${e.start.weekYear}/W${e.start.weekNumber}`;case`daily`:let r=e.start.month,i=e.start.day,a=r<10?`0${r}`:`${r}`,o=i<10?`0${i}`:`${i}`;return`${e.start.year}/${a}/${o}`;case`hourly`:let s=e.start.month,c=e.start.day,l=e.start.hour,u=s<10?`0${s}`:`${s}`,d=c<10?`0${c}`:`${c}`,f=l<10?`0${l}`:`${l}`;return`${e.start.year}/${u}/${d}/${f}`;default:return e.period}}static _discretizeNode(e,t,n,r){let i=[];if(n.length>0){let a=n[0];Object.keys(e).forEach((o,s,c)=>{let l={...t};l[a]=o,i.push(...this._discretizeNode(e[o],l,n.slice(1),r))})}else Object.keys(e).forEach(n=>{i.push(...this._discretizeLeaf(e[n],r,n,t))});return i}static _discretizeLeaf(e,t,n,r){let i=[];return Object.keys(e).forEach(a=>{let o={};Object.keys(r).forEach(t=>{o[t]={path:e[a][0].dimensions[t],icon:e[a][0].dimensions.icon,label:e[a][0].dimensions.label,description:e[a][0].dimensions.description}}),i.push({unit:a,metric:n,dimensions:o,series:this._discretizeSeries(e[a],t)})}),i}static _discretizeSeries(e,t){let n={};for(let r of e){let e=this._getValue(r,t[0].start);for(let i of t){let t=this._getValue(r,i.end),a=`${i.start.toISO()}-${i.period}`;n[a]?(n[a].inc+=t-e,n[a].sum+=t):n[a]={inc:t-e,sum:t},e=t}}return n}static _getValue(e,t){switch(e.fn){case`Single`:return this._getSingleValue(e,t);case`DssVest`:return this._getVestValue(e,t);default:return 0}}static _getSingleValue(e,t){return t>=e.start?e.value:0}static _getVestValue(e,t){let n=t,r=e.start,i=e.end,a=e.params?.cliff?R.fromISO(e.params.cliff):null;if(n<r||a&&n<a)return 0;if(i&&n>=i)return e.value;let o=Iu.fromDateTimes(r,n),s=Iu.fromDateTimes(r,i||n);return o.length()/s.length()*e.value}static _buildIndex(e,t){let n={},r={},i=t[0]||``;for(let t of e){let e=t.dimensions[i];r[e]===void 0&&(r[e]=[]),r[e].push(t)}if(t.length>1){let e=t.slice(1);Object.keys(r).forEach(t=>{n[t]=this._buildIndex(r[t],e)})}else Object.keys(r).forEach(e=>{n[e]=this._buildMetricsIndex(r[e])});return n}static _buildMetricsIndex(e){let t={},n={};for(let t of e){let e=t.metric;n[e]===void 0&&(n[e]=[]),n[e].push(t)}return Object.keys(n).forEach(e=>t[e]=this._buildUnitIndex(n[e])),t}static _buildUnitIndex(e){let t={};for(let n of e){let e=n.unit||`__NULL__`;t[e]===void 0&&(t[e]=[]),t[e].push(n)}return t}},$d=class{_profiler;constructor(e,t){this._analyticsStore=e,this._profiler=t??new zd}async executeCompound(e){let t,n={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},r={start:e.start,end:e.end,granularity:e.granularity,lod:{priceData:1},select:{priceData:[Eo.fromString(`atlas`)]},metrics:[e.expression.operand.metric],currency:e.expression.operand.currency},i=await this.execute(n),a=await this.execute(r);return t=[wo.VectorAdd,wo.VectorSubtract].includes(e.expression.operator)?await this._profiler.record(`ApplyVectorOperator`,async()=>await this._applyVectorOperator(i,a,e.expression.operator,e.expression.resultCurrency)):await this._profiler.record(`ApplyScalarOperator`,async()=>await this._applyScalarOperator(i,a,e.expression.operator,e.expression.operand.useSum,e.expression.resultCurrency)),t}async execute(e){let t=await this._executeSeriesQuery(e),n=this._profiler.recordSync(`ApplyLODs`,()=>this._applyLods(t,e.lod)),r=Object.keys(e.select);return this._profiler.recordSync(`Discretize`,()=>n.length<1?[]:Qd.discretize(n,r,e.start,e.end,e.granularity))}async executeMultiCurrency(e,t){let n={...e,currency:t.targetCurrency??e.currency},r=await this.execute(n);for(let i of t.conversions){let a={start:e.start,end:e.end,granularity:e.granularity,lod:e.lod,select:e.select,expression:{inputs:{metrics:n.metrics,currency:i.currency},operator:wo.ScalarMultiply,operand:{metric:i.metric,currency:t.targetCurrency,useSum:!0},resultCurrency:t.targetCurrency}},o=await this.executeCompound(a);r=await this._applyVectorOperator(r,o,wo.VectorAdd,t.targetCurrency)}return r}_applyVectorOperator(e,t,n,r){if([wo.ScalarMultiply,wo.ScalarDivide].includes(n))throw Error(`Invalid operator for vector operation`);return Promise.resolve(t)}_applyScalarOperator(e,t,n,r,i){if([wo.VectorAdd,wo.VectorSubtract].includes(n))throw Error(`Invalid operator for scalar operation`);let a=[],o={},s=r?`sum`:`value`;for(let e of t)e.rows.length>0&&(o[e.period]=e.rows[0][s]);for(let t of e){let e={period:t.period,start:t.start,end:t.end,rows:t.rows.map(e=>({dimensions:e.dimensions,metric:e.metric,unit:i?i.toString():e.unit,value:this._calculateOutputValue(e.value,n,o[t.period]),sum:-1}))};a.push(e)}return Promise.resolve(a)}_calculateOutputValue(e,t,n){switch(t){case wo.VectorAdd:return e+n;case wo.VectorSubtract:return e-n;case wo.ScalarMultiply:return e*n;case wo.ScalarDivide:return e/n}}async _executeSeriesQuery(e){let t={start:e.start,end:e.end,select:e.select,metrics:e.metrics,currency:e.currency};return await this._analyticsStore.getMatchingSeries(t)}_applyLods(e,t){return e.map(e=>({...e,dimensions:this._applyDimensionsLods(e.dimensions,t)}))}_applyDimensionsLods(e,t){let n={};for(let[r,i]of Object.entries(t))i!==null&&e[r]&&(n[r]=e[r].path.applyLod(i).toString(),n.icon=e[r].icon.toString(),n.label=e[r].label.toString(),n.description=e[r].description.toString());return n}async getDimensions(){return await this._analyticsStore.getDimensions()}},ef=class extends Error{innerErrors;constructor(e){super(e.map(e=>e.message).join(`
|
|
235
|
+
`,r)}async getAuthorizationHeader(){if(this.config.jwtHandler)try{let 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,t){let n={"Content-Type":`application/json`},r=await this.getAuthorizationHeader();r&&(n.Authorization=r);let i=e.match(/(?:query|mutation)\s+(\w+)/)?.[1]??`unknown`;this.logger.verbose(`GQL request @channelId @operation @url vars=@variables`,this.channelId,i,this.config.url,JSON.stringify(t));let a=this.config.fetchFn??fetch,o;try{o=await a(this.config.url,{method:`POST`,headers:n,body:JSON.stringify({query:e,variables:t}),signal:this.abortController.signal})}catch(e){throw new xa(`GraphQL request failed: ${e instanceof Error?e.message:String(e)}`,`network`)}if(!o.ok)throw new xa(`GraphQL request failed: ${o.status} ${o.statusText}`,`http`,o.status);let s;try{s=await o.json()}catch(e){throw new xa(`Failed to parse GraphQL response: ${e instanceof Error?e.message:String(e)}`,`parse`)}if(this.logger.verbose(`GQL response @channelId @operation status=@status data=@data errors=@errors`,this.channelId,i,o.status,JSON.stringify(s.data),s.errors?JSON.stringify(s.errors):`none`),s.errors)throw new xa(`GraphQL errors: ${JSON.stringify(s.errors,null,2)}`,`graphql`);if(!s.data)throw new xa(`GraphQL response missing data field`,`missing-data`);return s.data}get poller(){return this.pollTimer}},Ka=class{logger;jwtHandler;queue;constructor(e,t,n){this.logger=e,this.jwtHandler=t,this.queue=n}instance(e,t,n,r,i,a,o,s){let c=n.parameters.url;if(typeof c!=`string`||!c)throw Error(`GqlRequestChannelFactory requires "url" parameter in config.parameters`);let l={url:c,collectionId:i,filter:a,jwtHandler:this.jwtHandler,retryBaseDelayMs:1e3,retryMaxDelayMs:3e5},u=2e3;if(n.parameters.pollIntervalMs!==void 0){if(typeof n.parameters.pollIntervalMs!=`number`)throw Error(`"pollIntervalMs" parameter must be a number`);u=n.parameters.pollIntervalMs}let d;if(n.parameters.retryBaseDelayMs!==void 0){if(typeof n.parameters.retryBaseDelayMs!=`number`)throw Error(`"retryBaseDelayMs" parameter must be a number`);d=n.parameters.retryBaseDelayMs}let f;if(n.parameters.retryMaxDelayMs!==void 0){if(typeof n.parameters.retryMaxDelayMs!=`number`)throw Error(`"retryMaxDelayMs" parameter must be a number`);f=n.parameters.retryMaxDelayMs}if(n.parameters.fetchFn!==void 0){if(typeof n.parameters.fetchFn!=`function`)throw Error(`"fetchFn" parameter must be a function`);l.fetchFn=n.parameters.fetchFn}d!==void 0&&(l.retryBaseDelayMs=d),f!==void 0&&(l.retryMaxDelayMs=f);let p;if(n.parameters.maxQueueDepth!==void 0){if(typeof n.parameters.maxQueueDepth!=`number`)throw Error(`"maxQueueDepth" parameter must be a number`);p=n.parameters.maxQueueDepth}let m;if(n.parameters.backpressureCheckIntervalMs!==void 0){if(typeof n.parameters.backpressureCheckIntervalMs!=`number`)throw Error(`"backpressureCheckIntervalMs" parameter must be a number`);m=n.parameters.backpressureCheckIntervalMs}let h=new La(this.queue,{intervalMs:u,...d!==void 0&&{retryBaseDelayMs:d},...f!==void 0&&{retryMaxDelayMs:f},...p!==void 0&&{maxQueueDepth:p},...m!==void 0&&{backpressureCheckIntervalMs:m},startPaused:s?.pollBehavior===ma.Manual});return new Ga(this.logger,e,t,r,l,o,h)}},qa=class{inbox;outbox;deadLetter;channelId;remoteName;cursorStorage;isShutdown;lastPersistedInboxOrdinal=0;lastPersistedOutboxOrdinal=0;connectionState=`connecting`;connectionStateCallbacks=new Set;constructor(e,t,n,r){this.logger=e,this.channelId=t,this.remoteName=n,this.cursorStorage=r,this.isShutdown=!1,this.inbox=new ya,this.outbox=new ya,this.deadLetter=new ya,this.outbox.onRemoved(e=>{let t=Wa(e);t>this.lastPersistedOutboxOrdinal&&(this.lastPersistedOutboxOrdinal=t,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:`outbox`,cursorOrdinal:t,lastSyncedAtUtcMs:Date.now()}).catch(e=>{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,e)}))}),this.inbox.onRemoved(e=>{let t=Wa(e);t>this.lastPersistedInboxOrdinal&&(this.lastPersistedInboxOrdinal=t,this.cursorStorage.upsert({remoteName:this.remoteName,cursorType:`inbox`,cursorOrdinal:t,lastSyncedAtUtcMs:Date.now()}).catch(e=>{this.logger.error(`Failed to update inbox cursor for @ChannelId! This is unlikely to cause a problem, but not-optimal: @Error`,this.channelId,e)}))})}shutdown(){return this.isShutdown=!0,this.transitionConnectionState(`disconnected`),Promise.resolve()}getConnectionState(){return{state:this.connectionState,failureCount:0,lastSuccessUtcMs:0,lastFailureUtcMs:0,pushBlocked:!1,pushFailureCount:0,receivingPages:!1}}onConnectionStateChange(e){return this.connectionStateCallbacks.add(e),()=>{this.connectionStateCallbacks.delete(e)}}triggerPull(){}transitionConnectionState(e){if(this.connectionState===e)return;this.connectionState=e;let t=this.getConnectionState();for(let e of this.connectionStateCallbacks)try{e(t)}catch(e){this.logger.error(`Connection state change callback error: @Error`,e)}}async init(){let e=await this.cursorStorage.list(this.remoteName),t=e.find(e=>e.cursorType===`inbox`)?.cursorOrdinal??0,n=e.find(e=>e.cursorType===`outbox`)?.cursorOrdinal??0;this.inbox.init(t),this.outbox.init(n),this.lastPersistedInboxOrdinal=t,this.lastPersistedOutboxOrdinal=n,this.transitionConnectionState(`connected`)}},Ja=class{logger;constructor(e){this.logger=e}instance(e,t,n,r){return new qa(this.logger,e,t,r)}};function Ya(e){return{remoteName:e.remote_name,cursorType:e.cursor_type,cursorOrdinal:Number(e.cursor_ordinal),lastSyncedAtUtcMs:e.last_synced_at_utc_ms?new Date(e.last_synced_at_utc_ms).getTime():void 0}}function Xa(e){return{remote_name:e.remoteName,cursor_type:e.cursorType,cursor_ordinal:BigInt(e.cursorOrdinal),last_synced_at_utc_ms:e.lastSyncedAtUtcMs?new Date(e.lastSyncedAtUtcMs).toISOString():null}}var Za=class{constructor(e){this.db=e}async list(e,t){if(t?.aborted)throw Error(`Operation aborted`);let n=await this.db.selectFrom(`sync_cursors`).selectAll().where(`remote_name`,`=`,e).execute();if(t?.aborted)throw Error(`Operation aborted`);return n.map(Ya)}async get(e,t,n){if(n?.aborted)throw Error(`Operation aborted`);let r=await this.db.selectFrom(`sync_cursors`).selectAll().where(`remote_name`,`=`,e).where(`cursor_type`,`=`,t).executeTakeFirst();if(n?.aborted)throw Error(`Operation aborted`);return r?Ya(r):{remoteName:e,cursorType:t,cursorOrdinal:0}}async upsert(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{let n=Xa(e);await t.insertInto(`sync_cursors`).values(n).onConflict(e=>e.columns([`remote_name`,`cursor_type`]).doUpdateSet({...n,updated_at:Ve`NOW()`})).execute()}),t?.aborted))throw Error(`Operation aborted`)}async remove(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_cursors`).where(`remote_name`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}};function Qa(e){return{id:e.id,jobId:e.job_id,jobDependencies:e.job_dependencies,remoteName:e.remote_name,documentId:e.document_id,scopes:e.scopes,branch:e.branch,operations:e.operations,errorSource:e.error_source,errorMessage:e.error_message}}function $a(e){return{id:e.id,job_id:e.jobId,job_dependencies:JSON.stringify(e.jobDependencies),remote_name:e.remoteName,document_id:e.documentId,scopes:JSON.stringify(e.scopes),branch:e.branch,operations:JSON.stringify(e.operations),error_source:e.errorSource,error_message:e.errorMessage}}var eo=class{constructor(e){this.db=e}async list(e,t,n){if(n?.aborted)throw Error(`Operation aborted`);let r=t?.cursor?parseInt(t.cursor):0,i=t?.limit||100,a=await this.db.selectFrom(`sync_dead_letters`).selectAll().where(`remote_name`,`=`,e).orderBy(`ordinal`,`desc`).offset(r).limit(i+1).execute(),o=!1,s=a;t?.limit&&a.length>i&&(o=!0,s=a.slice(0,i));let c=o?String(r+i):void 0,l=t?.cursor||`0`;if(n?.aborted)throw Error(`Operation aborted`);return{results:s.map(Qa),options:{cursor:l,limit:i},nextCursor:c}}async add(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{let n=$a(e);await t.insertInto(`sync_dead_letters`).values(n).onConflict(e=>e.column(`id`).doNothing()).execute()}),t?.aborted))throw Error(`Operation aborted`)}async remove(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_dead_letters`).where(`id`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}async removeByRemote(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_dead_letters`).where(`remote_name`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}async listQuarantinedDocumentIds(e){if(e?.aborted)throw Error(`Operation aborted`);let t=await this.db.selectFrom(`sync_dead_letters`).select(`document_id`).distinct().execute();if(e?.aborted)throw Error(`Operation aborted`);return t.map(e=>e.document_id)}};function to(e){return{id:e.channel_id,name:e.name,collectionId:Ae.fromKey(e.collection_id),channelConfig:{type:e.channel_type,parameters:e.channel_parameters??{}},filter:{documentId:e.filter_document_ids??[],scope:e.filter_scopes??[],branch:e.filter_branch},options:{sinceTimestampUtcMs:`0`},status:{push:{state:e.push_state,lastSuccessUtcMs:e.push_last_success_utc_ms?new Date(e.push_last_success_utc_ms).getTime():void 0,lastFailureUtcMs:e.push_last_failure_utc_ms?new Date(e.push_last_failure_utc_ms).getTime():void 0,failureCount:e.push_failure_count},pull:{state:e.pull_state,lastSuccessUtcMs:e.pull_last_success_utc_ms?new Date(e.pull_last_success_utc_ms).getTime():void 0,lastFailureUtcMs:e.pull_last_failure_utc_ms?new Date(e.pull_last_failure_utc_ms).getTime():void 0,failureCount:e.pull_failure_count}}}}function no(e){return{name:e.name,collection_id:e.collectionId.key,channel_type:e.channelConfig.type,channel_id:e.id,remote_name:e.name,channel_parameters:e.channelConfig.parameters,filter_document_ids:e.filter.documentId.length>0?e.filter.documentId:null,filter_scopes:e.filter.scope.length>0?e.filter.scope:null,filter_branch:e.filter.branch,push_state:e.status.push.state,push_last_success_utc_ms:e.status.push.lastSuccessUtcMs?new Date(e.status.push.lastSuccessUtcMs).toISOString():null,push_last_failure_utc_ms:e.status.push.lastFailureUtcMs?new Date(e.status.push.lastFailureUtcMs).toISOString():null,push_failure_count:e.status.push.failureCount,pull_state:e.status.pull.state,pull_last_success_utc_ms:e.status.pull.lastSuccessUtcMs?new Date(e.status.pull.lastSuccessUtcMs).toISOString():null,pull_last_failure_utc_ms:e.status.pull.lastFailureUtcMs?new Date(e.status.pull.lastFailureUtcMs).toISOString():null,pull_failure_count:e.status.pull.failureCount}}var ro=class{constructor(e){this.db=e}async list(e){if(e?.aborted)throw Error(`Operation aborted`);let t=await this.db.selectFrom(`sync_remotes`).selectAll().execute();if(e?.aborted)throw Error(`Operation aborted`);return t.map(to)}async get(e,t){if(t?.aborted)throw Error(`Operation aborted`);let n=await this.db.selectFrom(`sync_remotes`).selectAll().where(`name`,`=`,e).executeTakeFirst();if(t?.aborted)throw Error(`Operation aborted`);if(!n)throw Error(`Remote not found: ${e}`);return to(n)}async upsert(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{let n=no(e);await t.insertInto(`sync_remotes`).values(n).onConflict(e=>e.column(`name`).doUpdateSet({...n,updated_at:Ve`NOW()`})).execute()}),t?.aborted))throw Error(`Operation aborted`)}async remove(e,t){if(t?.aborted||(await this.db.transaction().execute(async t=>{await t.deleteFrom(`sync_remotes`).where(`name`,`=`,e).execute()}),t?.aborted))throw Error(`Operation aborted`)}},io=class{logger;driveContainerTypes;onBatchReady;queue=[];processing=!1;pendingBatches=new Map;constructor(e,t,n){this.logger=e,this.driveContainerTypes=t,this.onBatchReady=n}async enqueueWriteReady(e){this.queue.push(e),await this.processQueue()}async handleJobFailed(e){let t=e.job?.meta.batchId;if(!t)return;let n=this.pendingBatches.get(t);n&&(this.pendingBatches.delete(t),n.events.length>0&&await this.onBatchReady(this.prepareBatch(n.events)))}clear(){this.queue=[],this.pendingBatches.clear()}async processQueue(){if(!this.processing){this.processing=!0;try{for(;this.queue.length>0;){let e=this.queue.shift();try{await this.handleWriteReady(e)}catch(t){let n=t instanceof Error?t:Error(String(t));this.logger.error(`Failed to process write-ready event (@jobId, @error)`,e.jobId,n.message)}}}finally{this.processing=!1}}}async handleWriteReady(e){let{batchId:t,batchJobIds:n}=e.jobMeta;if(n.length<=1){await this.onBatchReady(this.prepareBatch([e]));return}let r=this.pendingBatches.get(t);r||(r={expectedJobIds:new Set(n),arrivedJobIds:new Set,events:[]},this.pendingBatches.set(t,r)),r.arrivedJobIds.add(e.jobId),r.events.push(e),r.arrivedJobIds.size>=r.expectedJobIds.size&&(this.pendingBatches.delete(t),await this.onBatchReady(this.prepareBatch(r.events)))}prepareBatch(e){let t=this.mergeCollectionMemberships(e),n=e.length>1,r=[],i=[];for(let t of e)i.push({event:t,jobDependencies:n?[...r]:[]}),n&&t.jobId&&r.push(t.jobId);return{collectionMemberships:t,entries:i}}mergeCollectionMemberships(e){let t={};for(let n of e){if(n.collectionMemberships)for(let[e,r]of Object.entries(n.collectionMemberships)){e in t||(t[e]=[]);for(let n of r)t[e].includes(n)||t[e].push(n)}for(let e of n.operations){let n=e.operation.action;if(n.type!==`ADD_RELATIONSHIP`||!this.driveContainerTypes.has(e.context.documentType))continue;let r=n.input;if(!r?.sourceId||!r.targetId)continue;let i=Ae.forDrive(r.sourceId,e.context.branch).key;r.targetId in t||(t[r.targetId]=[]),t[r.targetId].includes(i)||t[r.targetId].push(i)}}return t}},ao=class{completedResults=new Map;pendingWaiters=new Map;unsubscribers=[];isShutdown=!1;constructor(e){this.eventBus=e,this.subscribeToEvents()}waitForSync(e,t){if(t?.aborted)return Promise.reject(Error(`Operation aborted`));if(this.isShutdown)return Promise.reject(Error(`SyncAwaiter is shutdown`));let n=this.completedResults.get(e);return n?Promise.resolve(n):new Promise((n,r)=>{let i={resolve:n,reject:r,signal:t},a=this.pendingWaiters.get(e)||[];a.push(i),this.pendingWaiters.set(e,a),t&&t.addEventListener(`abort`,()=>{let t=this.pendingWaiters.get(e);if(t){let n=t.indexOf(i);n!==-1&&(t.splice(n,1),t.length===0&&this.pendingWaiters.delete(e),i.reject(Error(`Operation aborted`)))}},{once:!0})})}shutdown(){this.isShutdown=!0;for(let e of this.unsubscribers)e();this.unsubscribers.length=0;for(let[,e]of this.pendingWaiters)for(let t of e)t.reject(Error(`SyncAwaiter shutdown`));this.pendingWaiters.clear()}subscribeToEvents(){this.unsubscribers.push(this.eventBus.subscribe(_a.SYNC_SUCCEEDED,(e,t)=>{this.handleSyncSucceeded(t)})),this.unsubscribers.push(this.eventBus.subscribe(_a.SYNC_FAILED,(e,t)=>{this.handleSyncFailed(t)}))}handleSyncSucceeded(e){let t={jobId:e.jobId,status:`succeeded`,syncOperationCount:e.syncOperationCount,successCount:e.syncOperationCount,failureCount:0,errors:[]};this.completedResults.set(e.jobId,t),this.resolveWaiters(e.jobId,t)}handleSyncFailed(e){let t={jobId:e.jobId,status:`failed`,syncOperationCount:e.successCount+e.failureCount,successCount:e.successCount,failureCount:e.failureCount,errors:e.errors};this.completedResults.set(e.jobId,t),this.resolveWaiters(e.jobId,t)}resolveWaiters(e,t){let n=this.pendingWaiters.get(e);if(!(!n||n.length===0)){this.pendingWaiters.delete(e);for(let e of n)e.signal?.aborted?e.reject(Error(`Operation aborted`)):e.resolve(t)}}},oo=function(e){return e.Synced=`SYNCED`,e.Outgoing=`OUTGOING`,e.Incoming=`INCOMING`,e.OutgoingAndIncoming=`OUTGOING_AND_INCOMING`,e.Error=`ERROR`,e}({}),so=class{remotes=new Map;seen=new Set;callbacks=new Set;getStatus(e){if(!this.seen.has(e))return;let t=0,n=0,r=0;for(let i of this.remotes.values()){let a=i.get(e);a&&(t+=a.inboxCount,n+=a.outboxCount,r+=a.errorCount)}return co(t,n,r)}onChange(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e)}}trackRemote(e,t){this.remotes.set(e,new Map),t.inbox.onAdded(t=>this.handleAdded(e,`inbox`,t)),t.inbox.onRemoved(t=>this.handleRemoved(e,`inbox`,t)),t.outbox.onAdded(t=>this.handleAdded(e,`outbox`,t)),t.outbox.onRemoved(t=>this.handleRemoved(e,`outbox`,t)),t.deadLetter.onAdded(t=>this.handleAdded(e,`deadLetter`,t))}untrackRemote(e){let t=this.remotes.get(e);if(!t)return;let n=[...t.keys()];this.remotes.delete(e);for(let e of n)this.notifyChange(e)}clear(){this.remotes.clear(),this.seen.clear(),this.callbacks.clear()}handleAdded(e,t,n){let r=new Set;for(let i of n){if(t===`inbox`&&!i.remoteName)continue;let n=this.getOrCreateCounts(e,i.documentId);this.seen.add(i.documentId),t===`inbox`?n.inboxCount++:t===`outbox`?n.outboxCount++:n.errorCount++,r.add(i.documentId)}for(let e of r)this.notifyChange(e)}handleRemoved(e,t,n){let r=new Set;for(let i of n){let n=this.getOrCreateCounts(e,i.documentId);t===`inbox`?n.inboxCount=Math.max(0,n.inboxCount-1):t===`outbox`&&(n.outboxCount=Math.max(0,n.outboxCount-1)),r.add(i.documentId)}for(let e of r)this.notifyChange(e)}getOrCreateCounts(e,t){let n=this.remotes.get(e);n||(n=new Map,this.remotes.set(e,n));let r=n.get(t);return r||(r={inboxCount:0,outboxCount:0,errorCount:0},n.set(t,r)),r}notifyChange(e){let t=this.getStatus(e);if(t!==void 0)for(let n of[...this.callbacks])n(e,t)}};function co(e,t,n){return n>0?oo.Error:e>0&&t>0?oo.OutgoingAndIncoming:e>0?oo.Incoming:t>0?oo.Outgoing:oo.Synced}var lo=function(e){return e.Backfill=`backfill`,e.BatchTriggered=`batch-triggered`,e}(lo||{}),uo={maxDeadLettersPerRemote:100,maxInboxBatchSize:32},fo=1e4,po=class{logger;remoteStorage;cursorStorage;deadLetterStorage;channelFactory;operationIndex;reactor;eventBus;remotes;awaiter;syncAwaiter;abortController=new AbortController;isShutdown;eventUnsubscribe;failedEventUnsubscribe;batchAggregator;syncStatusTracker;config;connectionStateUnsubscribes=new Map;quarantinedDocumentIds=new Set;backfillAbortControllers=new Map;planKeyToJobUuid=new Map;lastEnqueuedJobIdByKey=new Map;inboxChunkChain=Promise.resolve();constructor(e,t,n,r,i,a,o,s,c,l={}){this.logger=e,this.remoteStorage=t,this.cursorStorage=n,this.deadLetterStorage=r,this.channelFactory=i,this.operationIndex=a,this.reactor=o,this.eventBus=s,this.config={...uo,...l},this.remotes=new Map,this.awaiter=new ji(s,(e,t)=>o.getJobStatus(e,t)),this.syncAwaiter=new ao(s),this.isShutdown=!1,this.batchAggregator=new io(e,c,e=>this.processCompleteBatch(e)),this.syncStatusTracker=new so}async startup(){if(this.isShutdown)throw Error(`SyncManager is already shutdown and cannot be started`);try{let e=await this.deadLetterStorage.listQuarantinedDocumentIds();for(let t of e)this.quarantinedDocumentIds.add(t)}catch(e){this.logger.error(`Failed to load quarantined document IDs (@error)`,e instanceof Error?e.message:String(e))}let e=await this.remoteStorage.list();for(let t of e){let e=this.channelFactory.instance(t.id,t.name,t.channelConfig,this.cursorStorage,t.collectionId,t.filter,this.operationIndex,t.options),n={id:t.id,name:t.name,collectionId:t.collectionId,filter:t.filter,options:t.options,channel:e};this.remotes.set(t.name,n),await this.loadDeadLetters(n),this.wireChannelCallbacks(n);try{await e.init()}catch(e){this.logger.error(`Error initializing channel for remote (@name, @error)`,t.name,e instanceof Error?e.message:String(e)),this.remotes.delete(t.name);continue}let r=n.channel.outbox.ackOrdinal;if(r>0){let e=new AbortController;this.backfillAbortControllers.set(t.name,e),this.updateOutbox(n,r,lo.Backfill,e.signal).catch(t=>{e.signal.aborted||this.logger.error(`Backfill failed for remote @RemoteName: @Error`,n.name,t instanceof Error?t:Error(String(t)))}).finally(()=>{this.backfillAbortControllers.delete(t.name)})}}this.eventUnsubscribe=this.eventBus.subscribe(w.JOB_WRITE_READY,async(e,t)=>this.batchAggregator.enqueueWriteReady(t)),this.failedEventUnsubscribe=this.eventBus.subscribe(w.JOB_FAILED,async(e,t)=>this.batchAggregator.handleJobFailed(t))}shutdown(){this.isShutdown=!0,this.abortController.abort();for(let e of this.backfillAbortControllers.values())e.abort();this.backfillAbortControllers.clear(),this.planKeyToJobUuid.clear(),this.lastEnqueuedJobIdByKey.clear(),this.batchAggregator.clear(),this.eventUnsubscribe&&=(this.eventUnsubscribe(),void 0),this.failedEventUnsubscribe&&=(this.failedEventUnsubscribe(),void 0),this.awaiter.shutdown(),this.syncAwaiter.shutdown(),this.syncStatusTracker.clear();for(let e of this.connectionStateUnsubscribes.values())e();this.connectionStateUnsubscribes.clear();let e=[];for(let t of this.remotes.values())e.push(t.channel.shutdown());return this.remotes.clear(),{isShutdown:!0,completed:Promise.all(e).then(()=>void 0)}}getByName(e){let t=this.remotes.get(e);if(!t)throw Error(`Remote with name '${e}' does not exist`);return t}getById(e){for(let t of this.remotes.values())if(t.id===e)return t;throw Error(`Remote with id '${e}' does not exist`)}async add(e,t,n,r={documentId:[],scope:[],branch:``},i={sinceTimestampUtcMs:`0`},a){if(this.isShutdown)throw Error(`SyncManager is shutdown and cannot add remotes`);if(this.remotes.has(e))throw Error(`Remote with name '${e}' already exists`);this.logger.debug(`Adding remote (@name, @collectionId, @channelConfig, @filter, @options, @id)`,e,t.key,n,r,i,a);let o=a??crypto.randomUUID(),s={id:o,name:e,collectionId:t,channelConfig:n,filter:r,options:i,status:{push:Oa(),pull:Oa()}};await this.remoteStorage.upsert(s);let c=this.channelFactory.instance(o,e,n,this.cursorStorage,t,r,this.operationIndex,i),l={id:o,name:e,collectionId:t,filter:r,options:i,channel:c};this.remotes.set(e,l),await this.loadDeadLetters(l),this.wireChannelCallbacks(l);try{await c.init()}catch(t){throw this.remotes.delete(e),await this.remoteStorage.remove(e),t}let u=new AbortController;return this.backfillAbortControllers.set(e,u),this.updateOutbox(l,0,lo.Backfill,u.signal).catch(e=>{u.signal.aborted||this.logger.error(`Backfill failed for remote @RemoteName: @Error`,l.name,e instanceof Error?e:Error(String(e)))}).finally(()=>{this.backfillAbortControllers.delete(e)}),l}triggerPull(e){let t=this.remotes.get(e);if(!t)throw Error(`Remote with name '${e}' does not exist`);t.channel.triggerPull()}async remove(e){let t=this.remotes.get(e);if(!t)throw Error(`Remote with name '${e}' does not exist`);let n=this.backfillAbortControllers.get(e);n&&(n.abort(),this.backfillAbortControllers.delete(e)),await t.channel.shutdown(),await this.remoteStorage.remove(e),await this.cursorStorage.remove(e),this.syncStatusTracker.untrackRemote(e);let r=this.connectionStateUnsubscribes.get(e);r&&(r(),this.connectionStateUnsubscribes.delete(e)),this.remotes.delete(e)}list(){return Array.from(this.remotes.values())}waitForSync(e,t){return this.syncAwaiter.waitForSync(e,t)}getSyncStatus(e){return this.syncStatusTracker.getStatus(e)}onSyncStatusChange(e){return this.syncStatusTracker.onChange(e)}recordPlanKeyMapping(e,t){if(!this.planKeyToJobUuid.has(e)&&this.planKeyToJobUuid.size>=fo){let e=this.planKeyToJobUuid.keys().next().value;e!==void 0&&this.planKeyToJobUuid.delete(e)}this.planKeyToJobUuid.set(e,t)}wireChannelCallbacks(e){e.channel.inbox.onAdded(t=>this.handleInboxAdded(e,t)),this.syncStatusTracker.trackRemote(e.name,e.channel);let t=e.channel.onConnectionStateChange(t=>{this.eventBus.emit(_a.CONNECTION_STATE_CHANGED,{remoteName:e.name,remoteId:e.id,previous:t.state,current:t.state,snapshot:t}).catch(()=>{})});this.connectionStateUnsubscribes.set(e.name,t),e.channel.deadLetter.onAdded(t=>{for(let n of t){this.logger.error(`Dead letter (@remote, @documentId, @jobId, @error, @dependencies)`,e.name,n.documentId,n.jobId,n.error?.message??`unknown`,n.jobDependencies),this.quarantinedDocumentIds.add(n.documentId);let t={id:n.id,jobId:n.jobId,jobDependencies:n.jobDependencies,remoteName:n.remoteName,documentId:n.documentId,scopes:n.scopes,branch:n.branch,operations:n.operations,errorSource:n.error?.source??ga.None,errorMessage:n.error?.error.message??`unknown`};this.deadLetterStorage.add(t).catch(e=>{this.logger.error(`Failed to persist dead letter (@id, @error)`,t.id,e instanceof Error?e.message:String(e))}),this.eventBus.emit(_a.DEAD_LETTER_ADDED,{id:t.id,jobId:t.jobId,remoteName:t.remoteName,documentId:t.documentId,errorSource:t.errorSource}).catch(()=>{})}let n=e.channel.deadLetter.items;if(n.length>this.config.maxDeadLettersPerRemote){let t=n.length-this.config.maxDeadLettersPerRemote,r=n.slice(0,t);e.channel.deadLetter.remove(...r)}})}async loadDeadLetters(e){let t;try{t=(await this.deadLetterStorage.list(e.name,{cursor:`0`,limit:this.config.maxDeadLettersPerRemote})).results}catch(t){this.logger.error(`Failed to load dead letters for remote (@name, @error)`,e.name,t instanceof Error?t.message:String(t));return}if(t.length===0)return;t.reverse();let n=[];for(let e of t){let t=new wa(e.id,e.jobId,e.jobDependencies,e.remoteName,e.documentId,e.scopes,e.branch,e.operations);t.failed(new Sa(e.errorSource,Error(e.errorMessage))),n.push(t)}e.channel.deadLetter.add(...n),this.logger.debug(`Loaded @count persisted dead letters for remote @name`,t.length,e.name)}getRemotesForCollection(e){return Array.from(this.remotes.values()).filter(t=>t.collectionId.key===e)}async processCompleteBatch(e){if(this.isShutdown)return;let t=[...new Set(Object.values(e.collectionMemberships).flatMap(e=>e))],n=[];for(let e of t){let t=this.getRemotesForCollection(e);for(let e of t)n.includes(e)||n.push(e)}for(let t of n)Ta(t.channel.inbox,e);for(let e of n)await this.updateOutbox(e,e.channel.outbox.latestOrdinal,lo.BatchTriggered)}handleInboxAdded(e,t){if(this.isShutdown)return;let n=t.filter(e=>!this.quarantinedDocumentIds.has(e.documentId));if(n.length===0)return;let r=[],i=[];for(let e of n)e.jobId?r.push(e):i.push(e);for(let t of i)this.applyInboxJob(e,t);if(r.length>0){let t=Na(r.map(t=>({remote:e,syncOp:t})),this.config.maxInboxBatchSize);this.processInboxChunks(t)}}processInboxChunks(e){let t=this.inboxChunkChain.then(async()=>{for(let t of e){if(this.isShutdown)return;await this.applyInboxBatch(t)}});return this.inboxChunkChain=t.catch(e=>{this.logger.error(`Inbox chunk processing failed (@error)`,e instanceof Error?e.message:String(e))}),t}async applyInboxJob(e,t){let n=t.operations.map(e=>e.operation),r;try{r=await this.reactor.load(t.documentId,t.branch,n,this.abortController.signal,{sourceRemote:e.name})}catch(n){if(this.isShutdown)return;let r=n instanceof Error?n:Error(String(n));this.logger.error(`Failed to load operations from inbox (@remote, @documentId, @error)`,e.name,t.documentId,r.message);let i=new Sa(ga.Inbox,r);t.failed(i),e.channel.deadLetter.add(t),e.channel.inbox.remove(t);return}let i;try{i=await this.awaiter.waitForJob(r.id,this.abortController.signal)}catch(n){if(this.isShutdown)return;let i=n instanceof Error?n:Error(String(n));this.logger.error(`Failed to wait for job completion (@remote, @documentId, @jobId, @error)`,e.name,t.documentId,r.id,i.message);let a=new Sa(ga.Inbox,i);t.failed(a),e.channel.deadLetter.add(t),e.channel.inbox.remove(t);return}if(!this.isShutdown){if(i.status===A.FAILED){let n=i.error?.message||`Unknown error`;this.logger.error(`Failed to apply operations from inbox (@remote, @documentId, @jobId, @error)`,e.name,t.documentId,i.id,n);let r=new Sa(ga.Inbox,Error(`Failed to apply operations: ${n}`));t.failed(r),e.channel.deadLetter.add(t)}else t.executed();e.channel.inbox.remove(t)}}async applyInboxBatch(e){let t=e[0].remote.name,n=new Set(e.map(({syncOp:e})=>e.jobId)),r=e.map(({syncOp:e})=>{let t=[],r=[];for(let i of e.jobDependencies)if(i)if(n.has(i))t.push(i);else{let e=this.planKeyToJobUuid.get(i);e!==void 0&&r.push(e)}let i=`${e.documentId}:${e.scopes[0]}:${e.branch}`,a=this.lastEnqueuedJobIdByKey.get(i);return a!==void 0&&r.push(a),{key:e.jobId,documentId:e.documentId,scope:e.scopes[0],branch:e.branch,operations:e.operations.map(e=>e.operation),dependsOn:t,externalDeps:r}}),i={jobs:r},a;try{a=await this.reactor.loadBatch(i,this.abortController.signal,{sourceRemote:t})}catch(t){if(this.isShutdown)return;for(let{remote:n,syncOp:r}of e){let e=t instanceof Error?t:Error(String(t));r.failed(new Sa(ga.Inbox,e)),n.channel.deadLetter.add(r),n.channel.inbox.remove(r)}return}if(!this.isShutdown){for(let e of r){if(!(e.key in a.jobs))continue;let t=a.jobs[e.key];this.recordPlanKeyMapping(e.key,t.id);let n=`${e.documentId}:${e.scope}:${e.branch}`;this.lastEnqueuedJobIdByKey.set(n,t.id)}for(let{remote:t,syncOp:n}of e){if(!(n.jobId in a.jobs)){this.logger.error(`Job key missing from batch load result (@remote, @documentId, @jobId)`,t.name,n.documentId,n.jobId);let e=new Sa(ga.Inbox,Error(`Job key '${n.jobId}' missing from batch load result`));n.failed(e),t.channel.deadLetter.add(n),t.channel.inbox.remove(n);continue}let e=a.jobs[n.jobId],r;try{r=await this.awaiter.waitForJob(e.id,this.abortController.signal)}catch(e){if(this.isShutdown)continue;let r=e instanceof Error?e:Error(String(e));n.failed(new Sa(ga.Inbox,r)),t.channel.deadLetter.add(n),t.channel.inbox.remove(n);continue}if(this.isShutdown)return;if(r.status===A.FAILED){let e=r.error?.message||`Unknown error`,i=new Sa(ga.Inbox,Error(`Failed to apply operations: ${e}`));n.failed(i),t.channel.deadLetter.add(n)}else n.executed();t.channel.inbox.remove(n)}}}async updateOutbox(e,t,n=lo.Backfill,r){let i=r?AbortSignal.any([r,this.abortController.signal]):this.abortController.signal,a=t,o=new Map,s,c=e.options.sinceTimestampUtcMs,l=t=>{if(t.length===0)return;let r=ka(t),i=[];for(let t of r){let r=crypto.randomUUID(),a=o.get(t.documentId),c=[];a&&c.push(a),n===lo.BatchTriggered&&s&&s!==a&&c.push(s);let l=new wa(crypto.randomUUID(),r,c,e.name,t.documentId,[t.scope],t.branch,t.operations);i.push(l),o.set(t.documentId,r),n===lo.BatchTriggered&&(s=r)}e.channel.outbox.add(...i)},u=await this.operationIndex.find(e.collectionId.key,t,{excludeSourceRemote:e.name},void 0,i),d=[],f;do{if(i.aborted)return;for(let e of u.results)a=Math.max(a,e.ordinal??0);let t=u.results.map(e=>ja(e));if(d.length>0&&(t=[...d,...t],d=[]),c&&c!==`0`&&(t=t.filter(e=>e.operation.timestampUtcMs>=c)),t=Da(t,e.filter),t=t.filter(e=>!this.quarantinedDocumentIds.has(e.context.documentId)),f=!!u.next,t.length>0)if(t.sort((e,t)=>e.context.documentId===t.context.documentId?e.context.scope===t.context.scope?e.context.ordinal-t.context.ordinal:e.context.scope<t.context.scope?-1:1:e.context.documentId<t.context.documentId?-1:1),f){let e=Aa(t);d=e.carry,l(e.emit)}else l(t);f&&(u=await u.next())}while(f);d.length>0&&l(d),e.channel.outbox.advanceOrdinal(a)}},mo=class{channelFactory;remoteStorage;cursorStorage;deadLetterStorage;config={};withChannelFactory(e){return this.channelFactory=e,this}withRemoteStorage(e){return this.remoteStorage=e,this}withCursorStorage(e){return this.cursorStorage=e,this}withDeadLetterStorage(e){return this.deadLetterStorage=e,this}withMaxDeadLettersPerRemote(e){return this.config.maxDeadLettersPerRemote=e,this}withMaxInboxBatchSize(e){return this.config.maxInboxBatchSize=e,this}build(e,t,n,r,i,a){return this.buildModule(e,t,n,r,i,a).syncManager}buildModule(e,t,n,r,i,a){if(!this.channelFactory)throw Error(`Channel factory is required`);let o=this.remoteStorage??new ro(i),s=this.cursorStorage??new Za(i),c=this.deadLetterStorage??new eo(i),l=new po(t,o,s,c,this.channelFactory,n,e,r,a,this.config);return{remoteStorage:o,cursorStorage:s,deadLetterStorage:c,channelFactory:this.channelFactory,syncManager:l}}};async function ho(){let{Kysely:e}=await r(async()=>{let{Kysely:e}=await import(`./esm-DUjqbF8m.js`);return{Kysely:e}},__vite__mapDeps([0,1])),{PGlite:t}=await r(async()=>{let{PGlite:e}=await import(`./dist-ScMbe_zR.js`);return{PGlite:e}},__vite__mapDeps([2,3,4,5,6,7,8,9])),{PGliteDialect:n}=await r(async()=>{let{PGliteDialect:e}=await import(`./dist-PLXkZ7-H.js`);return{PGliteDialect:e}},__vite__mapDeps([10,11,1]));return new e({dialect:new n(new t)})}function go(e=!1){let t=e,n=Promise.resolve();return[{get isShutdown(){return t},get completed(){return n}},e=>{t=e},e=>{n=e}]}var j=class extends Error{constructor(e){super(e||`Aborted`),this.name=`AbortError`}},_o=class{logger;documentModelRegistry;shutdownStatus;setShutdown;setCompleted;queue;jobTracker;readModelCoordinator;features;documentView;documentIndexer;operationStore;eventBus;executorManager;constructor(e,t,n,r,i,a,o,s,c,l,u){this.logger=e,this.documentModelRegistry=t,this.queue=n,this.jobTracker=r,this.readModelCoordinator=i,this.features=a,this.documentView=o,this.documentIndexer=s,this.operationStore=c,this.eventBus=l,this.executorManager=u;let[d,f,p]=go(!1);this.shutdownStatus=d,this.setShutdown=f,this.setCompleted=p,this.eventBus.subscribe(w.JOB_FAILED,(e,t)=>{this.logger.error(`Job @JobId failed with @Message: @Job`,t.jobId,t.error.message,t.job)}),this.readModelCoordinator.start()}kill(){return this.logger.verbose(`kill()`),this.shutdownStatus.isShutdown?this.shutdownStatus:(this.setShutdown(!0),this.setCompleted((async()=>{await this.executorManager.stop(!0),this.readModelCoordinator.stop(),this.jobTracker.shutdown()})()),this.shutdownStatus)}getDocumentModels(e,t,n){this.logger.verbose(`getDocumentModels(@namespace, @paging)`,e,t),D(n,()=>new j);let r=this.documentModelRegistry.getAllModules().filter(t=>!e||t.documentModel.global.id.startsWith(e)),i=t&&parseInt(t.cursor)||0,a=t?.limit||r.length,o=r.slice(i,i+a),s=i+a<r.length,c=s?String(i+a):void 0;return Promise.resolve({results:o,options:t||{cursor:`0`,limit:r.length},nextCursor:c,next:s?()=>this.getDocumentModels(e,{cursor:c,limit:a},n):void 0})}async get(e,t,n,r){return this.logger.verbose(`get(@id, @view)`,e,t),await this.documentView.get(e,t,n,r)}async getBySlug(e,t,n,r){this.logger.verbose(`getBySlug(@slug, @view)`,e,t);let i=await this.documentView.resolveSlug(e,t,n,r);if(!i)throw Error(`Document not found with slug: ${e}`);return await this.get(i,t,n,r)}async getByIdOrSlug(e,t,n,r){return this.logger.verbose(`getByIdOrSlug(@identifier, @view)`,e,t),await this.documentView.getByIdOrSlug(e,t,n,r)}async getOutgoingRelationships(e,t,n,r){let i=await this.documentIndexer.getOutgoing(e,[t],void 0,n,r);return D(r,()=>new j),i.results.map(e=>e.targetId)}async getIncomingRelationships(e,t,n,r){let i=await this.documentIndexer.getIncoming(e,[t],void 0,n,r);return D(r,()=>new j),i.results.map(e=>e.sourceId)}async getOperations(e,t,n,r,i,a){this.logger.verbose(`getOperations(@documentId, @view, @filter, @paging)`,e,t,n,r);let o=t?.branch||`main`,s=await this.operationStore.getRevisions(e,o,a);D(a,()=>new j);let c=Object.keys(s.revision),l={};for(let s of c){if(!ye(t,s))continue;D(a,()=>new j);let c=await this.operationStore.getSince(e,s,o,-1,n,r,a);l[s]={results:c.results,options:c.options,nextCursor:c.nextCursor,next:c.next?async()=>(await this.getOperations(e,t,n,{cursor:c.nextCursor,limit:c.options.limit},i,a))[s]:void 0}}return l}async find(e,t,n,r,i){this.logger.verbose(`find(@search, @view, @paging)`,e,t,n);let a;if(e.ids){if(e.slugs&&e.slugs.length>0)throw Error(`Cannot use both ids and slugs in the same search`);a=await this.findByIds(e.ids,t,n,r,i),e.type&&(a=xi(a,e.type))}else if(e.slugs)a=await this.findBySlugs(e.slugs,t,n,r,i),e.type&&(a=xi(a,e.type));else if(e.parentId)a=await this.findByParentId(e.parentId,t,n,r,i),e.type&&(a=xi(a,e.type));else if(e.type)a=await this.findByType(e.type,t,n,r,i);else throw Error(`No search criteria provided`);return D(i,()=>new j),a}async create(e,t,n,r){this.logger.verbose(`create(@id, @type, @slug)`,e.header.id,e.header.documentType,e.header.slug);let i=new Date().toISOString();D(n,()=>new j);let a=[li({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}}),ui({documentId:e.header.id,model:e.header.documentType,fromVersion:0,toVersion:e.state.document.version,initialState:e.state})];t&&(a=await Ti(a,t,n));let o=ke(),s=Ei(o,r),c={id:o,kind:`mutation`,documentId:e.header.id,scope:`document`,branch:`main`,actions:a,operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:s},l={id:o,documentId:c.documentId,status:A.PENDING,createdAtUtcIso:i,consistencyToken:{version:1,createdAtUtcIso:i,coordinates:[]},meta:s};return this.jobTracker.registerJob(l),this.emitJobPending(l.id,s),await this.queue.enqueue(c),l}async deleteDocument(e,t,n,r){this.logger.verbose(`deleteDocument(@id)`,e);let i=new Date().toISOString();D(n,()=>new j);let a=di(e);t&&(a=await wi(a,t,n));let o=ke(),s=Ei(o,r),c={id:o,kind:`mutation`,documentId:e,scope:`document`,branch:`main`,actions:[a],operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:s},l={id:o,documentId:c.documentId,status:A.PENDING,createdAtUtcIso:i,consistencyToken:{version:1,createdAtUtcIso:i,coordinates:[]},meta:s};return this.jobTracker.registerJob(l),this.emitJobPending(l.id,s),await this.queue.enqueue(c),l}async execute(e,t,n,r,i){this.logger.verbose(`execute(@docId, @branch, @actions)`,e,t,n),D(r,()=>new j);let a=new Date().toISOString(),o=Ci(n),s=ke(),c=Ei(s,i),l={id:s,kind:`mutation`,documentId:e,scope:o,branch:t,actions:n,operations:[],createdAt:new Date().toISOString(),queueHint:[],maxRetries:3,errorHistory:[],meta:c},u={id:s,documentId:l.documentId,status:A.PENDING,createdAtUtcIso:a,consistencyToken:{version:1,createdAtUtcIso:a,coordinates:[]},meta:c};return this.jobTracker.registerJob(u),this.emitJobPending(u.id,c),await this.queue.enqueue(l),D(r,()=>new j),u}async load(e,t,n,r,i){if(this.logger.verbose(`load(@docId, @branch, @count, @operations)`,e,t,n.length,n),D(r,()=>new j),n.length===0)throw Error(`load requires at least one operation`);let a=Si(n),o=new Date().toISOString(),s=ke(),c=Ei(s,i),l={id:s,kind:`load`,documentId:e,scope:a,branch:t,actions:[],operations:n,createdAt:o,queueHint:[],maxRetries:3,errorHistory:[],meta:c},u={id:s,documentId:l.documentId,status:A.PENDING,createdAtUtcIso:o,consistencyToken:{version:1,createdAtUtcIso:o,coordinates:[]},meta:c};return this.jobTracker.registerJob(u),this.emitJobPending(u.id,c),await this.queue.enqueue(l),D(r,()=>new j),u}async executeBatch(e,t,n){this.logger.verbose(`executeBatch(@count jobs)`,e.jobs.length),D(t,()=>new j),hi(e.jobs);for(let t of e.jobs)_i(t);let r=new Date().toISOString(),i=new Map;for(let t of e.jobs)i.set(t.key,ke());let a=ke(),o=[...i.values()],s={...n,batchId:a,batchJobIds:o},c=new Map;for(let t of e.jobs){let e={id:i.get(t.key),documentId:t.documentId,status:A.PENDING,createdAtUtcIso:r,consistencyToken:{version:1,createdAtUtcIso:r,coordinates:[]},meta:s};this.jobTracker.registerJob(e),this.emitJobPending(e.id,s),c.set(t.key,e)}let l=yi(e.jobs),u=[];try{for(let n of l){D(t,()=>new j);let a=e.jobs.find(e=>e.key===n),o=i.get(n),c=a.dependsOn.map(e=>i.get(e)),l={id:o,kind:`mutation`,documentId:a.documentId,scope:a.scope,branch:a.branch,actions:a.actions,operations:[],createdAt:r,queueHint:c,maxRetries:3,errorHistory:[],meta:s};await this.queue.enqueue(l),u.push(n)}}catch(e){for(let e of u){let t=i.get(e);try{await this.queue.remove(t)}catch{}}for(let e of c.values())this.jobTracker.markFailed(e.id,bi(`Batch enqueue failed`));throw e}return{jobs:Object.fromEntries(c)}}async loadBatch(e,t,n){this.logger.verbose(`loadBatch(@count jobs)`,e.jobs.length),D(t,()=>new j),gi(e.jobs);for(let t of e.jobs)vi(t);let r=new Date().toISOString(),i=new Map;for(let t of e.jobs)i.set(t.key,ke());let a=ke(),o=[...i.values()],s={...n,batchId:a,batchJobIds:o},c=new Map;for(let t of e.jobs){let e={id:i.get(t.key),documentId:t.documentId,status:A.PENDING,createdAtUtcIso:r,consistencyToken:{version:1,createdAtUtcIso:r,coordinates:[]},meta:s};this.jobTracker.registerJob(e),this.emitJobPending(e.id,s),c.set(t.key,e)}let l=yi(e.jobs),u=[];try{for(let n of l){D(t,()=>new j);let a=e.jobs.find(e=>e.key===n),o=i.get(n),c=[...a.dependsOn.map(e=>i.get(e)),...a.externalDeps],l={id:o,kind:`load`,documentId:a.documentId,scope:a.scope,branch:a.branch,actions:[],operations:a.operations,createdAt:r,queueHint:c,maxRetries:3,errorHistory:[],meta:s};await this.queue.enqueue(l),u.push(n)}}catch(e){for(let e of u){let t=i.get(e);try{await this.queue.remove(t)}catch{}}for(let e of c.values())this.jobTracker.markFailed(e.id,bi(`Batch enqueue failed`));throw e}return{jobs:Object.fromEntries(c)}}async addRelationship(e,t,n,r=`main`,i,a){this.logger.verbose(`addRelationship(@sourceId, @targetId, @relationshipType, @branch)`,e,t,n,r),D(a,()=>new j);let o=[fi(e,t,n)];return i&&(o=await Ti(o,i,a)),await this.execute(e,r,o,a)}async removeRelationship(e,t,n,r=`main`,i,a){this.logger.verbose(`removeRelationship(@sourceId, @targetId, @relationshipType, @branch)`,e,t,n,r),D(a,()=>new j);let o=[pi(e,t,n)];return i&&(o=await Ti(o,i,a)),await this.execute(e,r,o,a)}getJobStatus(e,t){this.logger.verbose(`getJobStatus(@jobId)`,e),D(t,()=>new j);let n=this.jobTracker.getJobStatus(e);if(!n){let t=new Date().toISOString();return Promise.resolve({id:e,documentId:``,status:A.FAILED,createdAtUtcIso:t,completedAtUtcIso:t,error:bi(`Job not found`),consistencyToken:{version:1,createdAtUtcIso:t,coordinates:[]},meta:{batchId:e,batchJobIds:[e]}})}return Promise.resolve(n)}async findByIds(e,t,n,r,i){this.logger.verbose(`findByIds(@count ids)`,e.length);let a=n?.cursor&&parseInt(n.cursor)||0,o=n?.limit||e.length,s=e.slice(a,a+o),c=await this.documentView.getMany(s,t,r,i),l=a+o<e.length?String(a+o):void 0;return{results:c,options:n||{cursor:`0`,limit:e.length},nextCursor:l}}async findBySlugs(e,t,n,r,i){this.logger.verbose(`findBySlugs(@count slugs)`,e.length);let a=await this.documentView.resolveSlugs(e,t,r,i);return await this.findByIds(a,t,n,r,i)}async findByParentId(e,t,n,r,i){this.logger.verbose(`findByParentId(@parentId)`,e);let a=(await this.documentIndexer.getOutgoing(e,[`child`],n,r,i)).results.map(e=>e.targetId);return await this.findByIds(a,t,n,void 0,i)}async findByType(e,t,n,r,i){return this.logger.verbose(`findByType(@type)`,e),await this.documentView.findByType(e,t,n,r,i)}emitJobPending(e,t){let n={jobId:e,jobMeta:t};this.eventBus.emit(w.JOB_PENDING,n).catch(()=>{})}},vo=class{logger;documentModels=[];upgradeManifests=[];features={legacyStorageEnabled:!1};readModels=[];readModelFactories=[];executorManager;executorConfig={};writeCacheConfig;migrationStrategy=`auto`;syncBuilder;eventBus;readModelCoordinator;signatureVerifier;kyselyInstance;signalHandlersEnabled=!1;queueInstance;channelScheme;jwtHandler;documentModelLoader;shutdownHooks=[];driveContainerTypes=Oe;documentModelSpecs=[];workerPoolConfig;resolvedModelManifest;workerDbConfig;workerSignatureVerifierSpec;workerFactory;projectionShardConfig;projectionWorkerFactory;instrumentedPools=[];withLogger(e){return this.logger=e,this}withDocumentModels(e){return this.documentModels=e,this}withUpgradeManifests(e){return this.upgradeManifests=e,this}withFeatures(e){return this.features={...this.features,...e},this}withReadModel(e){return this.readModels.push(e),this}withReadModelFactory(e){return this.readModelFactories.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}withDriveContainerTypes(e){return this.driveContainerTypes=new Set(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}withInstrumentedPool(e){return this.instrumentedPools.push(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}withShutdownHook(e){return this.shutdownHooks.push(e),this}withDocumentModelSpecs(e){return this.documentModelSpecs=e,this}withWorkerPool(e){return this.workerPoolConfig=e,this}withWorkerDbConfig(e){return this.workerDbConfig=e,this}withWorkerSignatureVerifierSpec(e){return this.workerSignatureVerifierSpec=e,this}withWorkerFactory(e){return this.workerFactory=e,this}withProjectionShards(e){return this.projectionShardConfig=e,this}withProjectionWorkerFactory(e){return this.projectionWorkerFactory=e,this}getResolvedModelManifest(){return this.resolvedModelManifest}async build(){return(await this.buildModule()).reactor}async buildModule(){if(this.logger||=new me([`reactor`]),this.workerPoolConfig?.enabled){if(this.documentModels.length>0)throw Error(`workerPool.enabled requires withDocumentModelSpecs; remove withDocumentModels() in worker-pool mode.`);if(this.documentModelSpecs.length===0)throw Error(`workerPool.enabled requires at least one spec registered via withDocumentModelSpecs.`);let e=!this.executorManager&&!this.workerFactory;if(e&&!this.workerDbConfig)throw Error(`workerPool.enabled requires withWorkerDbConfig (or a custom withWorkerFactory / withExecutor).`);if(e&&!this.workerSignatureVerifierSpec)throw Error(`workerPool.enabled requires withWorkerSignatureVerifierSpec (or a custom withWorkerFactory / withExecutor).`)}this.documentModelSpecs.length>0&&(this.resolvedModelManifest=this.documentModelSpecs.map(e=>`filePath`in e?{documentType:`<unresolved>`,version:`<unresolved>`,spec:{module:{filePath:e.filePath,exportName:`documentModel`}}}:{documentType:`<unresolved>`,version:e.version,spec:{module:{packageName:e.packageName,exportName:`documentModel`}}}));let e=new Fe;if(this.upgradeManifests.length>0){let t=e.registerUpgradeManifests(...this.upgradeManifests);for(let e of t)e.status===`error`&&this.logger.error(`Failed to register upgrade manifest: @error`,e.error.message)}if(this.documentModels.length>0){let t=e.registerModules(...this.documentModels);for(let e of t)e.status===`error`&&this.logger.error(`Failed to register document model: @error`,e.error.message)}let t=this.kyselyInstance??(this.workerPoolConfig?.enabled&&this.workerDbConfig?await this.createPostgresDatabase(this.workerDbConfig):await ho());if(this.migrationStrategy===`auto`){let e=await ge(t,Be);if(!e.success&&e.error)throw Error(`Database migration failed: ${e.error.message}`)}let n=t.withSchema(Be),r=new Ee(n),i=new je(n),a=this.eventBus||new Te,o=this.documentModelLoader?new ca(e,this.documentModelLoader):new la(e),s=this.queueInstance??new sa(a,o),c=new $i(a),l=new be(i,r,e,{maxDocuments:this.writeCacheConfig?.maxDocuments??100,ringBufferSize:this.writeCacheConfig?.ringBufferSize??10,keyframeInterval:this.writeCacheConfig?.keyframeInterval??10});await l.startup();let u=new De(n),d=new Me(r,{maxDocuments:1e3});await d.startup();let f=new Pe(u),p=new Ne(n,r,u,i,l,d,f),m=this.executorManager,h=this.executorConfig.maxConcurrency??1;if(!m)if(this.workerPoolConfig?.enabled){let e=new Ji(this.workerFactory??await this.createDefaultWorkerFactory(this.workerPoolConfig),a,s,c,this.logger,o,f,this.executorConfig.jobTimeoutMs);m=e,h=this.workerPoolConfig.numWorkers,o instanceof ca&&o.setBroadcastHook(t=>e.loadModel(t))}else m=new Qi(()=>new Se(this.logger,e,r,a,l,u,d,f,this.driveContainerTypes,this.executorConfig,this.signatureVerifier,p),a,s,c,this.logger,o,this.executorConfig.jobTimeoutMs);await m.start(h);let g=Array.from(new Set([...this.readModels])),_=new bn,v=new vn(n,r,u,l,_);try{await v.init()}catch(e){console.error(`Error initializing document view`,e)}g.push(v);let y=new bn,b=new Sn(n,u,l,y);try{await b.init()}catch(e){console.error(`Error initializing document indexer`,e)}g.push(b);let x=new da(new ua),ee=new fa(x,v),te=new bn,ne=new aa(n,u,l,te,this.logger,this.driveContainerTypes);try{await ne.init()}catch(e){console.error(`Error initializing processor manager`,e)}for(let e of this.readModelFactories){let t=await e({operationIndex:u,writeCache:l,processorManagerConsistencyTracker:te});g.push(t)}let S=this.readModelCoordinator?this.readModelCoordinator:this.projectionShardConfig?await this.createProjectionShardManager(this.projectionShardConfig,a):new _n(a,g,[ee,ne]),C=new _o(this.logger,e,s,c,S,this.features,v,b,r,a,m),re;if(this.channelScheme){let e=this.channelScheme===pa.CONNECT?new Ka(this.logger,this.jwtHandler,s):new Ja(this.logger);re=new mo().withChannelFactory(e).buildModule(C,this.logger,u,a,n,this.driveContainerTypes),await re.syncManager.startup()}else this.syncBuilder&&(re=this.syncBuilder.buildModule(C,this.logger,u,a,n,this.driveContainerTypes),await re.syncManager.startup());let w={eventBus:a,documentModelRegistry:e,queue:s,jobTracker:c,executorManager:m,database:n,operationStore:r,keyframeStore:i,writeCache:l,operationIndex:u,documentView:v,documentViewConsistencyTracker:_,documentIndexer:b,documentIndexerConsistencyTracker:y,readModelCoordinator:S,subscriptionManager:x,processorManager:ne,processorManagerConsistencyTracker:te,syncModule:re,reactor:C,pools:this.instrumentedPools};return this.signalHandlersEnabled&&this.attachSignalHandlers(w),w}async createProjectionShardManager(e,t){if(!this.workerDbConfig)throw Error(`withProjectionShards requires withWorkerDbConfig; projection workers need connection info to open their own pools.`);let n=this.resolvedModelManifest??[],i={...this.workerDbConfig,poolSize:e.poolSize??this.workerDbConfig.poolSize,applicationName:`reactor-projection-shard`},a=this.projectionWorkerFactory??await this.createDefaultProjectionWorkerFactory(),o=[];for(let t=0;t<e.shardCount;t++){let e=he(`projection-shard-${t}`);o.push(e),this.instrumentedPools.push(e)}let{ProjectionShardManager:s}=await r(async()=>{let{ProjectionShardManager:e}=await import(`./projection-shard-manager-_c7orNo5-CYmXImZA.js`);return{ProjectionShardManager:e}},__vite__mapDeps([12,4,13,14,15])),c=new s({shardCount:e.shardCount,db:i,models:n,preReadyKinds:e.preReadyKinds,postReadyKinds:e.postReadyKinds,factory:a,logger:this.logger,hostBus:t,initTimeoutMs:e.initTimeoutMs,shutdownGraceMs:e.shutdownGraceMs,drainTimeoutMs:e.drainTimeoutMs,chainDepthReportIntervalMs:e.chainDepthReportIntervalMs,poolInstrumentations:o});return await c.startup(),this.shutdownHooks.push(()=>c.shutdown()),c}async createDefaultProjectionWorkerFactory(){let[{createProjectionThreadTransport:e},{projectionWorkerEntryPath:t}]=await Promise.all([r(()=>import(`./transport-CuogVKN_-CmEFLNk5.js`),__vite__mapDeps([16,4,15])),r(()=>import(`./projection-worker-wI4PwcV2-DKlb7c3l.js`),[])]);return()=>e(t)}async createDefaultWorkerFactory(e){let[{WorkerHandle:t},{createThreadTransport:n},{workerEntryPath:i}]=await Promise.all([r(()=>import(`./worker-handle-B1w03nRA-BHJaS5pO.js`),__vite__mapDeps([17,4,18,19,15])),r(()=>import(`./transport-ByGviWdZ-zEKFyLfk.js`),__vite__mapDeps([20,4,15])),r(()=>import(`./worker-XYrQaEmt-Ce3Gpb8t.js`).then(e=>e.n),__vite__mapDeps([21,22,18,13,4,1]))]),a=this.workerDbConfig,o=this.workerSignatureVerifierSpec,s=this.resolvedModelManifest??[],c=this.logger;return r=>{let l=`reactor-worker-${r}`,u=he(l);return this.instrumentedPools.push(u),new t({workerId:l,index:r,transport:n(i),initPayload:{poolConfig:e,db:a,signatureVerifier:o,models:s},logger:c,poolInstrumentation:u})}}async createPostgresDatabase(e){let{Kysely:t,PostgresDialect:n}=await r(async()=>{let{Kysely:e,PostgresDialect:t}=await import(`./esm-DUjqbF8m.js`);return{Kysely:e,PostgresDialect:t}},__vite__mapDeps([0,1])),i=(await r(async()=>{let{default:e}=await import(`./esm-dD38MHAT.js`);return{default:e}},__vite__mapDeps([23,4,15]))).default.Pool,a=new i({host:e.host,port:e.port,database:e.database,user:e.user,password:e.password,ssl:e.ssl?{rejectUnauthorized:!1}:void 0,application_name:e.applicationName,max:e.poolSize,connectionTimeoutMillis:e.connectionTimeoutMillis,idleTimeoutMillis:e.idleTimeoutMillis});return this.instrumentedPools.push(Re(a,e.applicationName??`reactor-host`)),new t({dialect:new n({pool:a})})}attachSignalHandlers(e){if(typeof globalThis>`u`||!(`process`in globalThis)||typeof globalThis.process.on!=`function`)return;let t=globalThis.process,n=t.exit.bind(t),r=!1,i,a=async a=>{if(r){this.logger.warn(`Received ${a} again, continuing graceful shutdown...`);return}r=!0,t.exit=(e=>{i??=e??0}),this.logger.info(`Received ${a}, starting graceful shutdown...`);let o=e.reactor.kill();try{await o.completed}catch(e){this.logger.error(`Shutdown failed waiting for reactor:`,e),t.exit=n,n(1);return}for(let e of this.shutdownHooks)try{await e()}catch(e){this.logger.error(`Shutdown hook failed:`,e)}try{await e.database.destroy()}catch(e){this.logger.error(`Shutdown failed destroying database:`,e),t.exit=n,n(1);return}this.logger.info(`Shutdown complete`),t.exit=n,n(i??0)};t.prependListener(`SIGINT`,()=>void a(`SIGINT`)),t.prependListener(`SIGTERM`,()=>void a(`SIGTERM`))}},yo=class{publicKey={};sign(){return Promise.resolve(new Uint8Array)}verify(){return Promise.resolve()}signAction(){return Promise.resolve([``,``,``,``,``])}},bo=class{logger;reactorBuilder;reactor;eventBus;documentIndexer;documentView;signer;signatureVerifier;subscriptionManager;jobAwaiter;documentModelLoader;withLogger(e){return this.logger=e,this}withReactorBuilder(e){if(this.reactor)throw Error(`Reactor is already set`);return this.reactorBuilder=e,this}withReactor(e,t,n,r){if(this.reactorBuilder)throw Error(`ReactorBuilder is already set`);return this.reactor=e,this.eventBus=t,this.documentIndexer=n,this.documentView=r,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}withDocumentModelLoader(e){return this.documentModelLoader=e,this}async build(){return(await this.buildModule()).client}async buildModule(){this.logger||=new me([`reactor-client`]);let e,t,n,r,i;if(this.reactorBuilder)this.signatureVerifier&&this.reactorBuilder.withSignatureVerifier(this.signatureVerifier),this.documentModelLoader&&this.reactorBuilder.withDocumentModelLoader(this.documentModelLoader),i=await this.reactorBuilder.buildModule(),e=i.reactor,t=i.eventBus,n=i.documentIndexer,r=i.documentView;else if(this.reactor&&this.eventBus&&this.documentIndexer&&this.documentView)e=this.reactor,t=this.eventBus,n=this.documentIndexer,r=this.documentView,i=void 0;else throw Error(`Either ReactorBuilder or (Reactor + EventBus + DocumentIndexer + DocumentView) is required`);let a=this.signer??new yo,o=this.subscriptionManager??i?.subscriptionManager??new da(new ua),s=this.jobAwaiter??new ji(t,(t,n)=>e.getJobStatus(t,n));return{client:new Li(this.logger,e,a,o,s,n,r),reactor:e,eventBus:t,documentIndexer:n,documentView:r,signer:a,subscriptionManager:o,jobAwaiter:s,reactorModule:i}}},xo={putKeyframe:()=>Promise.resolve(),findNearestKeyframe:()=>Promise.resolve(void 0),listKeyframes:()=>Promise.resolve([]),deleteKeyframes:()=>Promise.resolve(0)},So=class{keyframeStore;operationStore;writeCache;documentView;documentModelRegistry;constructor(e,t,n,r,i){this.keyframeStore=e,this.operationStore=t,this.writeCache=n,this.documentView=r,this.documentModelRegistry=i}async validateDocument(e,t=`main`,n){let r=[],i=[],a=new be(xo,this.operationStore,this.documentModelRegistry,{maxDocuments:1,ringBufferSize:1,keyframeInterval:2**53-1}),o=await this.keyframeStore.listKeyframes(e,void 0,t,n);for(let i of o){D(n),a.invalidate(e,i.scope,t);let o=await a.getState(e,i.scope,t,i.revision,n),s=u(i.document,i.scope),c=u(o,i.scope);s!==c&&r.push({scope:i.scope,branch:t,revision:i.revision,keyframeHash:s,replayedHash:c})}let s;try{s=await this.documentView.get(e)}catch{return{documentId:e,isConsistent:r.length===0,keyframeIssues:r,snapshotIssues:i}}let c=await this.operationStore.getRevisions(e,t,n),l=Object.keys(c.revision);for(let r of l){if(r===`document`)continue;a.invalidate(e,r,t);let o;try{o=await a.getState(e,r,t,void 0,n)}catch{D(n);continue}let c=u(s,r),l=u(o,r);c!==l&&i.push({scope:r,branch:t,snapshotHash:c,replayedHash:l})}return{documentId:e,isConsistent:r.length===0&&i.length===0,keyframeIssues:r,snapshotIssues:i}}async rebuildKeyframes(e,t=`main`,n){return{documentId:e,keyframesDeleted:await this.keyframeStore.deleteKeyframes(e,void 0,t,n),scopesInvalidated:0}}async rebuildSnapshots(e,t=`main`,n){let r=await this.discoverScopes(e,t,n);for(let i of r)D(n),this.writeCache.invalidate(e,i,t);return{documentId:e,keyframesDeleted:0,scopesInvalidated:r.length}}async discoverScopes(e,t,n){let r=await this.operationStore.getRevisions(e,t,n);return Object.keys(r.revision)}},Co=function(e){return e[e.AnalyticsPath=0]=`AnalyticsPath`,e[e.AnalyticsPathSegment=1]=`AnalyticsPathSegment`,e[e.AnalyticsPeriod=2]=`AnalyticsPeriod`,e}({}),wo=function(e){return e[e.VectorAdd=0]=`VectorAdd`,e[e.VectorSubtract=1]=`VectorSubtract`,e[e.ScalarMultiply=2]=`ScalarMultiply`,e[e.ScalarDivide=3]=`ScalarDivide`,e}({}),To=function(e){return e[e.Total=0]=`Total`,e[e.Annual=1]=`Annual`,e[e.SemiAnnual=2]=`SemiAnnual`,e[e.Quarterly=3]=`Quarterly`,e[e.Monthly=4]=`Monthly`,e[e.Weekly=5]=`Weekly`,e[e.Daily=6]=`Daily`,e[e.Hourly=7]=`Hourly`,e}({}),Eo=class e{get segments(){return this._segments}_segments;static fromString(t){return new e(ko(t,`/`).map(e=>Do.fromString(e)))}static fromStringArray(t){return new e(t.map(e=>Do.fromString(e)))}static fromArray(t){return new e(t)}static fromJSON(t){return new e(t._v.split(`/`).map(e=>Do.fromString(e)))}constructor(e){this._segments=e}toJSON(){return{_t:Co.AnalyticsPath,_v:this.toString()}}toString(e=``){return this._segments.map(e=>e.toString()).join(`/`)+e}firstSegment(){return this._segments.length>0?this._segments[0]:new Do}reduce(){let t=this._segments.slice(1);return t.length<1&&t.push(new Do),new e(t)}applyLod(t){let n=[...this._segments];for(;n.length<t;)n.push(new Do);return new e(n.slice(0,t))}},Do=class e{get filters(){return this._filters}get groups(){return this._groups}_filters=null;_groups=null;static fromString(t){let n=ko(t,`:`),r;r=n[0]===`*`?null:ko(n[0],`,`).map(t=>e.unescape(t));let i;return i=n[1]===void 0||n[1].length<1?[]:n[1]===`*`?null:ko(n[1],`,`).map(t=>e.unescape(t)),new e(r,i)}static escape(e){return e.replace(/(\\|:|\/|,)/gi,`\\$1`)}static unescape(e){return e.replace(/\\(.)/gi,`$1`)}constructor(e=null,t=[]){this._filters=e,this._groups=t}toJSON(){return{_t:Co.AnalyticsPathSegment,_v:this.toString()}}toString(){let t=``;return this._filters===null?t+=`*`:t+=this._filters.map(t=>e.escape(t)).join(`,`),this._groups===null?t+=`:*`:this._groups.length>0&&(t+=`:`+this._groups.map(t=>e.escape(t)).join(`,`)),t}},Oo={":":/(?<!\\):/,",":/(?<!\\),/,"/":/(?<!\\)\//};function ko(e,t){let n=`@@`;for(;e.indexOf(n)>-1;)n+=`@`;return e.replaceAll(`\\\\`,n).split(Oo[t]).map(e=>e.replaceAll(n,`\\\\`))}var Ao=class extends Error{},jo=class extends Ao{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Mo=class extends Ao{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},No=class extends Ao{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},Po=class extends Ao{},Fo=class extends Ao{constructor(e){super(`Invalid unit ${e}`)}},Io=class extends Ao{},Lo=class extends Ao{constructor(){super(`Zone is an abstract class`)}},M=`numeric`,Ro=`short`,zo=`long`,Bo={year:M,month:M,day:M},Vo={year:M,month:Ro,day:M},Ho={year:M,month:Ro,day:M,weekday:Ro},Uo={year:M,month:zo,day:M},Wo={year:M,month:zo,day:M,weekday:zo},Go={hour:M,minute:M},Ko={hour:M,minute:M,second:M},qo={hour:M,minute:M,second:M,timeZoneName:Ro},Jo={hour:M,minute:M,second:M,timeZoneName:zo},Yo={hour:M,minute:M,hourCycle:`h23`},Xo={hour:M,minute:M,second:M,hourCycle:`h23`},Zo={hour:M,minute:M,second:M,hourCycle:`h23`,timeZoneName:Ro},Qo={hour:M,minute:M,second:M,hourCycle:`h23`,timeZoneName:zo},$o={year:M,month:M,day:M,hour:M,minute:M},es={year:M,month:M,day:M,hour:M,minute:M,second:M},ts={year:M,month:Ro,day:M,hour:M,minute:M},ns={year:M,month:Ro,day:M,hour:M,minute:M,second:M},rs={year:M,month:Ro,day:M,weekday:Ro,hour:M,minute:M},is={year:M,month:zo,day:M,hour:M,minute:M,timeZoneName:Ro},as={year:M,month:zo,day:M,hour:M,minute:M,second:M,timeZoneName:Ro},os={year:M,month:zo,day:M,weekday:zo,hour:M,minute:M,timeZoneName:zo},ss={year:M,month:zo,day:M,weekday:zo,hour:M,minute:M,second:M,timeZoneName:zo},cs=class{get type(){throw new Lo}get name(){throw new Lo}get ianaName(){return this.name}get isUniversal(){throw new Lo}offsetName(e,t){throw new Lo}formatOffset(e,t){throw new Lo}offset(e){throw new Lo}equals(e){throw new Lo}get isValid(){throw new Lo}},ls=null,us=class e extends cs{static get instance(){return ls===null&&(ls=new e),ls}get type(){return`system`}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return Jc(e,t,n)}formatOffset(e,t){return Qc(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type===`system`}get isValid(){return!0}},ds=new Map;function fs(e){let t=ds.get(e);return t===void 0&&(t=new Intl.DateTimeFormat(`en-US`,{hour12:!1,timeZone:e,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,era:`short`}),ds.set(e,t)),t}var ps={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ms(e,t){let n=e.format(t).replace(/\u200E/g,``),[,r,i,a,o,s,c,l]=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n);return[a,r,i,o,s,c,l]}function hs(e,t){let n=e.formatToParts(t),r=[];for(let e=0;e<n.length;e++){let{type:t,value:i}=n[e],a=ps[t];t===`era`?r[a]=i:F(a)||(r[a]=parseInt(i,10))}return r}var gs=new Map,_s=class e extends cs{static create(t){let n=gs.get(t);return n===void 0&&gs.set(t,n=new e(t)),n}static resetCache(){gs.clear(),ds.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(t){super(),this.zoneName=t,this.valid=e.isValidZone(t)}get type(){return`iana`}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return Jc(e,t,n,this.name)}formatOffset(e,t){return Qc(this.offset(e),t)}offset(e){if(!this.valid)return NaN;let t=new Date(e);if(isNaN(t))return NaN;let n=fs(this.name),[r,i,a,o,s,c,l]=n.formatToParts?hs(n,t):ms(n,t);o===`BC`&&(r=-Math.abs(r)+1);let u=Wc({year:r,month:i,day:a,hour:s===24?0:s,minute:c,second:l,millisecond:0}),d=+t,f=d%1e3;return d-=f>=0?f:1e3+f,(u-d)/(60*1e3)}equals(e){return e.type===`iana`&&e.name===this.name}get isValid(){return this.valid}},vs={};function ys(e,t={}){let n=JSON.stringify([e,t]),r=vs[n];return r||(r=new Intl.ListFormat(e,t),vs[n]=r),r}var bs=new Map;function xs(e,t={}){let n=JSON.stringify([e,t]),r=bs.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),bs.set(n,r)),r}var Ss=new Map;function Cs(e,t={}){let n=JSON.stringify([e,t]),r=Ss.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),Ss.set(n,r)),r}var ws=new Map;function Ts(e,t={}){let{base:n,...r}=t,i=JSON.stringify([e,r]),a=ws.get(i);return a===void 0&&(a=new Intl.RelativeTimeFormat(e,t),ws.set(i,a)),a}var Es=null;function Ds(){return Es||(Es=new Intl.DateTimeFormat().resolvedOptions().locale,Es)}var Os=new Map;function ks(e){let t=Os.get(e);return t===void 0&&(t=new Intl.DateTimeFormat(e).resolvedOptions(),Os.set(e,t)),t}var As=new Map;function js(e){let t=As.get(e);if(!t){let n=new Intl.Locale(e);t=`getWeekInfo`in n?n.getWeekInfo():n.weekInfo,`minimalDays`in t||(t={...Vs,...t}),As.set(e,t)}return t}function Ms(e){let t=e.indexOf(`-x-`);t!==-1&&(e=e.substring(0,t));let n=e.indexOf(`-u-`);if(n===-1)return[e];{let t,r;try{t=xs(e).resolvedOptions(),r=e}catch{let i=e.substring(0,n);t=xs(i).resolvedOptions(),r=i}let{numberingSystem:i,calendar:a}=t;return[r,i,a]}}function Ns(e,t,n){return n||t?(e.includes(`-u-`)||(e+=`-u`),n&&(e+=`-ca-${n}`),t&&(e+=`-nu-${t}`),e):e}function Ps(e){let t=[];for(let n=1;n<=12;n++){let r=R.utc(2009,n,1);t.push(e(r))}return t}function Fs(e){let t=[];for(let n=1;n<=7;n++){let r=R.utc(2016,11,13+n);t.push(e(r))}return t}function Is(e,t,n,r){let i=e.listingMode();return i===`error`?null:i===`en`?n(t):r(t)}function Ls(e){return e.numberingSystem&&e.numberingSystem!==`latn`?!1:e.numberingSystem===`latn`||!e.locale||e.locale.startsWith(`en`)||ks(e.locale).numberingSystem===`latn`}var Rs=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:r,floor:i,...a}=n;if(!t||Object.keys(a).length>0){let t={useGrouping:!1,...n};n.padTo>0&&(t.minimumIntegerDigits=n.padTo),this.inf=Cs(e,t)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else return I(this.floor?Math.floor(e):Bc(e,3),this.padTo)}},zs=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type===`fixed`){let t=-1*(e.offset/60),n=t>=0?`Etc/GMT+${t}`:`Etc/GMT${t}`;e.offset!==0&&_s.create(n).valid?(r=n,this.dt=e):(r=`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,r=e.zone.name):(r=`UTC`,this.dt=e.setZone(`UTC`).plus({minutes:e.offset}),this.originalZone=e.zone);let i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=xs(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(``):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(e=>{if(e.type===`timeZoneName`){let t=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...e,value:t}}else return e}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Bs=class{constructor(e,t,n){this.opts={style:`long`,...n},!t&&Oc()&&(this.rtf=Ts(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):_l(t,e,this.opts.numeric,this.opts.style!==`long`)}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},Vs={firstDay:1,minimalDays:4,weekend:[6,7]},N=class e{static fromOpts(t){return e.create(t.locale,t.numberingSystem,t.outputCalendar,t.weekSettings,t.defaultToEN)}static create(t,n,r,i,a=!1){let o=t||P.defaultLocale;return new e(o||(a?`en-US`:Ds()),n||P.defaultNumberingSystem,r||P.defaultOutputCalendar,Pc(i)||P.defaultWeekSettings,o)}static resetCache(){Es=null,bs.clear(),Ss.clear(),ws.clear(),Os.clear(),As.clear()}static fromObject({locale:t,numberingSystem:n,outputCalendar:r,weekSettings:i}={}){return e.create(t,n,r,i)}constructor(e,t,n,r,i){let[a,o,s]=Ms(e);this.locale=a,this.numberingSystem=t||o||null,this.outputCalendar=n||s||null,this.weekSettings=r,this.intl=Ns(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached??=Ls(this),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem===`latn`)&&(this.outputCalendar===null||this.outputCalendar===`gregory`);return e&&t?`en`:`intl`}clone(t){return!t||Object.getOwnPropertyNames(t).length===0?this:e.create(t.locale||this.specifiedLocale,t.numberingSystem||this.numberingSystem,t.outputCalendar||this.outputCalendar,Pc(t.weekSettings)||this.weekSettings,t.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return Is(this,e,rl,()=>{let n=this.intl===`ja`||this.intl.startsWith(`ja-`);t&=!n;let r=t?{month:e,day:`numeric`}:{month:e},i=t?`format`:`standalone`;if(!this.monthsCache[i][e]){let t=n?e=>this.dtFormatter(e,r).format():e=>this.extract(e,r,`month`);this.monthsCache[i][e]=Ps(t)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return Is(this,e,sl,()=>{let n=t?{weekday:e,year:`numeric`,month:`long`,day:`numeric`}:{weekday:e},r=t?`format`:`standalone`;return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=Fs(e=>this.extract(e,n,`weekday`))),this.weekdaysCache[r][e]})}meridiems(){return Is(this,void 0,()=>cl,()=>{if(!this.meridiemCache){let e={hour:`numeric`,hourCycle:`h12`};this.meridiemCache=[R.utc(2016,11,13,9),R.utc(2016,11,13,19)].map(t=>this.extract(t,e,`dayperiod`))}return this.meridiemCache})}eras(e){return Is(this,e,fl,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[R.utc(-40,1,1),R.utc(2017,1,1)].map(e=>this.extract(e,t,`era`))),this.eraCache[e]})}extract(e,t,n){let r=this.dtFormatter(e,t).formatToParts().find(e=>e.type.toLowerCase()===n);return r?r.value:null}numberFormatter(e={}){return new Rs(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new zs(e,this.intl,t)}relFormatter(e={}){return new Bs(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ys(this.intl,e)}isEnglish(){return this.locale===`en`||this.locale.toLowerCase()===`en-us`||ks(this.intl).locale.startsWith(`en-us`)}getWeekSettings(){return this.weekSettings?this.weekSettings:kc()?js(this.locale):Vs}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})`}},Hs=null,Us=class e extends cs{static get utcInstance(){return Hs===null&&(Hs=new e(0)),Hs}static instance(t){return t===0?e.utcInstance:new e(t)}static parseSpecifier(t){if(t){let n=t.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new e(Yc(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return`fixed`}get name(){return this.fixed===0?`UTC`:`UTC${Qc(this.fixed,`narrow`)}`}get ianaName(){return this.fixed===0?`Etc/UTC`:`Etc/GMT${Qc(-this.fixed,`narrow`)}`}offsetName(){return this.name}formatOffset(e,t){return Qc(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type===`fixed`&&e.fixed===this.fixed}get isValid(){return!0}},Ws=class extends cs{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 Gs(e,t){if(F(e)||e===null)return t;if(e instanceof cs)return e;if(Ec(e)){let n=e.toLowerCase();return n===`default`?t:n===`local`||n===`system`?us.instance:n===`utc`||n===`gmt`?Us.utcInstance:Us.parseSpecifier(n)||_s.create(e)}else if(wc(e))return Us.instance(e);else if(typeof e==`object`&&`offset`in e&&typeof e.offset==`function`)return e;else return new Ws(e)}var Ks={arab:`[٠-٩]`,arabext:`[۰-۹]`,bali:`[᭐-᭙]`,beng:`[০-৯]`,deva:`[०-९]`,fullwide:`[0-9]`,gujr:`[૦-૯]`,hanidec:`[〇|一|二|三|四|五|六|七|八|九]`,khmr:`[០-៩]`,knda:`[೦-೯]`,laoo:`[໐-໙]`,limb:`[᥆-᥏]`,mlym:`[൦-൯]`,mong:`[᠐-᠙]`,mymr:`[၀-၉]`,orya:`[୦-୯]`,tamldec:`[௦-௯]`,telu:`[౦-౯]`,thai:`[๐-๙]`,tibt:`[༠-༩]`,latn:`\\d`},qs={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]},Js=Ks.hanidec.replace(/[\[|\]]/g,``).split(``);function Ys(e){let t=parseInt(e,10);if(isNaN(t)){t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(e[n].search(Ks.hanidec)!==-1)t+=Js.indexOf(e[n]);else for(let e in qs){let[n,i]=qs[e];r>=n&&r<=i&&(t+=r-n)}}return parseInt(t,10)}else return t}var Xs=new Map;function Zs(){Xs.clear()}function Qs({numberingSystem:e},t=``){let n=e||`latn`,r=Xs.get(n);r===void 0&&(r=new Map,Xs.set(n,r));let i=r.get(t);return i===void 0&&(i=RegExp(`${Ks[n]}${t}`),r.set(t,i)),i}var $s=()=>Date.now(),ec=`system`,tc=null,nc=null,rc=null,ic=60,ac,oc=null,P=class{static get now(){return $s}static set now(e){$s=e}static set defaultZone(e){ec=e}static get defaultZone(){return Gs(ec,us.instance)}static get defaultLocale(){return tc}static set defaultLocale(e){tc=e}static get defaultNumberingSystem(){return nc}static set defaultNumberingSystem(e){nc=e}static get defaultOutputCalendar(){return rc}static set defaultOutputCalendar(e){rc=e}static get defaultWeekSettings(){return oc}static set defaultWeekSettings(e){oc=Pc(e)}static get twoDigitCutoffYear(){return ic}static set twoDigitCutoffYear(e){ic=e%100}static get throwOnInvalid(){return ac}static set throwOnInvalid(e){ac=e}static resetCaches(){N.resetCache(),_s.resetCache(),R.resetCache(),Zs()}},sc=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},cc=[0,31,59,90,120,151,181,212,243,273,304,334],lc=[0,31,60,91,121,152,182,213,244,274,305,335];function uc(e,t){return new sc(`unit out of range`,`you specified ${t} (of type ${typeof t}) as a ${e}, which is invalid`)}function dc(e,t,n){let r=new Date(Date.UTC(e,t-1,n));e<100&&e>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let i=r.getUTCDay();return i===0?7:i}function fc(e,t,n){return n+(Vc(e)?lc:cc)[t-1]}function pc(e,t){let n=Vc(e)?lc:cc,r=n.findIndex(e=>e<t),i=t-n[r];return{month:r+1,day:i}}function mc(e,t){return(e-t+7)%7+1}function hc(e,t=4,n=1){let{year:r,month:i,day:a}=e,o=fc(r,i,a),s=mc(dc(r,i,a),n),c=Math.floor((o-s+14-t)/7),l;return c<1?(l=r-1,c=Kc(l,t,n)):c>Kc(r,t,n)?(l=r+1,c=1):l=r,{weekYear:l,weekNumber:c,weekday:s,...$c(e)}}function gc(e,t=4,n=1){let{weekYear:r,weekNumber:i,weekday:a}=e,o=mc(dc(r,1,t),n),s=Hc(r),c=i*7+a-o-7+t,l;c<1?(l=r-1,c+=Hc(l)):c>s?(l=r+1,c-=Hc(r)):l=r;let{month:u,day:d}=pc(l,c);return{year:l,month:u,day:d,...$c(e)}}function _c(e){let{year:t,month:n,day:r}=e;return{year:t,ordinal:fc(t,n,r),...$c(e)}}function vc(e){let{year:t,ordinal:n}=e,{month:r,day:i}=pc(t,n);return{year:t,month:r,day:i,...$c(e)}}function yc(e,t){if(!F(e.localWeekday)||!F(e.localWeekNumber)||!F(e.localWeekYear)){if(!F(e.weekday)||!F(e.weekNumber)||!F(e.weekYear))throw new Po(`Cannot mix locale-based week fields with ISO-based week fields`);return F(e.localWeekday)||(e.weekday=e.localWeekday),F(e.localWeekNumber)||(e.weekNumber=e.localWeekNumber),F(e.localWeekYear)||(e.weekYear=e.localWeekYear),delete e.localWeekday,delete e.localWeekNumber,delete e.localWeekYear,{minDaysInFirstWeek:t.getMinDaysInFirstWeek(),startOfWeek:t.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function bc(e,t=4,n=1){let r=Tc(e.weekYear),i=Fc(e.weekNumber,1,Kc(e.weekYear,t,n)),a=Fc(e.weekday,1,7);return r?i?a?!1:uc(`weekday`,e.weekday):uc(`week`,e.weekNumber):uc(`weekYear`,e.weekYear)}function xc(e){let t=Tc(e.year),n=Fc(e.ordinal,1,Hc(e.year));return t?n?!1:uc(`ordinal`,e.ordinal):uc(`year`,e.year)}function Sc(e){let t=Tc(e.year),n=Fc(e.month,1,12),r=Fc(e.day,1,Uc(e.year,e.month));return t?n?r?!1:uc(`day`,e.day):uc(`month`,e.month):uc(`year`,e.year)}function Cc(e){let{hour:t,minute:n,second:r,millisecond:i}=e,a=Fc(t,0,23)||t===24&&n===0&&r===0&&i===0,o=Fc(n,0,59),s=Fc(r,0,59),c=Fc(i,0,999);return a?o?s?c?!1:uc(`millisecond`,i):uc(`second`,r):uc(`minute`,n):uc(`hour`,t)}function F(e){return e===void 0}function wc(e){return typeof e==`number`}function Tc(e){return typeof e==`number`&&e%1==0}function Ec(e){return typeof e==`string`}function Dc(e){return Object.prototype.toString.call(e)===`[object Date]`}function Oc(){try{return typeof Intl<`u`&&!!Intl.RelativeTimeFormat}catch{return!1}}function kc(){try{return typeof Intl<`u`&&!!Intl.Locale&&(`weekInfo`in Intl.Locale.prototype||`getWeekInfo`in Intl.Locale.prototype)}catch{return!1}}function Ac(e){return Array.isArray(e)?e:[e]}function jc(e,t,n){if(e.length!==0)return e.reduce((e,r)=>{let i=[t(r),r];return e&&n(e[0],i[0])===e[0]?e:i},null)[1]}function Mc(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function Nc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Pc(e){if(e==null)return null;if(typeof e!=`object`)throw new Io(`Week settings must be an object`);if(!Fc(e.firstDay,1,7)||!Fc(e.minimalDays,1,7)||!Array.isArray(e.weekend)||e.weekend.some(e=>!Fc(e,1,7)))throw new Io(`Invalid week settings`);return{firstDay:e.firstDay,minimalDays:e.minimalDays,weekend:Array.from(e.weekend)}}function Fc(e,t,n){return Tc(e)&&e>=t&&e<=n}function Ic(e,t){return e-t*Math.floor(e/t)}function I(e,t=2){let n=e<0,r;return r=n?`-`+(``+-e).padStart(t,`0`):(``+e).padStart(t,`0`),r}function Lc(e){if(!(F(e)||e===null||e===``))return parseInt(e,10)}function Rc(e){if(!(F(e)||e===null||e===``))return parseFloat(e)}function zc(e){if(!(F(e)||e===null||e===``)){let t=parseFloat(`0.`+e)*1e3;return Math.floor(t)}}function Bc(e,t,n=`round`){let r=10**t;switch(n){case`expand`:return e>0?Math.ceil(e*r)/r:Math.floor(e*r)/r;case`trunc`:return Math.trunc(e*r)/r;case`round`:return Math.round(e*r)/r;case`floor`:return Math.floor(e*r)/r;case`ceil`:return Math.ceil(e*r)/r;default:throw RangeError(`Value rounding ${n} is out of range`)}}function Vc(e){return e%4==0&&(e%100!=0||e%400==0)}function Hc(e){return Vc(e)?366:365}function Uc(e,t){let n=Ic(t-1,12)+1,r=e+(t-n)/12;return n===2?Vc(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function Wc(e){let t=Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute,e.second,e.millisecond);return e.year<100&&e.year>=0&&(t=new Date(t),t.setUTCFullYear(e.year,e.month-1,e.day)),+t}function Gc(e,t,n){return-mc(dc(e,1,t),n)+t-1}function Kc(e,t=4,n=1){let r=Gc(e,t,n),i=Gc(e+1,t,n);return(Hc(e)-r+i)/7}function qc(e){return e>99?e:e>P.twoDigitCutoffYear?1900+e:2e3+e}function Jc(e,t,n,r=null){let i=new Date(e),a={hourCycle:`h23`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`};r&&(a.timeZone=r);let o={timeZoneName:t,...a},s=new Intl.DateTimeFormat(n,o).formatToParts(i).find(e=>e.type.toLowerCase()===`timezonename`);return s?s.value:null}function Yc(e,t){let n=parseInt(e,10);Number.isNaN(n)&&(n=0);let r=parseInt(t,10)||0,i=n<0||Object.is(n,-0)?-r:r;return n*60+i}function Xc(e){let t=Number(e);if(typeof e==`boolean`||e===``||!Number.isFinite(t))throw new Io(`Invalid unit value ${e}`);return t}function Zc(e,t){let n={};for(let r in e)if(Nc(e,r)){let i=e[r];if(i==null)continue;n[t(r)]=Xc(i)}return n}function Qc(e,t){let n=Math.trunc(Math.abs(e/60)),r=Math.trunc(Math.abs(e%60)),i=e>=0?`+`:`-`;switch(t){case`short`:return`${i}${I(n,2)}:${I(r,2)}`;case`narrow`:return`${i}${n}${r>0?`:${r}`:``}`;case`techie`:return`${i}${I(n,2)}${I(r,2)}`;default:throw RangeError(`Value format ${t} is out of range for property format`)}}function $c(e){return Mc(e,[`hour`,`minute`,`second`,`millisecond`])}var el=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],tl=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],nl=[`J`,`F`,`M`,`A`,`M`,`J`,`J`,`A`,`S`,`O`,`N`,`D`];function rl(e){switch(e){case`narrow`:return[...nl];case`short`:return[...tl];case`long`:return[...el];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}}var il=[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`],al=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],ol=[`M`,`T`,`W`,`T`,`F`,`S`,`S`];function sl(e){switch(e){case`narrow`:return[...ol];case`short`:return[...al];case`long`:return[...il];case`numeric`:return[`1`,`2`,`3`,`4`,`5`,`6`,`7`];default:return null}}var cl=[`AM`,`PM`],ll=[`Before Christ`,`Anno Domini`],ul=[`BC`,`AD`],dl=[`B`,`A`];function fl(e){switch(e){case`narrow`:return[...dl];case`short`:return[...ul];case`long`:return[...ll];default:return null}}function pl(e){return cl[e.hour<12?0:1]}function ml(e,t){return sl(t)[e.weekday-1]}function hl(e,t){return rl(t)[e.month-1]}function gl(e,t){return fl(t)[e.year<0?0:1]}function _l(e,t,n=`always`,r=!1){let i={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.`]},a=[`hours`,`minutes`,`seconds`].indexOf(e)===-1;if(n===`auto`&&a){let n=e===`days`;switch(t){case 1:return n?`tomorrow`:`next ${i[e][0]}`;case-1:return n?`yesterday`:`last ${i[e][0]}`;case 0:return n?`today`:`this ${i[e][0]}`}}let o=Object.is(t,-0)||t<0,s=Math.abs(t),c=s===1,l=i[e],u=r?c?l[1]:l[2]||l[1]:c?i[e][0]:e;return o?`${s} ${u} ago`:`in ${s} ${u}`}function vl(e,t){let n=``;for(let r of e)r.literal?n+=r.val:n+=t(r.val);return n}var yl={D:Bo,DD:Vo,DDD:Uo,DDDD:Wo,t:Go,tt:Ko,ttt:qo,tttt:Jo,T:Yo,TT:Xo,TTT:Zo,TTTT:Qo,f:$o,ff:ts,fff:is,ffff:os,F:es,FF:ns,FFF:as,FFFF:ss},bl=class e{static create(t,n={}){return new e(t,n)}static parseFormat(e){let t=null,n=``,r=!1,i=[];for(let a=0;a<e.length;a++){let o=e.charAt(a);o===`'`?((n.length>0||r)&&i.push({literal:r||/^\s+$/.test(n),val:n===``?`'`:n}),t=null,n=``,r=!r):r||o===t?n+=o:(n.length>0&&i.push({literal:/^\s+$/.test(n),val:n}),n=o,t=o)}return n.length>0&&i.push({literal:r||/^\s+$/.test(n),val:n}),i}static macroTokenToFormatOpts(e){return yl[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,n=void 0){if(this.opts.forceSimple)return I(e,t);let r={...this.opts};return t>0&&(r.padTo=t),n&&(r.signDisplay=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(t,n){let r=this.loc.listingMode()===`en`,i=this.loc.outputCalendar&&this.loc.outputCalendar!==`gregory`,a=(e,n)=>this.loc.extract(t,e,n),o=e=>t.isOffsetFixed&&t.offset===0&&e.allowZ?`Z`:t.isValid?t.zone.formatOffset(t.ts,e.format):``,s=()=>r?pl(t):a({hour:`numeric`,hourCycle:`h12`},`dayperiod`),c=(e,n)=>r?hl(t,e):a(n?{month:e}:{month:e,day:`numeric`},`month`),l=(e,n)=>r?ml(t,e):a(n?{weekday:e}:{weekday:e,month:`long`,day:`numeric`},`weekday`),u=n=>{let r=e.macroTokenToFormatOpts(n);return r?this.formatWithSystemDefault(t,r):n},d=e=>r?gl(t,e):a({era:e},`era`);return vl(e.parseFormat(n),e=>{switch(e){case`S`:return this.num(t.millisecond);case`u`:case`SSS`:return this.num(t.millisecond,3);case`s`:return this.num(t.second);case`ss`:return this.num(t.second,2);case`uu`:return this.num(Math.floor(t.millisecond/10),2);case`uuu`:return this.num(Math.floor(t.millisecond/100));case`m`:return this.num(t.minute);case`mm`:return this.num(t.minute,2);case`h`:return this.num(t.hour%12==0?12:t.hour%12);case`hh`:return this.num(t.hour%12==0?12:t.hour%12,2);case`H`:return this.num(t.hour);case`HH`:return this.num(t.hour,2);case`Z`:return o({format:`narrow`,allowZ:this.opts.allowZ});case`ZZ`:return o({format:`short`,allowZ:this.opts.allowZ});case`ZZZ`:return o({format:`techie`,allowZ:this.opts.allowZ});case`ZZZZ`:return t.zone.offsetName(t.ts,{format:`short`,locale:this.loc.locale});case`ZZZZZ`:return t.zone.offsetName(t.ts,{format:`long`,locale:this.loc.locale});case`z`:return t.zoneName;case`a`:return s();case`d`:return i?a({day:`numeric`},`day`):this.num(t.day);case`dd`:return i?a({day:`2-digit`},`day`):this.num(t.day,2);case`c`:return this.num(t.weekday);case`ccc`:return l(`short`,!0);case`cccc`:return l(`long`,!0);case`ccccc`:return l(`narrow`,!0);case`E`:return this.num(t.weekday);case`EEE`:return l(`short`,!1);case`EEEE`:return l(`long`,!1);case`EEEEE`:return l(`narrow`,!1);case`L`:return i?a({month:`numeric`,day:`numeric`},`month`):this.num(t.month);case`LL`:return i?a({month:`2-digit`,day:`numeric`},`month`):this.num(t.month,2);case`LLL`:return c(`short`,!0);case`LLLL`:return c(`long`,!0);case`LLLLL`:return c(`narrow`,!0);case`M`:return i?a({month:`numeric`},`month`):this.num(t.month);case`MM`:return i?a({month:`2-digit`},`month`):this.num(t.month,2);case`MMM`:return c(`short`,!1);case`MMMM`:return c(`long`,!1);case`MMMMM`:return c(`narrow`,!1);case`y`:return i?a({year:`numeric`},`year`):this.num(t.year);case`yy`:return i?a({year:`2-digit`},`year`):this.num(t.year.toString().slice(-2),2);case`yyyy`:return i?a({year:`numeric`},`year`):this.num(t.year,4);case`yyyyyy`:return i?a({year:`numeric`},`year`):this.num(t.year,6);case`G`:return d(`short`);case`GG`:return d(`long`);case`GGGGG`:return d(`narrow`);case`kk`:return this.num(t.weekYear.toString().slice(-2),2);case`kkkk`:return this.num(t.weekYear,4);case`W`:return this.num(t.weekNumber);case`WW`:return this.num(t.weekNumber,2);case`n`:return this.num(t.localWeekNumber);case`nn`:return this.num(t.localWeekNumber,2);case`ii`:return this.num(t.localWeekYear.toString().slice(-2),2);case`iiii`:return this.num(t.localWeekYear,4);case`o`:return this.num(t.ordinal);case`ooo`:return this.num(t.ordinal,3);case`q`:return this.num(t.quarter);case`qq`:return this.num(t.quarter,2);case`X`:return this.num(Math.floor(t.ts/1e3));case`x`:return this.num(t.ts);default:return u(e)}})}formatDurationFromString(t,n){let r=this.opts.signMode===`negativeLargestOnly`?-1:1,i=e=>{switch(e[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}},a=(e,t)=>n=>{let a=i(n);if(a){let i=t.isNegativeDuration&&a!==t.largestUnit?r:1,o;return o=this.opts.signMode===`negativeLargestOnly`&&a!==t.largestUnit?`never`:this.opts.signMode===`all`?`always`:`auto`,this.num(e.get(a)*i,n.length,o)}else return n},o=e.parseFormat(n),s=o.reduce((e,{literal:t,val:n})=>t?e:e.concat(n),[]),c=t.shiftTo(...s.map(i).filter(e=>e));return vl(o,a(c,{isNegativeDuration:c<0,largestUnit:Object.keys(c.values)[0]}))}},xl=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Sl(...e){let t=e.reduce((e,t)=>e+t.source,``);return RegExp(`^${t}$`)}function Cl(...e){return t=>e.reduce(([e,n,r],i)=>{let[a,o,s]=i(t,r);return[{...e,...a},o||n,s]},[{},null,1]).slice(0,2)}function wl(e,...t){if(e==null)return[null,null];for(let[n,r]of t){let t=n.exec(e);if(t)return r(t)}return[null,null]}function Tl(...e){return(t,n)=>{let r={},i;for(i=0;i<e.length;i++)r[e[i]]=Lc(t[n+i]);return[r,null,n+i]}}var El=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Dl=`(?:${El.source}?(?:\\[(${xl.source})\\])?)?`,Ol=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,kl=RegExp(`${Ol.source}${Dl}`),Al=RegExp(`(?:[Tt]${kl.source})?`),jl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Ml=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Nl=/(\d{4})-?(\d{3})/,Pl=Tl(`weekYear`,`weekNumber`,`weekDay`),Fl=Tl(`year`,`ordinal`),Il=/(\d{4})-(\d\d)-(\d\d)/,Ll=RegExp(`${Ol.source} ?(?:${El.source}|(${xl.source}))?`),Rl=RegExp(`(?: ${Ll.source})?`);function zl(e,t,n){let r=e[t];return F(r)?n:Lc(r)}function Bl(e,t){return[{year:zl(e,t),month:zl(e,t+1,1),day:zl(e,t+2,1)},null,t+3]}function Vl(e,t){return[{hours:zl(e,t,0),minutes:zl(e,t+1,0),seconds:zl(e,t+2,0),milliseconds:zc(e[t+3])},null,t+4]}function Hl(e,t){let n=!e[t]&&!e[t+1],r=Yc(e[t+1],e[t+2]);return[{},n?null:Us.instance(r),t+3]}function Ul(e,t){return[{},e[t]?_s.create(e[t]):null,t+1]}var Wl=RegExp(`^T?${Ol.source}$`),Gl=/^-?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 Kl(e){let[t,n,r,i,a,o,s,c,l]=e,u=t[0]===`-`,d=c&&c[0]===`-`,f=(e,t=!1)=>e!==void 0&&(t||e&&u)?-e:e;return[{years:f(Rc(n)),months:f(Rc(r)),weeks:f(Rc(i)),days:f(Rc(a)),hours:f(Rc(o)),minutes:f(Rc(s)),seconds:f(Rc(c),c===`-0`),milliseconds:f(zc(l),d)}]}var ql={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Jl(e,t,n,r,i,a,o){let s={year:t.length===2?qc(Lc(t)):Lc(t),month:tl.indexOf(n)+1,day:Lc(r),hour:Lc(i),minute:Lc(a)};return o&&(s.second=Lc(o)),e&&(s.weekday=e.length>3?il.indexOf(e)+1:al.indexOf(e)+1),s}var Yl=/^(?:(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 Xl(e){let[,t,n,r,i,a,o,s,c,l,u,d]=e,f=Jl(t,i,r,n,a,o,s),p;return p=c?ql[c]:l?0:Yc(u,d),[f,new Us(p)]}function Zl(e){return e.replace(/\([^()]*\)|[\n\t]/g,` `).replace(/(\s\s+)/g,` `).trim()}var Ql=/^(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$/,$l=/^(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$/,eu=/^(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 tu(e){let[,t,n,r,i,a,o,s]=e;return[Jl(t,i,r,n,a,o,s),Us.utcInstance]}function nu(e){let[,t,n,r,i,a,o,s]=e;return[Jl(t,s,n,r,i,a,o),Us.utcInstance]}var ru=Sl(jl,Al),iu=Sl(Ml,Al),au=Sl(Nl,Al),ou=Sl(kl),su=Cl(Bl,Vl,Hl,Ul),cu=Cl(Pl,Vl,Hl,Ul),lu=Cl(Fl,Vl,Hl,Ul),uu=Cl(Vl,Hl,Ul);function du(e){return wl(e,[ru,su],[iu,cu],[au,lu],[ou,uu])}function fu(e){return wl(Zl(e),[Yl,Xl])}function pu(e){return wl(e,[Ql,tu],[$l,tu],[eu,nu])}function mu(e){return wl(e,[Gl,Kl])}var hu=Cl(Vl);function gu(e){return wl(e,[Wl,hu])}var _u=Sl(Il,Rl),vu=Sl(Ll),yu=Cl(Vl,Hl,Ul);function bu(e){return wl(e,[_u,su],[vu,yu])}var xu=`Invalid Duration`,Su={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}},Cu={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},...Su},wu=146097/400,Tu=146097/4800,Eu={years:{quarters:4,months:12,weeks:wu/7,days:wu,hours:wu*24,minutes:wu*24*60,seconds:wu*24*60*60,milliseconds:wu*24*60*60*1e3},quarters:{months:3,weeks:wu/28,days:wu/4,hours:wu*24/4,minutes:wu*24*60/4,seconds:wu*24*60*60/4,milliseconds:wu*24*60*60*1e3/4},months:{weeks:Tu/7,days:Tu,hours:Tu*24,minutes:Tu*24*60,seconds:Tu*24*60*60,milliseconds:Tu*24*60*60*1e3},...Su},Du=[`years`,`quarters`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`],Ou=Du.slice(0).reverse();function ku(e,t,n=!1){return new Nu({values:n?t.values:{...e.values,...t.values||{}},loc:e.loc.clone(t.loc),conversionAccuracy:t.conversionAccuracy||e.conversionAccuracy,matrix:t.matrix||e.matrix})}function Au(e,t){let n=t.milliseconds??0;for(let r of Ou.slice(1))t[r]&&(n+=t[r]*e[r].milliseconds);return n}function ju(e,t){let n=Au(e,t)<0?-1:1;Du.reduceRight((r,i)=>{if(F(t[i]))return r;if(r){let a=t[r]*n,o=e[i][r],s=Math.floor(a/o);t[i]+=s*n,t[r]-=s*o*n}return i},null),Du.reduce((n,r)=>{if(F(t[r]))return n;if(n){let i=t[n]%1;t[n]-=i,t[r]+=i*e[n][r]}return r},null)}function Mu(e){let t={};for(let[n,r]of Object.entries(e))r!==0&&(t[n]=r);return t}var Nu=class e{constructor(e){let t=e.conversionAccuracy===`longterm`||!1,n=t?Eu:Cu;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||N.create(),this.conversionAccuracy=t?`longterm`:`casual`,this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(t,n){return e.fromObject({milliseconds:t},n)}static fromObject(t,n={}){if(typeof t!=`object`||!t)throw new Io(`Duration.fromObject: argument expected to be an object, got ${t===null?`null`:typeof t}`);return new e({values:Zc(t,e.normalizeUnit),loc:N.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(t){if(wc(t))return e.fromMillis(t);if(e.isDuration(t))return t;if(typeof t==`object`)return e.fromObject(t);throw new Io(`Unknown duration argument ${t} of type ${typeof t}`)}static fromISO(t,n){let[r]=mu(t);return r?e.fromObject(r,n):e.invalid(`unparsable`,`the input "${t}" can't be parsed as ISO 8601`)}static fromISOTime(t,n){let[r]=gu(t);return r?e.fromObject(r,n):e.invalid(`unparsable`,`the input "${t}" can't be parsed as ISO 8601`)}static invalid(t,n=null){if(!t)throw new Io(`need to specify a reason the Duration is invalid`);let r=t instanceof sc?t:new sc(t,n);if(P.throwOnInvalid)throw new No(r);return new e({invalid:r})}static normalizeUnit(e){let t={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(!t)throw new Fo(e);return t}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,t={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?bl.create(this.loc,n).formatDurationFromString(this,e):xu}toHuman(e={}){if(!this.isValid)return xu;let t=e.showZeros!==!1,n=Du.map(n=>{let r=this.values[n];return F(r)||r===0&&!t?null:this.loc.numberFormatter({style:`unit`,unitDisplay:`long`,...e,unit:n.slice(0,-1)}).format(r)}).filter(e=>e);return this.loc.listFormatter({type:`conjunction`,style:e.listStyle||`narrow`,...e}).format(n)}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+=Bc(this.seconds+this.milliseconds/1e3,3)+`S`),e===`P`&&(e+=`T0S`),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:`extended`,...e,includeOffset:!1},R.fromMillis(t,{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?Au(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(t){if(!this.isValid)return this;let n=e.fromDurationLike(t),r={};for(let e of Du)(Nc(n.values,e)||Nc(this.values,e))&&(r[e]=n.get(e)+this.get(e));return ku(this,{values:r},!0)}minus(t){if(!this.isValid)return this;let n=e.fromDurationLike(t);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=Xc(e(this.values[n],n));return ku(this,{values:t},!0)}get(t){return this[e.normalizeUnit(t)]}set(t){if(!this.isValid)return this;let n={...this.values,...Zc(t,e.normalizeUnit)};return ku(this,{values:n})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:r}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:r,conversionAccuracy:n};return ku(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return ju(this.matrix,e),ku(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Mu(this.normalize().shiftToAll().toObject());return ku(this,{values:e},!0)}shiftTo(...t){if(!this.isValid||t.length===0)return this;t=t.map(t=>e.normalizeUnit(t));let n={},r={},i=this.toObject(),a;for(let e of Du)if(t.indexOf(e)>=0){a=e;let t=0;for(let n in r)t+=this.matrix[n][e]*r[n],r[n]=0;wc(i[e])&&(t+=i[e]);let o=Math.trunc(t);n[e]=o,r[e]=(t*1e3-o*1e3)/1e3}else wc(i[e])&&(r[e]=i[e]);for(let e in r)r[e]!==0&&(n[a]+=e===a?r[e]:r[e]/this.matrix[a][e]);return ju(this.matrix,n),ku(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo(`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return ku(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;let e=Mu(this.values);return ku(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 t(e,t){return e===void 0||e===0?t===void 0||t===0:e===t}for(let n of Du)if(!t(this.values[n],e.values[n]))return!1;return!0}},Pu=`Invalid Interval`;function Fu(e,t){return!e||!e.isValid?Iu.invalid(`missing or invalid start`):!t||!t.isValid?Iu.invalid(`missing or invalid end`):t<e?Iu.invalid(`end before start`,`The end of an interval must be after its start, but you had start=${e.toISO()} and end=${t.toISO()}`):null}var Iu=class e{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(t,n=null){if(!t)throw new Io(`need to specify a reason the Interval is invalid`);let r=t instanceof sc?t:new sc(t,n);if(P.throwOnInvalid)throw new Mo(r);return new e({invalid:r})}static fromDateTimes(t,n){let r=Rd(t),i=Rd(n);return Fu(r,i)??new e({start:r,end:i})}static after(t,n){let r=Nu.fromDurationLike(n),i=Rd(t);return e.fromDateTimes(i,i.plus(r))}static before(t,n){let r=Nu.fromDurationLike(n),i=Rd(t);return e.fromDateTimes(i.minus(r),i)}static fromISO(t,n){let[r,i]=(t||``).split(`/`,2);if(r&&i){let t,a;try{t=R.fromISO(r,n),a=t.isValid}catch{a=!1}let o,s;try{o=R.fromISO(i,n),s=o.isValid}catch{s=!1}if(a&&s)return e.fromDateTimes(t,o);if(a){let r=Nu.fromISO(i,n);if(r.isValid)return e.after(t,r)}else if(s){let t=Nu.fromISO(r,n);if(t.isValid)return e.before(o,t)}}return e.invalid(`unparsable`,`the input "${t}" 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`,t){if(!this.isValid)return NaN;let n=this.start.startOf(e,t),r;return r=t?.useLocaleWeeks?this.end.reconfigure({locale:n.locale}):this.end,r=r.startOf(e,t),Math.floor(r.diff(n,e).get(e))+(r.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:t,end:n}={}){return this.isValid?e.fromDateTimes(t||this.s,n||this.e):this}splitAt(...t){if(!this.isValid)return[];let n=t.map(Rd).filter(e=>this.contains(e)).sort((e,t)=>e.toMillis()-t.toMillis()),r=[],{s:i}=this,a=0;for(;i<this.e;){let t=n[a]||this.e,o=+t>+this.e?this.e:t;r.push(e.fromDateTimes(i,o)),i=o,a+=1}return r}splitBy(t){let n=Nu.fromDurationLike(t);if(!this.isValid||!n.isValid||n.as(`milliseconds`)===0)return[];let{s:r}=this,i=1,a,o=[];for(;r<this.e;){let t=this.start.plus(n.mapUnits(e=>e*i));a=+t>+this.e?this.e:t,o.push(e.fromDateTimes(r,a)),r=a,i+=1}return o}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(t){if(!this.isValid)return this;let n=this.s>t.s?this.s:t.s,r=this.e<t.e?this.e:t.e;return n>=r?null:e.fromDateTimes(n,r)}union(t){if(!this.isValid)return this;let n=this.s<t.s?this.s:t.s,r=this.e>t.e?this.e:t.e;return e.fromDateTimes(n,r)}static merge(e){let[t,n]=e.sort((e,t)=>e.s-t.s).reduce(([e,t],n)=>t?t.overlaps(n)||t.abutsStart(n)?[e,t.union(n)]:[e.concat([t]),n]:[e,n],[[],null]);return n&&t.push(n),t}static xor(t){let n=null,r=0,i=[],a=t.map(e=>[{time:e.s,type:`s`},{time:e.e,type:`e`}]),o=Array.prototype.concat(...a).sort((e,t)=>e.time-t.time);for(let t of o)r+=t.type===`s`?1:-1,r===1?n=t.time:(n&&+n!=+t.time&&i.push(e.fromDateTimes(n,t.time)),n=null);return e.merge(i)}difference(...t){return e.xor([this].concat(t)).map(e=>this.intersection(e)).filter(e=>e&&!e.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Pu}[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=Bo,t={}){return this.isValid?bl.create(this.s.loc.clone(t),e).formatInterval(this):Pu}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Pu}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Pu}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Pu}toFormat(e,{separator:t=` – `}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Pu}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):Nu.invalid(this.invalidReason)}mapEndpoints(t){return e.fromDateTimes(t(this.s),t(this.e))}},Lu=class{static hasDST(e=P.defaultZone){let t=R.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return _s.isValidZone(e)}static normalizeZone(e){return Gs(e,P.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||N.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||N.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||N.create(e)).getWeekendDays().slice()}static months(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null,outputCalendar:i=`gregory`}={}){return(r||N.create(t,n,i)).months(e)}static monthsFormat(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null,outputCalendar:i=`gregory`}={}){return(r||N.create(t,n,i)).months(e,!0)}static weekdays(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null}={}){return(r||N.create(t,n,null)).weekdays(e)}static weekdaysFormat(e=`long`,{locale:t=null,numberingSystem:n=null,locObj:r=null}={}){return(r||N.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return N.create(e).meridiems()}static eras(e=`short`,{locale:t=null}={}){return N.create(t,null,`gregory`).eras(e)}static features(){return{relative:Oc(),localeWeek:kc()}}};function Ru(e,t){let n=e=>e.toUTC(0,{keepLocalTime:!0}).startOf(`day`).valueOf(),r=n(t)-n(e);return Math.floor(Nu.fromMillis(r).as(`days`))}function zu(e,t,n){let r=[[`years`,(e,t)=>t.year-e.year],[`quarters`,(e,t)=>t.quarter-e.quarter+(t.year-e.year)*4],[`months`,(e,t)=>t.month-e.month+(t.year-e.year)*12],[`weeks`,(e,t)=>{let n=Ru(e,t);return(n-n%7)/7}],[`days`,Ru]],i={},a=e,o,s;for(let[c,l]of r)n.indexOf(c)>=0&&(o=c,i[c]=l(e,t),s=a.plus(i),s>t?(i[c]--,e=a.plus(i),e>t&&(s=e,i[c]--,e=a.plus(i))):e=s);return[e,i,s,o]}function Bu(e,t,n,r){let[i,a,o,s]=zu(e,t,n),c=t-i,l=n.filter(e=>[`hours`,`minutes`,`seconds`,`milliseconds`].indexOf(e)>=0);l.length===0&&(o<t&&(o=i.plus({[s]:1})),o!==i&&(a[s]=(a[s]||0)+c/(o-i)));let u=Nu.fromObject(a,r);return l.length>0?Nu.fromMillis(c,r).shiftTo(...l).plus(u):u}var Vu=`missing Intl.DateTimeFormat.formatToParts support`;function L(e,t=e=>e){return{regex:e,deser:([e])=>t(Ys(e))}}var Hu=`[ \xA0]`,Uu=new RegExp(Hu,`g`);function Wu(e){return e.replace(/\./g,`\\.?`).replace(Uu,Hu)}function Gu(e){return e.replace(/\./g,``).replace(Uu,` `).toLowerCase()}function Ku(e,t){return e===null?null:{regex:RegExp(e.map(Wu).join(`|`)),deser:([n])=>e.findIndex(e=>Gu(n)===Gu(e))+t}}function qu(e,t){return{regex:e,deser:([,e,t])=>Yc(e,t),groups:t}}function Ju(e){return{regex:e,deser:([e])=>e}}function Yu(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function Xu(e,t){let n=Qs(t),r=Qs(t,`{2}`),i=Qs(t,`{3}`),a=Qs(t,`{4}`),o=Qs(t,`{6}`),s=Qs(t,`{1,2}`),c=Qs(t,`{1,3}`),l=Qs(t,`{1,6}`),u=Qs(t,`{1,9}`),d=Qs(t,`{2,4}`),f=Qs(t,`{4,6}`),p=e=>({regex:RegExp(Yu(e.val)),deser:([e])=>e,literal:!0}),m=(m=>{if(e.literal)return p(m);switch(m.val){case`G`:return Ku(t.eras(`short`),0);case`GG`:return Ku(t.eras(`long`),0);case`y`:return L(l);case`yy`:return L(d,qc);case`yyyy`:return L(a);case`yyyyy`:return L(f);case`yyyyyy`:return L(o);case`M`:return L(s);case`MM`:return L(r);case`MMM`:return Ku(t.months(`short`,!0),1);case`MMMM`:return Ku(t.months(`long`,!0),1);case`L`:return L(s);case`LL`:return L(r);case`LLL`:return Ku(t.months(`short`,!1),1);case`LLLL`:return Ku(t.months(`long`,!1),1);case`d`:return L(s);case`dd`:return L(r);case`o`:return L(c);case`ooo`:return L(i);case`HH`:return L(r);case`H`:return L(s);case`hh`:return L(r);case`h`:return L(s);case`mm`:return L(r);case`m`:return L(s);case`q`:return L(s);case`qq`:return L(r);case`s`:return L(s);case`ss`:return L(r);case`S`:return L(c);case`SSS`:return L(i);case`u`:return Ju(u);case`uu`:return Ju(s);case`uuu`:return L(n);case`a`:return Ku(t.meridiems(),0);case`kkkk`:return L(a);case`kk`:return L(d,qc);case`W`:return L(s);case`WW`:return L(r);case`E`:case`c`:return L(n);case`EEE`:return Ku(t.weekdays(`short`,!1),1);case`EEEE`:return Ku(t.weekdays(`long`,!1),1);case`ccc`:return Ku(t.weekdays(`short`,!0),1);case`cccc`:return Ku(t.weekdays(`long`,!0),1);case`Z`:case`ZZ`:return qu(RegExp(`([+-]${s.source})(?::(${r.source}))?`),2);case`ZZZ`:return qu(RegExp(`([+-]${s.source})(${r.source})?`),2);case`z`:return Ju(/[a-z_+-/]{1,256}?/i);case` `:return Ju(/[^\S\n\r]/);default:return p(m)}})(e)||{invalidReason:Vu};return m.token=e,m}var Zu={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 Qu(e,t,n){let{type:r,value:i}=e;if(r===`literal`){let e=/^\s+$/.test(i);return{literal:!e,val:e?` `:i}}let a=t[r],o=r;r===`hour`&&(o=t.hour12==null?t.hourCycle==null?n.hour12?`hour12`:`hour24`:t.hourCycle===`h11`||t.hourCycle===`h12`?`hour12`:`hour24`:t.hour12?`hour12`:`hour24`);let s=Zu[o];if(typeof s==`object`&&(s=s[a]),s)return{literal:!1,val:s}}function $u(e){return[`^${e.map(e=>e.regex).reduce((e,t)=>`${e}(${t.source})`,``)}$`,e]}function ed(e,t,n){let r=e.match(t);if(r){let e={},t=1;for(let i in n)if(Nc(n,i)){let a=n[i],o=a.groups?a.groups+1:1;!a.literal&&a.token&&(e[a.token.val[0]]=a.deser(r.slice(t,t+o))),t+=o}return[r,e]}else return[r,{}]}function td(e){let t=e=>{switch(e){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}},n=null,r;return F(e.z)||(n=_s.create(e.z)),F(e.Z)||(n||=new Us(e.Z),r=e.Z),F(e.q)||(e.M=(e.q-1)*3+1),F(e.h)||(e.h<12&&e.a===1?e.h+=12:e.h===12&&e.a===0&&(e.h=0)),e.G===0&&e.y&&(e.y=-e.y),F(e.u)||(e.S=zc(e.u)),[Object.keys(e).reduce((n,r)=>{let i=t(r);return i&&(n[i]=e[r]),n},{}),n,r]}var nd=null;function rd(){return nd||=R.fromMillis(1555555555555),nd}function id(e,t){if(e.literal)return e;let n=ld(bl.macroTokenToFormatOpts(e.val),t);return n==null||n.includes(void 0)?e:n}function ad(e,t){return Array.prototype.concat(...e.map(e=>id(e,t)))}var od=class{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=ad(bl.parseFormat(t),e),this.units=this.tokens.map(t=>Xu(t,e)),this.disqualifyingUnit=this.units.find(e=>e.invalidReason),!this.disqualifyingUnit){let[e,t]=$u(this.units);this.regex=RegExp(e,`i`),this.handlers=t}}explainFromTokens(e){if(this.isValid){let[t,n]=ed(e,this.regex,this.handlers),[r,i,a]=n?td(n):[null,null,void 0];if(Nc(n,`a`)&&Nc(n,`H`))throw new Po(`Can't include meridiem when specifying 24-hour format`);return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:n,result:r,zone:i,specificOffset:a}}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 sd(e,t,n){return new od(e,n).explainFromTokens(t)}function cd(e,t,n){let{result:r,zone:i,specificOffset:a,invalidReason:o}=sd(e,t,n);return[r,i,a,o]}function ld(e,t){if(!e)return null;let n=bl.create(t,e).dtFormatter(rd()),r=n.formatToParts(),i=n.resolvedOptions();return r.map(t=>Qu(t,e,i))}var ud=`Invalid DateTime`,dd=864e13;function fd(e){return new sc(`unsupported zone`,`the zone "${e.name}" is not supported`)}function pd(e){return e.weekData===null&&(e.weekData=hc(e.c)),e.weekData}function md(e){return e.localWeekData===null&&(e.localWeekData=hc(e.c,e.loc.getMinDaysInFirstWeek(),e.loc.getStartOfWeek())),e.localWeekData}function hd(e,t){let n={ts:e.ts,zone:e.zone,c:e.c,o:e.o,loc:e.loc,invalid:e.invalid};return new R({...n,...t,old:n})}function gd(e,t,n){let r=e-t*60*1e3,i=n.offset(r);if(t===i)return[r,t];r-=(i-t)*60*1e3;let a=n.offset(r);return i===a?[r,i]:[e-Math.min(i,a)*60*1e3,Math.max(i,a)]}function _d(e,t){e+=t*60*1e3;let n=new Date(e);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function vd(e,t,n){return gd(Wc(e),t,n)}function yd(e,t){let n=e.o,r=e.c.year+Math.trunc(t.years),i=e.c.month+Math.trunc(t.months)+Math.trunc(t.quarters)*3,a={...e.c,year:r,month:i,day:Math.min(e.c.day,Uc(r,i))+Math.trunc(t.days)+Math.trunc(t.weeks)*7},o=Nu.fromObject({years:t.years-Math.trunc(t.years),quarters:t.quarters-Math.trunc(t.quarters),months:t.months-Math.trunc(t.months),weeks:t.weeks-Math.trunc(t.weeks),days:t.days-Math.trunc(t.days),hours:t.hours,minutes:t.minutes,seconds:t.seconds,milliseconds:t.milliseconds}).as(`milliseconds`),[s,c]=gd(Wc(a),n,e.zone);return o!==0&&(s+=o,c=e.zone.offset(s)),{ts:s,o:c}}function bd(e,t,n,r,i,a){let{setZone:o,zone:s}=n;if(e&&Object.keys(e).length!==0||t){let r=t||s,i=R.fromObject(e,{...n,zone:r,specificOffset:a});return o?i:i.setZone(s)}else return R.invalid(new sc(`unparsable`,`the input "${i}" can't be parsed as ${r}`))}function xd(e,t,n=!0){return e.isValid?bl.create(N.create(`en-US`),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(e,t):null}function Sd(e,t,n){let r=e.c.year>9999||e.c.year<0,i=``;if(r&&e.c.year>=0&&(i+=`+`),i+=I(e.c.year,r?6:4),n===`year`)return i;if(t){if(i+=`-`,i+=I(e.c.month),n===`month`)return i;i+=`-`}else if(i+=I(e.c.month),n===`month`)return i;return i+=I(e.c.day),i}function Cd(e,t,n,r,i,a,o){let s=!n||e.c.millisecond!==0||e.c.second!==0,c=``;switch(o){case`day`:case`month`:case`year`:break;default:if(c+=I(e.c.hour),o===`hour`)break;if(t){if(c+=`:`,c+=I(e.c.minute),o===`minute`)break;s&&(c+=`:`,c+=I(e.c.second))}else{if(c+=I(e.c.minute),o===`minute`)break;s&&(c+=I(e.c.second))}if(o===`second`)break;s&&(!r||e.c.millisecond!==0)&&(c+=`.`,c+=I(e.c.millisecond,3))}return i&&(e.isOffsetFixed&&e.offset===0&&!a?c+=`Z`:e.o<0?(c+=`-`,c+=I(Math.trunc(-e.o/60)),c+=`:`,c+=I(Math.trunc(-e.o%60))):(c+=`+`,c+=I(Math.trunc(e.o/60)),c+=`:`,c+=I(Math.trunc(e.o%60)))),a&&(c+=`[`+e.zone.ianaName+`]`),c}var wd={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Td={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Ed={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Dd=[`year`,`month`,`day`,`hour`,`minute`,`second`,`millisecond`],Od=[`weekYear`,`weekNumber`,`weekday`,`hour`,`minute`,`second`,`millisecond`],kd=[`year`,`ordinal`,`hour`,`minute`,`second`,`millisecond`];function Ad(e){let t={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`}[e.toLowerCase()];if(!t)throw new Fo(e);return t}function jd(e){switch(e.toLowerCase()){case`localweekday`:case`localweekdays`:return`localWeekday`;case`localweeknumber`:case`localweeknumbers`:return`localWeekNumber`;case`localweekyear`:case`localweekyears`:return`localWeekYear`;default:return Ad(e)}}function Md(e){if(Id===void 0&&(Id=P.now()),e.type!==`iana`)return e.offset(Id);let t=e.name,n=Ld.get(t);return n===void 0&&(n=e.offset(Id),Ld.set(t,n)),n}function Nd(e,t){let n=Gs(t.zone,P.defaultZone);if(!n.isValid)return R.invalid(fd(n));let r=N.fromObject(t),i,a;if(F(e.year))i=P.now();else{for(let t of Dd)F(e[t])&&(e[t]=wd[t]);let t=Sc(e)||Cc(e);if(t)return R.invalid(t);let r=Md(n);[i,a]=vd(e,r,n)}return new R({ts:i,zone:n,loc:r,o:a})}function Pd(e,t,n){let r=F(n.round)?!0:n.round,i=F(n.rounding)?`trunc`:n.rounding,a=(e,a)=>(e=Bc(e,r||n.calendary?0:2,n.calendary?`round`:i),t.loc.clone(n).relFormatter(n).format(e,a)),o=r=>n.calendary?t.hasSame(e,r)?0:t.startOf(r).diff(e.startOf(r),r).get(r):t.diff(e,r).get(r);if(n.unit)return a(o(n.unit),n.unit);for(let e of n.units){let t=o(e);if(Math.abs(t)>=1)return a(t,e)}return a(e>t?-0:0,n.units[n.units.length-1])}function Fd(e){let t={},n;return e.length>0&&typeof e[e.length-1]==`object`?(t=e[e.length-1],n=Array.from(e).slice(0,e.length-1)):n=Array.from(e),[t,n]}var Id,Ld=new Map,R=class e{constructor(e){let t=e.zone||P.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new sc(`invalid input`):null)||(t.isValid?null:fd(t));this.ts=F(e.ts)?P.now():e.ts;let r=null,i=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[r,i]=[e.old.c,e.old.o];else{let a=wc(e.o)&&!e.old?e.o:t.offset(this.ts);r=_d(this.ts,a),n=Number.isNaN(r.year)?new sc(`invalid input`):null,r=n?null:r,i=n?null:a}this._zone=t,this.loc=e.loc||N.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new e({})}static local(){let[e,t]=Fd(arguments),[n,r,i,a,o,s,c]=t;return Nd({year:n,month:r,day:i,hour:a,minute:o,second:s,millisecond:c},e)}static utc(){let[e,t]=Fd(arguments),[n,r,i,a,o,s,c]=t;return e.zone=Us.utcInstance,Nd({year:n,month:r,day:i,hour:a,minute:o,second:s,millisecond:c},e)}static fromJSDate(t,n={}){let r=Dc(t)?t.valueOf():NaN;if(Number.isNaN(r))return e.invalid(`invalid input`);let i=Gs(n.zone,P.defaultZone);return i.isValid?new e({ts:r,zone:i,loc:N.fromObject(n)}):e.invalid(fd(i))}static fromMillis(t,n={}){if(!wc(t))throw new Io(`fromMillis requires a numerical input, but received a ${typeof t} with value ${t}`);return t<-dd||t>dd?e.invalid(`Timestamp out of range`):new e({ts:t,zone:Gs(n.zone,P.defaultZone),loc:N.fromObject(n)})}static fromSeconds(t,n={}){if(wc(t))return new e({ts:t*1e3,zone:Gs(n.zone,P.defaultZone),loc:N.fromObject(n)});throw new Io(`fromSeconds requires a numerical input`)}static fromObject(t,n={}){t||={};let r=Gs(n.zone,P.defaultZone);if(!r.isValid)return e.invalid(fd(r));let i=N.fromObject(n),a=Zc(t,jd),{minDaysInFirstWeek:o,startOfWeek:s}=yc(a,i),c=P.now(),l=F(n.specificOffset)?r.offset(c):n.specificOffset,u=!F(a.ordinal),d=!F(a.year),f=!F(a.month)||!F(a.day),p=d||f,m=a.weekYear||a.weekNumber;if((p||u)&&m)throw new Po(`Can't mix weekYear/weekNumber units with year/month/day or ordinals`);if(f&&u)throw new Po(`Can't mix ordinal dates with month/day`);let h=m||a.weekday&&!p,g,_,v=_d(c,l);h?(g=Od,_=Td,v=hc(v,o,s)):u?(g=kd,_=Ed,v=_c(v)):(g=Dd,_=wd);let y=!1;for(let e of g){let t=a[e];F(t)?y?a[e]=_[e]:a[e]=v[e]:y=!0}let b=(h?bc(a,o,s):u?xc(a):Sc(a))||Cc(a);if(b)return e.invalid(b);let[x,ee]=vd(h?gc(a,o,s):u?vc(a):a,l,r),te=new e({ts:x,zone:r,o:ee,loc:i});return a.weekday&&p&&t.weekday!==te.weekday?e.invalid(`mismatched weekday`,`you can't specify both a weekday of ${a.weekday} and a date of ${te.toISO()}`):te.isValid?te:e.invalid(te.invalid)}static fromISO(e,t={}){let[n,r]=du(e);return bd(n,r,t,`ISO 8601`,e)}static fromRFC2822(e,t={}){let[n,r]=fu(e);return bd(n,r,t,`RFC 2822`,e)}static fromHTTP(e,t={}){let[n,r]=pu(e);return bd(n,r,t,`HTTP`,t)}static fromFormat(t,n,r={}){if(F(t)||F(n))throw new Io(`fromFormat requires an input string and a format`);let{locale:i=null,numberingSystem:a=null}=r,[o,s,c,l]=cd(N.fromOpts({locale:i,numberingSystem:a,defaultToEN:!0}),t,n);return l?e.invalid(l):bd(o,s,r,`format ${n}`,t,c)}static fromString(t,n,r={}){return e.fromFormat(t,n,r)}static fromSQL(e,t={}){let[n,r]=bu(e);return bd(n,r,t,`SQL`,e)}static invalid(t,n=null){if(!t)throw new Io(`need to specify a reason the DateTime is invalid`);let r=t instanceof sc?t:new sc(t,n);if(P.throwOnInvalid)throw new jo(r);return new e({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=ld(e,N.fromObject(t));return n?n.map(e=>e?e.val:null).join(``):null}static expandFormat(e,t={}){return ad(bl.parseFormat(e),N.fromObject(t)).map(e=>e.val).join(``)}static resetCache(){Id=void 0,Ld.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?pd(this).weekYear:NaN}get weekNumber(){return this.isValid?pd(this).weekNumber:NaN}get weekday(){return this.isValid?pd(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?md(this).weekday:NaN}get localWeekNumber(){return this.isValid?md(this).weekNumber:NaN}get localWeekYear(){return this.isValid?md(this).weekYear:NaN}get ordinal(){return this.isValid?_c(this.c).ordinal:NaN}get monthShort(){return this.isValid?Lu.months(`short`,{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Lu.months(`long`,{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Lu.weekdays(`short`,{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Lu.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];let e=864e5,t=6e4,n=Wc(this.c),r=this.zone.offset(n-e),i=this.zone.offset(n+e),a=this.zone.offset(n-r*t),o=this.zone.offset(n-i*t);if(a===o)return[this];let s=n-a*t,c=n-o*t,l=_d(s,a),u=_d(c,o);return l.hour===u.hour&&l.minute===u.minute&&l.second===u.second&&l.millisecond===u.millisecond?[hd(this,{ts:s}),hd(this,{ts:c})]:[this]}get isInLeapYear(){return Vc(this.year)}get daysInMonth(){return Uc(this.year,this.month)}get daysInYear(){return this.isValid?Hc(this.year):NaN}get weeksInWeekYear(){return this.isValid?Kc(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Kc(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:r}=bl.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(Us.instance(e),t)}toLocal(){return this.setZone(P.defaultZone)}setZone(t,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(t=Gs(t,P.defaultZone),t.equals(this.zone))return this;if(t.isValid){let e=this.ts;if(n||r){let n=t.offset(this.ts),r=this.toObject();[e]=vd(r,n,t)}return hd(this,{ts:e,zone:t})}else return e.invalid(fd(t))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return hd(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=Zc(e,jd),{minDaysInFirstWeek:n,startOfWeek:r}=yc(t,this.loc),i=!F(t.weekYear)||!F(t.weekNumber)||!F(t.weekday),a=!F(t.ordinal),o=!F(t.year),s=!F(t.month)||!F(t.day),c=o||s,l=t.weekYear||t.weekNumber;if((c||a)&&l)throw new Po(`Can't mix weekYear/weekNumber units with year/month/day or ordinals`);if(s&&a)throw new Po(`Can't mix ordinal dates with month/day`);let u;i?u=gc({...hc(this.c,n,r),...t},n,r):F(t.ordinal)?(u={...this.toObject(),...t},F(t.day)&&(u.day=Math.min(Uc(u.year,u.month),u.day))):u=vc({..._c(this.c),...t});let[d,f]=vd(u,this.o,this.zone);return hd(this,{ts:d,o:f})}plus(e){if(!this.isValid)return this;let t=Nu.fromDurationLike(e);return hd(this,yd(this,t))}minus(e){if(!this.isValid)return this;let t=Nu.fromDurationLike(e).negate();return hd(this,yd(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let n={},r=Nu.normalizeUnit(e);switch(r){case`years`:n.month=1;case`quarters`:case`months`:n.day=1;case`weeks`:case`days`:n.hour=0;case`hours`:n.minute=0;case`minutes`:n.second=0;case`seconds`:n.millisecond=0;break}if(r===`weeks`)if(t){let e=this.loc.getStartOfWeek(),{weekday:t}=this;t<e&&(n.weekNumber=this.weekNumber-1),n.weekday=e}else n.weekday=1;return r===`quarters`&&(n.month=(Math.ceil(this.month/3)-1)*3+1),this.set(n)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?bl.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):ud}toLocaleString(e=Bo,t={}){return this.isValid?bl.create(this.loc.clone(t),e).formatDateTime(this):ud}toLocaleParts(e={}){return this.isValid?bl.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e=`extended`,suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:r=!0,extendedZone:i=!1,precision:a=`milliseconds`}={}){if(!this.isValid)return null;a=Ad(a);let o=e===`extended`,s=Sd(this,o,a);return Dd.indexOf(a)>=3&&(s+=`T`),s+=Cd(this,o,t,n,r,i,a),s}toISODate({format:e=`extended`,precision:t=`day`}={}){return this.isValid?Sd(this,e===`extended`,Ad(t)):null}toISOWeekDate(){return xd(this,`kkkk-'W'WW-c`)}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:r=!1,extendedZone:i=!1,format:a=`extended`,precision:o=`milliseconds`}={}){return this.isValid?(o=Ad(o),(r&&Dd.indexOf(o)>=3?`T`:``)+Cd(this,a===`extended`,t,e,n,i,o)):null}toRFC2822(){return xd(this,`EEE, dd LLL yyyy HH:mm:ss ZZZ`,!1)}toHTTP(){return xd(this.toUTC(),`EEE, dd LLL yyyy HH:mm:ss 'GMT'`)}toSQLDate(){return this.isValid?Sd(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let r=`HH:mm:ss.SSS`;return(t||e)&&(n&&(r+=` `),t?r+=`z`:e&&(r+=`ZZ`)),xd(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ud}[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{};let t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t=`milliseconds`,n={}){if(!this.isValid||!e.isValid)return Nu.invalid(`created by diffing an invalid DateTime`);let r={locale:this.locale,numberingSystem:this.numberingSystem,...n},i=Ac(t).map(Nu.normalizeUnit),a=e.valueOf()>this.valueOf(),o=Bu(a?this:e,a?e:this,i,r);return a?o.negate():o}diffNow(t=`milliseconds`,n={}){return this.diff(e.now(),t,n)}until(e){return this.isValid?Iu.fromDateTimes(this,e):this}hasSame(e,t,n){if(!this.isValid)return!1;let r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,n)<=r&&r<=i.endOf(t,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(t={}){if(!this.isValid)return null;let n=t.base||e.fromObject({},{zone:this.zone}),r=t.padding?this<n?-t.padding:t.padding:0,i=[`years`,`months`,`days`,`hours`,`minutes`,`seconds`],a=t.unit;return Array.isArray(t.unit)&&(i=t.unit,a=void 0),Pd(n,this.plus(r),{...t,numeric:`always`,units:i,unit:a})}toRelativeCalendar(t={}){return this.isValid?Pd(t.base||e.fromObject({},{zone:this.zone}),this,{...t,numeric:`auto`,units:[`years`,`months`,`days`],calendary:!0}):null}static min(...t){if(!t.every(e.isDateTime))throw new Io(`min requires all arguments be DateTimes`);return jc(t,e=>e.valueOf(),Math.min)}static max(...t){if(!t.every(e.isDateTime))throw new Io(`max requires all arguments be DateTimes`);return jc(t,e=>e.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:r=null,numberingSystem:i=null}=n;return sd(N.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),e,t)}static fromStringExplain(t,n,r={}){return e.fromFormatExplain(t,n,r)}static buildFormatParser(e,t={}){let{locale:n=null,numberingSystem:r=null}=t;return new od(N.fromOpts({locale:n,numberingSystem:r,defaultToEN:!0}),e)}static fromFormatParser(t,n,r={}){if(F(t)||F(n))throw new Io(`fromFormatParser requires an input string and a format parser`);let{locale:i=null,numberingSystem:a=null}=r,o=N.fromOpts({locale:i,numberingSystem:a,defaultToEN:!0});if(!o.equals(n.locale))throw new Io(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);let{result:s,zone:c,specificOffset:l,invalidReason:u}=n.explainFromTokens(t);return u?e.invalid(u):bd(s,c,r,`format ${n.format}`,t,l)}static get DATE_SHORT(){return Bo}static get DATE_MED(){return Vo}static get DATE_MED_WITH_WEEKDAY(){return Ho}static get DATE_FULL(){return Uo}static get DATE_HUGE(){return Wo}static get TIME_SIMPLE(){return Go}static get TIME_WITH_SECONDS(){return Ko}static get TIME_WITH_SHORT_OFFSET(){return qo}static get TIME_WITH_LONG_OFFSET(){return Jo}static get TIME_24_SIMPLE(){return Yo}static get TIME_24_WITH_SECONDS(){return Xo}static get TIME_24_WITH_SHORT_OFFSET(){return Zo}static get TIME_24_WITH_LONG_OFFSET(){return Qo}static get DATETIME_SHORT(){return $o}static get DATETIME_SHORT_WITH_SECONDS(){return es}static get DATETIME_MED(){return ts}static get DATETIME_MED_WITH_SECONDS(){return ns}static get DATETIME_MED_WITH_WEEKDAY(){return rs}static get DATETIME_FULL(){return is}static get DATETIME_FULL_WITH_SECONDS(){return as}static get DATETIME_HUGE(){return os}static get DATETIME_HUGE_WITH_SECONDS(){return ss}};function Rd(e){if(R.isDateTime(e))return e;if(e&&e.valueOf&&wc(e.valueOf()))return R.fromJSDate(e);if(e&&typeof e==`object`)return R.fromObject(e);throw new Io(`Unknown datetime argument: ${e}, of type ${typeof e}`)}var zd=class{get prefix(){return``}push(e){}pop(){}popAndReturn(e){return e}async record(e,t){return await t()}recordSync(e,t){return t()}},Bd=e=>{let t=[],n=Vd(e),r=n.next();for(;r;)t.push(r),r=n.next();return t},Vd=e=>({...e,next:Hd(e)}),Hd=e=>{let t=e.start;return()=>{if(t==null)return null;let n=null;switch(e.granularity){case To.Total:n=Ud(t,e.end);break;case To.Annual:n=Wd(t,e.end);break;case To.SemiAnnual:n=Gd(t,e.end);break;case To.Quarterly:n=Kd(t,e.end);break;case To.Monthly:n=qd(t,e.end);break;case To.Weekly:n=Jd(t,e.end);break;case To.Daily:n=Yd(t,e.end);break;case To.Hourly:n=Xd(t,e.end)}return t=n===null?null:n.end.plus({milliseconds:1}),n}},Ud=(e,t)=>t<=e?null:{period:`total`,start:e,end:t},Wd=(e,t)=>{if(t<=e)return null;let n=e.toUTC();return{period:`annual`,start:e,end:R.utc(n.year,n.month,n.day).plus({years:1})}},Gd=(e,t)=>{if(t<=e)return null;let n=R.utc(e.year,7,1),r=R.utc(e.year,12,31,23,59,59,999),i;return i=n>e?n:r,i>t&&(i=t),{period:`semiAnnual`,start:e,end:i}},Kd=(e,t)=>{if(t<=e)return null;let n,r=e.toUTC(),i=r.month;return n=i<3?R.utc(r.year,4,1):i<6?R.utc(r.year,7,1):i<9?R.utc(r.year,10,1):R.utc(r.year,12,31,23,59,59,999),n>t&&(n=t),{period:`quarterly`,start:e,end:n}},qd=(e,t)=>{if(t<=e)return null;let n=e.toUTC(),r=R.utc(n.year,n.month,n.day).plus({months:1}).startOf(`month`);return r>t&&(e.hasSame(t,`month`)||(r=t)),{period:`monthly`,start:e,end:r}},Jd=(e,t)=>{if(t<=e)return null;let n=e.toUTC(),r=R.utc(n.year,n.month,n.day).plus({weeks:1}).startOf(`week`);return r>t&&!r.hasSame(t,`day`)?{period:`weekly`,start:e,end:t}:{period:`weekly`,start:e,end:r}},Yd=(e,t)=>{if(t<=e)return null;let n=e.toUTC().plus({days:1}).startOf(`day`);return(n>t||n.hasSame(t,`day`))&&(n=t),{period:`daily`,start:e,end:n}},Xd=(e,t)=>{if(t<=e)return null;let n=e.toUTC().plus({hours:1});return n>t&&e.hour!==t.hour&&(n=t.toUTC()),{period:`hourly`,start:e,end:n}},Zd=e=>Math.floor((e.month-1)/3)+1,Qd=class e{static discretize(e,t,n,r,i){let a=this._buildIndex(e,t),o=Bd(this._calculateRange(n,r,i,e)),s=this._discretizeNode(a,{},t,o);return this._groupResultsByPeriod(o,s)}static _calculateRange(e,t,n,r){let i=e||null,a=t||null;if(i==null||a==null)for(let e of r){i??=e.start;let t=e.end||e.start;(a==null||a<t)&&(a=t)}if(i==null||a==null)throw Error(`Cannot determine query start and/or end.`);return{start:i,end:a,granularity:n}}static _groupResultsByPeriod(t,n){let r={};for(let n of t){let t=n.start.toISO()+`-`+n.period;r[t]={period:e._getPeriodString(n),start:n.start,end:n.end,rows:[]}}for(let e of n)for(let t of Object.keys(e.series))r[t].rows.push({dimensions:e.dimensions,metric:e.metric,unit:e.unit==`__NULL__`?null:e.unit,value:e.series[t].inc,sum:e.series[t].sum});return Object.values(r)}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${Zd(e.start)}`;case`monthly`:let t=e.start.toUTC().month,n=t<10?`0${t}`:`${t}`;return`${e.start.year}/${n}`;case`weekly`:return`${e.start.weekYear}/W${e.start.weekNumber}`;case`daily`:let r=e.start.month,i=e.start.day,a=r<10?`0${r}`:`${r}`,o=i<10?`0${i}`:`${i}`;return`${e.start.year}/${a}/${o}`;case`hourly`:let s=e.start.month,c=e.start.day,l=e.start.hour,u=s<10?`0${s}`:`${s}`,d=c<10?`0${c}`:`${c}`,f=l<10?`0${l}`:`${l}`;return`${e.start.year}/${u}/${d}/${f}`;default:return e.period}}static _discretizeNode(e,t,n,r){let i=[];if(n.length>0){let a=n[0];Object.keys(e).forEach((o,s,c)=>{let l={...t};l[a]=o,i.push(...this._discretizeNode(e[o],l,n.slice(1),r))})}else Object.keys(e).forEach(n=>{i.push(...this._discretizeLeaf(e[n],r,n,t))});return i}static _discretizeLeaf(e,t,n,r){let i=[];return Object.keys(e).forEach(a=>{let o={};Object.keys(r).forEach(t=>{o[t]={path:e[a][0].dimensions[t],icon:e[a][0].dimensions.icon,label:e[a][0].dimensions.label,description:e[a][0].dimensions.description}}),i.push({unit:a,metric:n,dimensions:o,series:this._discretizeSeries(e[a],t)})}),i}static _discretizeSeries(e,t){let n={};for(let r of e){let e=this._getValue(r,t[0].start);for(let i of t){let t=this._getValue(r,i.end),a=`${i.start.toISO()}-${i.period}`;n[a]?(n[a].inc+=t-e,n[a].sum+=t):n[a]={inc:t-e,sum:t},e=t}}return n}static _getValue(e,t){switch(e.fn){case`Single`:return this._getSingleValue(e,t);case`DssVest`:return this._getVestValue(e,t);default:return 0}}static _getSingleValue(e,t){return t>=e.start?e.value:0}static _getVestValue(e,t){let n=t,r=e.start,i=e.end,a=e.params?.cliff?R.fromISO(e.params.cliff):null;if(n<r||a&&n<a)return 0;if(i&&n>=i)return e.value;let o=Iu.fromDateTimes(r,n),s=Iu.fromDateTimes(r,i||n);return o.length()/s.length()*e.value}static _buildIndex(e,t){let n={},r={},i=t[0]||``;for(let t of e){let e=t.dimensions[i];r[e]===void 0&&(r[e]=[]),r[e].push(t)}if(t.length>1){let e=t.slice(1);Object.keys(r).forEach(t=>{n[t]=this._buildIndex(r[t],e)})}else Object.keys(r).forEach(e=>{n[e]=this._buildMetricsIndex(r[e])});return n}static _buildMetricsIndex(e){let t={},n={};for(let t of e){let e=t.metric;n[e]===void 0&&(n[e]=[]),n[e].push(t)}return Object.keys(n).forEach(e=>t[e]=this._buildUnitIndex(n[e])),t}static _buildUnitIndex(e){let t={};for(let n of e){let e=n.unit||`__NULL__`;t[e]===void 0&&(t[e]=[]),t[e].push(n)}return t}},$d=class{_profiler;constructor(e,t){this._analyticsStore=e,this._profiler=t??new zd}async executeCompound(e){let t,n={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},r={start:e.start,end:e.end,granularity:e.granularity,lod:{priceData:1},select:{priceData:[Eo.fromString(`atlas`)]},metrics:[e.expression.operand.metric],currency:e.expression.operand.currency},i=await this.execute(n),a=await this.execute(r);return t=[wo.VectorAdd,wo.VectorSubtract].includes(e.expression.operator)?await this._profiler.record(`ApplyVectorOperator`,async()=>await this._applyVectorOperator(i,a,e.expression.operator,e.expression.resultCurrency)):await this._profiler.record(`ApplyScalarOperator`,async()=>await this._applyScalarOperator(i,a,e.expression.operator,e.expression.operand.useSum,e.expression.resultCurrency)),t}async execute(e){let t=await this._executeSeriesQuery(e),n=this._profiler.recordSync(`ApplyLODs`,()=>this._applyLods(t,e.lod)),r=Object.keys(e.select);return this._profiler.recordSync(`Discretize`,()=>n.length<1?[]:Qd.discretize(n,r,e.start,e.end,e.granularity))}async executeMultiCurrency(e,t){let n={...e,currency:t.targetCurrency??e.currency},r=await this.execute(n);for(let i of t.conversions){let a={start:e.start,end:e.end,granularity:e.granularity,lod:e.lod,select:e.select,expression:{inputs:{metrics:n.metrics,currency:i.currency},operator:wo.ScalarMultiply,operand:{metric:i.metric,currency:t.targetCurrency,useSum:!0},resultCurrency:t.targetCurrency}},o=await this.executeCompound(a);r=await this._applyVectorOperator(r,o,wo.VectorAdd,t.targetCurrency)}return r}_applyVectorOperator(e,t,n,r){if([wo.ScalarMultiply,wo.ScalarDivide].includes(n))throw Error(`Invalid operator for vector operation`);return Promise.resolve(t)}_applyScalarOperator(e,t,n,r,i){if([wo.VectorAdd,wo.VectorSubtract].includes(n))throw Error(`Invalid operator for scalar operation`);let a=[],o={},s=r?`sum`:`value`;for(let e of t)e.rows.length>0&&(o[e.period]=e.rows[0][s]);for(let t of e){let e={period:t.period,start:t.start,end:t.end,rows:t.rows.map(e=>({dimensions:e.dimensions,metric:e.metric,unit:i?i.toString():e.unit,value:this._calculateOutputValue(e.value,n,o[t.period]),sum:-1}))};a.push(e)}return Promise.resolve(a)}_calculateOutputValue(e,t,n){switch(t){case wo.VectorAdd:return e+n;case wo.VectorSubtract:return e-n;case wo.ScalarMultiply:return e*n;case wo.ScalarDivide:return e/n}}async _executeSeriesQuery(e){let t={start:e.start,end:e.end,select:e.select,metrics:e.metrics,currency:e.currency};return await this._analyticsStore.getMatchingSeries(t)}_applyLods(e,t){return e.map(e=>({...e,dimensions:this._applyDimensionsLods(e.dimensions,t)}))}_applyDimensionsLods(e,t){let n={};for(let[r,i]of Object.entries(t))i!==null&&e[r]&&(n[r]=e[r].path.applyLod(i).toString(),n.icon=e[r].icon.toString(),n.label=e[r].label.toString(),n.description=e[r].description.toString());return n}async getDimensions(){return await this._analyticsStore.getDimensions()}},ef=class extends Error{innerErrors;constructor(e){super(e.map(e=>e.message).join(`
|
|
236
236
|
`)),this.name=`NotificationError`,this.innerErrors=e}},tf=class{_subscriptions=new Map;subscribeToPath(e,t){let n=this.normalizePath(e.toString(`/`));return this._subscriptions.has(n)||this._subscriptions.set(n,new Set),this._subscriptions.get(n).add(t),()=>{let e=this._subscriptions.get(n);e&&(e.delete(t),e.size===0&&this._subscriptions.delete(n))}}notifySubscribers(e){if(e.length===0||this._subscriptions.size===0)return;let t=[];for(let n of e){let e=this.normalizePath(n.toString(`/`)),r=this.getPathPrefixes(e),i=[];r.filter(e=>this._subscriptions.has(e)).forEach(e=>{i.push({prefix:e,callbacks:this._subscriptions.get(e)})});for(let[t,n]of this._subscriptions.entries())r.includes(t)||this.pathMatchesWildcardPattern(e,t)&&i.push({prefix:t,callbacks:n});if(i.length!==0)for(let{callbacks:e}of i)for(let r of e)try{r(n)}catch(e){t.push(e)}}if(t.length>0)throw new ef(t)}normalizePath(e){return`/`+e.split(`/`).filter(e=>e.length>0).join(`/`)}pathMatchesWildcardPattern(e,t){if(t.includes(`*`)){let n=e.split(`/`).filter(e=>e.length>0),r=t.split(`/`).filter(e=>e.length>0);if(r.length>n.length)return!1;for(let e=0;e<r.length;e++){let t=r[e],i=n[e];if(!(t===`*`||t.startsWith(`*:`))&&t!==i)return!1}return!0}return e===t||e.startsWith(t+`/`)}getPathPrefixes(e){let t=e.split(`/`).filter(e=>e.length>0),n=[],r=``;for(let e of t)r=r?`${r}/${e}`:`/${e}`,n.push(r);return n.length===0&&e===`/`&&n.push(`/`),n}},nf=e=>{let t=[];for(let n of e.values()||[]){let{fields:e,rows:r}=n,i=Array(r.length);for(let t=0,n=i.length;t<n;t++){let n=r[t],a={};for(let t=0,r=e.length;t<r;t++){let{name:r}=e[t];a[r]=n[r]}i[t]=a}t.push(...i)}return t},rf=class{_index=0;_sql=null;constructor(e,t,n){this._profiler=e,this._queryLogger=t,this._resultsLogger=n}init(e){this._sql=e}async execute(e){if(!this._sql)throw Error(`PGLiteQueryExecutor not initialized`);let t=this._index++;this._queryLogger&&this._queryLogger(t,e);let n=await this._profiler.record(`Query`,async()=>{let t=await this._sql?.exec(e);if(t)return nf(t)});return this._resultsLogger&&this._resultsLogger(t,n),n}},af=`
|
|
237
237
|
|
|
238
238
|
create table if not exists "AnalyticsSeries"
|
|
@@ -939,4 +939,4 @@ this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names`):a
|
|
|
939
939
|
reactorDriveDescendants(driveId: ID!, root: ID!): [ReactorDriveNode!]!
|
|
940
940
|
}
|
|
941
941
|
`;var tO=typeof window<`u`?window.btoa?function(e){return btoa(unescape(encodeURIComponent(e)))}:function(e){let t=unescape(encodeURIComponent(e+``)),n=``;for(let e,r,i=0,a=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`;t.charAt(i|0)||(a=`=`,i%1);n+=a.charAt(63&e>>8-i%1*8)){if(r=t.charCodeAt(i+=3/4),r>255)throw Error(`'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.`);e=e<<8|r}return n}:function(e){return Buffer.from(e).toString(`base64`)};function $(e,t){let n=iO(e,t);return(t&&t.fallback!==void 0?t.fallback:$.defaults.fallback)===!0&&n===``&&(n=iO(tO(e),t)),n}var nO={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`}},rO={};function iO(e,t){if(typeof e!=`string`)throw Error(`slug() requires a string argument, received `+typeof e);if(!e.isWellFormed())throw Error(`slug() received a malformed string with lone surrogates`);typeof t==`string`&&(t={replacement:t}),t=t?Object.assign({},t):{},t.mode=t.mode||$.defaults.mode;let n=$.defaults.modes[t.mode],r=[`replacement`,`multicharmap`,`charmap`,`remove`,`lower`,`trim`];for(let e,i=0,a=r.length;i<a;i++)e=r[i],t[e]=e in t?t[e]:n[e];let i=nO[t.locale]||rO,a=[];for(let e in t.multicharmap){if(!Object.prototype.hasOwnProperty.call(t.multicharmap,e))continue;let n=e.length;a.indexOf(n)===-1&&a.push(n)}a=a.sort(function(e,t){return t-e});let o=t.mode===`rfc3986`?/[^\w\s\-.~]/:/[^A-Za-z0-9\s]/,s=``;for(let n,r=0,c=e.length;r<c;r++){n=e[r];let c=!1;for(let i=0;i<a.length;i++){let o=a[i],s=e.substr(r,o);if(t.multicharmap[s]){r+=o-1,n=t.multicharmap[s],c=!0;break}}c||(n=i[n]?i[n]:t.charmap[n]?t.charmap[n].replace(t.replacement,` `):n.includes(t.replacement)?n.replace(t.replacement,` `):n.replace(o,``)),s+=n}return t.remove&&(s=s.replace(t.remove,``)),t.trim&&(s=s.trim()),s=s.replace(/\s+/g,t.replacement),t.lower&&(s=s.toLowerCase()),s}var aO={फ़:`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`},oO={À:`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`};$.charmap=Object.assign({},oO),$.multicharmap=Object.assign({},aO),$.defaults={charmap:$.charmap,mode:`pretty`,modes:{rfc3986:{replacement:`-`,remove:null,lower:!0,charmap:$.charmap,multicharmap:$.multicharmap,trim:!0},pretty:{replacement:`-`,remove:null,lower:!0,charmap:$.charmap,multicharmap:$.multicharmap,trim:!0}},multicharmap:$.multicharmap,fallback:!0},$.reset=function(){$.defaults.modes.rfc3986.charmap=$.defaults.modes.pretty.charmap=$.charmap=$.defaults.charmap=Object.assign({},oO),$.defaults.modes.rfc3986.multicharmap=$.defaults.modes.pretty.multicharmap=$.multicharmap=$.defaults.multicharmap=Object.assign({},aO),rO=``},$.extend=function(e){let t=Object.keys(e),n={},r={};for(let i=0;i<t.length;i++)t[i].length>1?n[t[i]]=e[t[i]]:r[t[i]]=e[t[i]];Object.assign($.charmap,r),Object.assign($.multicharmap,n)},$.setLocale=function(e){rO=nO[e]||{}};var sO=e=>{cO.forEach(t=>{lO(e,t)})},cO=[`name`,`message`,`stack`,`cause`,`errors`],lO=(e,t)=>{let n=uO(e,t);if(n!==void 0){if(dO(n)){pO(e,t,e[t]);return}fO(n)&&mO(e,t,n)}},uO=(e,t)=>{let n=Object.getOwnPropertyDescriptor(e,t);if(n!==void 0)return n;let r=Object.getPrototypeOf(e);return r===null?void 0:uO(r,t)},dO=({get:e,set:t})=>e!==void 0&&t===void 0,fO=({enumerable:e,writable:t})=>e||!t,pO=(e,t,n)=>{mO(e,t,{value:n})},mO=(e,t,n)=>{Object.defineProperty(e,t,{...n,...`get`in n||`set`in n?{}:{writable:!0},enumerable:!1,configurable:!0})},hO=(e,t)=>{Array.isArray(e.errors)?pO(e,`errors`,e.errors.filter(gO).map(t).filter(Boolean)):_O(e)?pO(e,`errors`,[]):e.errors!==void 0&&vO(e)},gO=e=>e!==void 0,_O=e=>`AggregateError`in globalThis&&(e.name===`AggregateError`||e instanceof AggregateError),vO=e=>{delete e.errors,e.errors!==void 0&&pO(e,`errors`,[])},yO=(e,t)=>{if(!(`cause`in e))return;let n=e.cause===void 0?e.cause:t(e.cause);n===void 0?delete e.cause:pO(e,`cause`,n)},bO=e=>xO(e)||SO(e),xO=e=>{try{return e instanceof Error}catch{return!1}},SO=e=>{try{return CO.has(Object.prototype.toString.call(e))}catch{return!1}},CO=new Set([`[object Error]`,`[object DOMException]`,`[object DOMError]`,`[object Exception]`]);function wO(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}var TO=e=>!Object.isExtensible(e)||cO.some(t=>EO(e,t)||DO(e,t)),EO=(e,t)=>{let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&!n.configurable},DO=(e,t)=>{try{return e[t],!1}catch{return!0}},OO=e=>{pO(e,`stack`,kO(e.message,e.name))},kO=(e=``,t=`Error`)=>{let{stack:n}=new(AO(t))(e);return typeof n==`string`&&n!==``?n:`${t}: ${e}`},AO=e=>{let t={value:e,enumerable:!1,writable:!0,configurable:!0},n=Object.defineProperty(class extends Error{},`name`,t);return Object.defineProperty(n.prototype,`name`,t),n},jO=e=>{let t={};for(let n of MO(e))try{let r=e[n],{enumerable:i,configurable:a,writable:o=!0}=uO(e,n);Object.defineProperty(t,n,{value:r,enumerable:i,configurable:a,writable:o})}catch{}return t},MO=e=>{let t=NO(e);for(let n of cO)PO(e,n)&&t.push(n);return t},NO=e=>{try{return Reflect.ownKeys(e)}catch{return[]}},PO=(e,t)=>{try{return t in e&&!Object.hasOwn(e,t)}catch{return!1}},FO=e=>{let{name:t,message:n,stack:r,cause:i,errors:a,...o}=jO(e),s=IO(n,o),c=VO(t,s);return n===s&&UO(c,o),Object.entries({name:t,stack:r,cause:i,errors:a}).forEach(([e,t])=>{WO(c,e,t)}),r===void 0&&OO(c),c},IO=(e,t)=>typeof e==`string`&&e!==``?e:zO(LO(t)),LO=e=>{try{return JSON.stringify(e)}catch{return RO(e)}},RO=e=>{try{return String(e)}catch{return`Invalid error`}},zO=e=>e.length<BO?e:`${e.slice(0,BO)}...`,BO=1e3,VO=(e,t)=>e===`AggregateError`&&`AggregateError`in globalThis?AggregateError([],t):e in HO?new HO[e](t):Error(t),HO={Error,ReferenceError,TypeError,SyntaxError,RangeError,URIError,EvalError},UO=(e,t)=>{for(let n in t)n in e||(e[n]=t[n])},WO=(e,t,n)=>{n!==void 0&&pO(e,t,n)},GO=e=>{try{let t=Error(String(e));return OO(t),t}catch(e){return e}},{toString:KO}=Object.prototype,qO=e=>JO(e)?FO(e):bO(e)?YO(e)?FO(e):e:GO(e),JO=e=>{try{return wO(e)}catch{return!1}},YO=e=>XO(e)||TO(e)||ZO(e),XO=e=>{try{return KO.call(e)===`[object Object]`}catch{return!0}},ZO=e=>typeof e.constructor!=`function`||typeof e.constructor.name!=`string`||e.constructor.name===``||e.constructor.prototype!==Object.getPrototypeOf(e),QO=(e,{shallow:t=!1}={})=>$O(e,[],t),$O=(e,t,n)=>{if(t.includes(e))return;let r=n?ek:r=>$O(r,[...t,e],n),i=qO(e);return tk(i,r),i},ek=e=>e,tk=(e,t)=>{nk(e),rk(e),ik(e),yO(e,t),hO(e,t),sO(e)},nk=e=>{if(ak(e.name))return;let t=Object.getPrototypeOf(e).name;pO(e,`name`,ak(t)?t:e.constructor.name)},rk=e=>{ak(e.message)||pO(e,`message`,``)},ik=e=>{ak(e.stack)||OO(e)},ak=e=>typeof e==`string`&&e!==``,ok=e(n(((e,t)=>{var n=(function(){var e=String.fromCharCode,t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`,n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$`,r={};function i(e,t){if(!r[e]){r[e]={};for(var n=0;n<e.length;n++)r[e][e.charAt(n)]=n}return r[e][t]}var a={compressToBase64:function(e){if(e==null)return``;var n=a._compress(e,6,function(e){return t.charAt(e)});switch(n.length%4){default:case 0:return n;case 1:return n+`===`;case 2:return n+`==`;case 3:return n+`=`}},decompressFromBase64:function(e){return e==null?``:e==``?null:a._decompress(e.length,32,function(n){return i(t,e.charAt(n))})},compressToUTF16:function(t){return t==null?``:a._compress(t,15,function(t){return e(t+32)})+` `},decompressFromUTF16:function(e){return e==null?``:e==``?null:a._decompress(e.length,16384,function(t){return e.charCodeAt(t)-32})},compressToUint8Array:function(e){for(var t=a.compress(e),n=new Uint8Array(t.length*2),r=0,i=t.length;r<i;r++){var o=t.charCodeAt(r);n[r*2]=o>>>8,n[r*2+1]=o%256}return n},decompressFromUint8Array:function(t){if(t==null)return a.decompress(t);for(var n=Array(t.length/2),r=0,i=n.length;r<i;r++)n[r]=t[r*2]*256+t[r*2+1];var o=[];return n.forEach(function(t){o.push(e(t))}),a.decompress(o.join(``))},compressToEncodedURIComponent:function(e){return e==null?``:a._compress(e,6,function(e){return n.charAt(e)})},decompressFromEncodedURIComponent:function(e){return e==null?``:e==``?null:(e=e.replace(/ /g,`+`),a._decompress(e.length,32,function(t){return i(n,e.charAt(t))}))},compress:function(t){return a._compress(t,16,function(t){return e(t)})},_compress:function(e,t,n){if(e==null)return``;var r,i,a={},o={},s=``,c=``,l=``,u=2,d=3,f=2,p=[],m=0,h=0,g;for(g=0;g<e.length;g+=1)if(s=e.charAt(g),Object.prototype.hasOwnProperty.call(a,s)||(a[s]=d++,o[s]=!0),c=l+s,Object.prototype.hasOwnProperty.call(a,c))l=c;else{if(Object.prototype.hasOwnProperty.call(o,l)){if(l.charCodeAt(0)<256){for(r=0;r<f;r++)m<<=1,h==t-1?(h=0,p.push(n(m)),m=0):h++;for(i=l.charCodeAt(0),r=0;r<8;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}else{for(i=1,r=0;r<f;r++)m=m<<1|i,h==t-1?(h=0,p.push(n(m)),m=0):h++,i=0;for(i=l.charCodeAt(0),r=0;r<16;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}u--,u==0&&(u=2**f,f++),delete o[l]}else for(i=a[l],r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;u--,u==0&&(u=2**f,f++),a[c]=d++,l=String(s)}if(l!==``){if(Object.prototype.hasOwnProperty.call(o,l)){if(l.charCodeAt(0)<256){for(r=0;r<f;r++)m<<=1,h==t-1?(h=0,p.push(n(m)),m=0):h++;for(i=l.charCodeAt(0),r=0;r<8;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}else{for(i=1,r=0;r<f;r++)m=m<<1|i,h==t-1?(h=0,p.push(n(m)),m=0):h++,i=0;for(i=l.charCodeAt(0),r=0;r<16;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}u--,u==0&&(u=2**f,f++),delete o[l]}else for(i=a[l],r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;u--,u==0&&(u=2**f,f++)}for(i=2,r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;for(;;)if(m<<=1,h==t-1){p.push(n(m));break}else h++;return p.join(``)},decompress:function(e){return e==null?``:e==``?null:a._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(t,n,r){var i=[],a=4,o=4,s=3,c=``,l=[],u,d,f,p,m,h,g,_={val:r(0),position:n,index:1};for(u=0;u<3;u+=1)i[u]=u;for(f=0,m=2**2,h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=+(p>0)*h,h<<=1;switch(f){case 0:for(f=0,m=2**8,h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=+(p>0)*h,h<<=1;g=e(f);break;case 1:for(f=0,m=2**16,h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=+(p>0)*h,h<<=1;g=e(f);break;case 2:return``}for(i[3]=g,d=g,l.push(g);;){if(_.index>t)return``;for(f=0,m=2**s,h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=+(p>0)*h,h<<=1;switch(g=f){case 0:for(f=0,m=2**8,h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=+(p>0)*h,h<<=1;i[o++]=e(f),g=o-1,a--;break;case 1:for(f=0,m=2**16,h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=+(p>0)*h,h<<=1;i[o++]=e(f),g=o-1,a--;break;case 2:return l.join(``)}if(a==0&&(a=2**s,s++),i[g])c=i[g];else if(g===o)c=d+d.charAt(0);else return null;l.push(c),i[o++]=d+c.charAt(0),a--,d=c,a==0&&(a=2**s,s++)}}};return a})();typeof define==`function`&&define.amd?define(function(){return n}):t!==void 0&&t!=null?t.exports=n:typeof angular<`u`&&angular!=null&&angular.module(`LZString`,[]).factory(`LZString`,function(){return n})}))(),1),sk=class extends Error{constructor(e){super(`Attachment not found: ${e}`),this.name=`AttachmentNotFound`}},ck=class extends Error{constructor(e){super(`Reservation not found: ${e}`),this.name=`ReservationNotFound`}},lk=class extends Error{constructor(e){super(`Invalid attachment ref: ${e}`),this.name=`InvalidAttachmentRef`}},uk=class extends Error{hash;ref;constructor(e,t){super(`Attachment already exists for hash: ${e}`),this.name=`AttachmentAlreadyExists`,this.hash=e,this.ref=t}},dk=class extends Error{claimed;actual;constructor(e,t){super(`Hash mismatch: claimed ${e} but computed ${t}`),this.name=`HashMismatch`,this.claimed=e,this.actual=t}},fk=class extends Error{declared;actual;constructor(e,t){super(`Size mismatch: declared ${e} bytes but received ${t}`),this.name=`SizeMismatch`,this.declared=e,this.actual=t}},pk=class extends Error{hash;expiresAtUtc;metadata;constructor(e,t,n){super(`Attachment pending upload for hash: ${e}, expires: ${t}`),this.name=`AttachmentPending`,this.hash=e,this.expiresAtUtc=t,this.metadata=n}},mk=/^attachment:\/\/v(\d+):(.+)$/,hk=1;function gk(e){let t=mk.exec(e);if(!t)throw new lk(e);return{version:Number(t[1]),hash:t[2]}}function _k(e,t=hk){return`attachment://v${t}:${e}`}var vk=/^[a-f0-9]{64}$/,yk=class{constructor(e,t,n){this.store=e,this.reservations=t,this.uploadFactory=n}async reserve(e){if(e.clientHash!==void 0)return this.reserveHashFirst(e);let t=await this.reservations.create(e);return this.uploadFactory.createUpload(t)}async stat(e){let{hash:t}=gk(e);return this.store.stat(t)}async get(e,t){let{hash:n}=gk(e);return this.store.get(n,t)}async reserveHashFirst(e){let t=e.clientHash.toLowerCase();if(!vk.test(t))throw Error(`clientHash must be a 64-character lowercase hex string, got: ${e.clientHash}`);if(e.sizeBytes===void 0||!Number.isInteger(e.sizeBytes)||e.sizeBytes<=0||!Number.isSafeInteger(e.sizeBytes))throw Error(`sizeBytes must be a positive safe integer when clientHash is provided`);let n={...e,clientHash:t},r=null;try{r=await this.store.stat(t)}catch(e){if(!(e instanceof sk)&&!(e instanceof pk))throw e}if(r!==null&&r.status===`available`)throw new uk(t,_k(t));let i=await this.reservations.create(n);return this.uploadFactory.createUpload(i)}};async function bk(e,t){let n={};if(t){let r=await t(e);r&&(n.Authorization=`Bearer ${r}`)}return n}function xk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sk(e){let t=e.lastIndexOf(`.`);return t<=0||t===e.length-1?null:e.slice(t+1).toLowerCase()}function Ck(e){return!(!xk(e)||typeof e.reservationId!=`string`||typeof e.mimeType!=`string`||typeof e.fileName!=`string`||e.extension!==null&&typeof e.extension!=`string`||typeof e.createdAtUtc!=`string`||typeof e.expiresAtUtc!=`string`)}function wk(e){return!(!Ck(e)||e.clientHash!==void 0&&e.clientHash!==null&&typeof e.clientHash!=`string`||e.sizeBytes!==void 0&&e.sizeBytes!==null&&typeof e.sizeBytes!=`number`)}var Tk=class{remoteUrl;jwtHandler;fetchFn;constructor(e){this.remoteUrl=e.remoteUrl,this.jwtHandler=e.jwtHandler,this.fetchFn=(e.fetchFn??globalThis.fetch).bind(globalThis)}async create(e){let t=`${this.remoteUrl}/attachments/reservations`,n=await bk(t,this.jwtHandler),r=e.extension??Sk(e.fileName),i={mimeType:e.mimeType,fileName:e.fileName,extension:r};e.clientHash!==void 0&&(i.clientHash=e.clientHash),e.sizeBytes!==void 0&&(i.sizeBytes=e.sizeBytes);let a=await this.fetchFn(t,{method:`POST`,headers:{...n,"Content-Type":`application/json`},body:JSON.stringify(i)});if(a.status===409){let t;try{t=await a.json()}catch{throw Error(`Reservation create failed: ${a.status} ${a.statusText}`)}if(xk(t)&&t.error===`already_exists`&&e.clientHash!==void 0){let n;if(typeof t.ref==`string`)try{gk(t.ref),n=t.ref}catch{n=_k(e.clientHash)}else n=_k(e.clientHash);throw new uk(e.clientHash,n)}throw Error(`Reservation create failed: ${a.status} ${a.statusText}`)}if(!a.ok)throw Error(`Reservation create failed: ${a.status} ${a.statusText}`);let o;try{o=await a.json()}catch{throw Error(`Reservation create returned non-JSON response`)}if(typeof o!=`object`||!o||typeof o.reservationId!=`string`||o.reservationId.length===0)throw Error(`Reservation create returned a payload missing a non-empty reservationId string`);let s=o,c=new Date;return{reservationId:s.reservationId,mimeType:e.mimeType,fileName:e.fileName,extension:r,createdAtUtc:s.createdAtUtc??c.toISOString(),expiresAtUtc:s.expiresAtUtc??new Date(c.getTime()+1440*60*1e3).toISOString(),clientHash:e.clientHash??null,sizeBytes:e.sizeBytes??null}}async get(e){let t=`${this.remoteUrl}/attachments/reservations/${encodeURIComponent(e)}`,n=await bk(t,this.jwtHandler),r=await this.fetchFn(t,{headers:n});if(r.status===404)throw new ck(e);if(!r.ok)throw Error(`Reservation get failed: ${r.status} ${r.statusText}`);let i;try{i=await r.json()}catch{throw Error(`Reservation get returned non-JSON response`)}if(!wk(i))throw Error(`Reservation get returned a payload that does not match the Reservation shape`);return{reservationId:i.reservationId,mimeType:i.mimeType,fileName:i.fileName,extension:i.extension,createdAtUtc:i.createdAtUtc,expiresAtUtc:i.expiresAtUtc,clientHash:i.clientHash??null,sizeBytes:i.sizeBytes??null}}async delete(e){let t=`${this.remoteUrl}/attachments/reservations/${encodeURIComponent(e)}`,n=await bk(t,this.jwtHandler),r=await this.fetchFn(t,{method:`DELETE`,headers:n});if(!r.ok&&r.status!==404&&r.status!==410)throw Error(`Reservation delete failed: ${r.status} ${r.statusText}`)}deleteExpired(){return Promise.reject(Error(`RemoteReservationStore.deleteExpired is not supported`))}};function Ek(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Dk=class{reservationId;ref;expiresAtUtc;remoteUrl;jwtHandler;fetchFn;constructor(e,t){this.reservationId=e.reservationId,this.ref=e.clientHash===null?null:_k(e.clientHash),this.expiresAtUtc=e.expiresAtUtc,this.remoteUrl=t.remoteUrl,this.jwtHandler=t.jwtHandler,this.fetchFn=(t.fetchFn??globalThis.fetch).bind(globalThis)}async send(e){let t=`${this.remoteUrl}/attachments/reservations/${this.reservationId}`,n=await bk(t,this.jwtHandler),r=await new Response(e).blob(),i=await this.fetchFn(t,{method:`PUT`,headers:{...n,"Content-Type":`application/octet-stream`},body:r});if(i.status===422){let e;try{e=await i.json()}catch{throw Error(`Attachment upload failed: ${i.status} ${i.statusText}`)}if(Ek(e)){if(e.error===`hash_mismatch`&&typeof e.claimed==`string`&&typeof e.actual==`string`)throw new dk(e.claimed,e.actual);if(e.error===`size_mismatch`&&typeof e.declared==`number`&&typeof e.actual==`number`)throw new fk(e.declared,e.actual)}throw Error(`Attachment upload failed: ${i.status} ${i.statusText}`)}if(!i.ok)throw Error(`Attachment upload failed: ${i.status} ${i.statusText}`);return await i.json()}},Ok=class{constructor(e){this.config=e}createUpload(e){return new Dk(e,this.config)}};function kk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ak(e){return!(!kk(e)||typeof e.mimeType!=`string`||typeof e.fileName!=`string`||typeof e.sizeBytes!=`number`||!Number.isFinite(e.sizeBytes)||e.sizeBytes<0||e.extension!==null&&typeof e.extension!=`string`||typeof e.createdAtUtc!=`string`||e.lastAccessedAtUtc!==void 0&&typeof e.lastAccessedAtUtc!=`string`)}function jk(e){let t=e.headers.get(`Content-Length`);if(t===null)throw Error(`Switchboard response missing both Attachment-Metadata and Content-Length headers`);let n=Number(t);if(!Number.isInteger(n)||n<0)throw Error(`Switchboard response has invalid Content-Length header: ${JSON.stringify(t)}`);let r=e.headers.get(`Last-Modified`),i=e.headers.get(`Date`),a=r?new Date(r).toISOString():i?new Date(i).toISOString():new Date().toISOString();return{mimeType:e.headers.get(`Content-Type`)??`application/octet-stream`,fileName:`unknown`,sizeBytes:n,extension:null,createdAtUtc:a,lastAccessedAtUtc:a}}function Mk(e){let t,n=()=>(t===void 0&&(t=jk(e)),t),r=e.headers.get(`Attachment-Metadata`);if(r)try{let e=JSON.parse(r);if(kk(e)&&(e.extension===void 0&&(e.extension=null),e.createdAtUtc===void 0&&(e.createdAtUtc=n().createdAtUtc),e.lastAccessedAtUtc===void 0&&(e.lastAccessedAtUtc=n().lastAccessedAtUtc)),Ak(e))return e}catch{}return n()}function Nk(e){let t=e.headers.get(`Attachment-Pending`);if(!t)return null;try{let e=JSON.parse(t);if(!kk(e)||typeof e.expiresAtUtc!=`string`)return null;let n={expiresAtUtc:e.expiresAtUtc};return typeof e.mimeType==`string`&&(n.mimeType=e.mimeType),typeof e.fileName==`string`&&(n.fileName=e.fileName),typeof e.sizeBytes==`number`&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0&&(n.sizeBytes=e.sizeBytes),n}catch{return null}}function Pk(e){let t=Nk(e);return!t||typeof t.mimeType!=`string`||typeof t.fileName!=`string`||t.sizeBytes===void 0?null:{expiresAtUtc:t.expiresAtUtc,mimeType:t.mimeType,fileName:t.fileName,sizeBytes:t.sizeBytes}}var Fk=class{remoteUrl;jwtHandler;fetchFn;constructor(e){this.remoteUrl=e.remoteUrl,this.jwtHandler=e.jwtHandler,this.fetchFn=(e.fetchFn??globalThis.fetch).bind(globalThis)}async stat(e){let t=`${this.remoteUrl}/attachments/${e}`,n=await bk(t,this.jwtHandler),r=await this.fetchFn(t,{method:`HEAD`,headers:n});if(r.status===202){let t=Pk(r);if(t)return Lk(e,t);let n=Nk(r);throw n?new pk(e,n.expiresAtUtc):Error(`Attachment stat returned 202 with missing or malformed Attachment-Pending header`)}if(r.status===404)throw new sk(e);if(!r.ok)throw Error(`Attachment stat failed: ${r.status} ${r.statusText}`);return Ik(e,Mk(r))}async get(e,t){return this.fetchAttachment(e,t)}async fetchAttachment(e,t){let n=`${this.remoteUrl}/attachments/${e}`,r=await bk(n,this.jwtHandler),i=await this.fetchFn(n,{signal:t,headers:r});if(i.status===202){let t=Nk(i);throw t?new pk(e,t.expiresAtUtc):Error(`Attachment fetch returned 202 with missing or malformed Attachment-Pending header`)}if(i.status===404)throw new sk(e);if(!i.ok)throw Error(`Attachment fetch failed: ${i.status} ${i.statusText}`);if(!i.body)throw Error(`Response body is null`);return{header:Ik(e,Mk(i)),body:i.body}}};function Ik(e,t){return{hash:e,mimeType:t.mimeType,fileName:t.fileName,sizeBytes:t.sizeBytes,extension:t.extension,status:`available`,source:`sync`,createdAtUtc:t.createdAtUtc,lastAccessedAtUtc:t.lastAccessedAtUtc??t.createdAtUtc,expiresAtUtc:null}}function Lk(e,t){let n=new Date().toISOString();return{hash:e,mimeType:t.mimeType,fileName:t.fileName,sizeBytes:t.sizeBytes,extension:null,status:`pending`,source:`sync`,createdAtUtc:n,lastAccessedAtUtc:n,expiresAtUtc:t.expiresAtUtc}}function Rk(e){let t=new Tk(e),n=new Ok(e);return new yk(new Fk(e),t,n)}function zk(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}var Bk=class{constructor(e){this.service=e}async preprocess(e,t){let n=await e.arrayBuffer(),r=new Uint8Array(n),i=await globalThis.crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``),o=_k(a),s=e.size;return{ref:o,hash:a,sizeBytes:s,options:{mimeType:t?.mimeType??e.type,fileName:t?.fileName??(e instanceof File?e.name:`attachment`),clientHash:a,sizeBytes:s},data:zk(r),stream:()=>zk(r)}}async reserve(e,t){let n;try{n=await this.service.reserve(e)}catch(e){if(e instanceof uk){let t=await this.service.stat(e.ref);return{hash:e.hash,ref:e.ref,header:t}}throw e}return t(n)}};function Vk(e){return new Bk(e)}var Hk=class extends Error{constructor(e){super(`Document type ${e} is not supported`),this.name=`UnsupportedDocumentTypeError`}static isError(e){return Error.isError(e)&&e.name===`UnsupportedDocumentTypeError`}},Uk=class extends Error{documentType;name=`DocumentModelNotFoundError`;constructor(e){super(`Document model module for type ${e} not found`),this.documentType=e}static isError(e){return Error.isError(e)&&e.name===`DocumentModelNotFoundError`}},Wk=class extends Error{constructor(e,t,n){super(`Document ${e} is not of type ${t}. Actual type: ${n}`)}},Gk=class extends Error{constructor(){super(`There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?`)}};function Kk(e,t){return t?.length?t.some(t=>{if(t.endsWith(`/*`)){let n=t.slice(0,-2);return e.startsWith(n+`/`)}if(t.endsWith(`*`)&&!t.endsWith(`/*`)){let n=t.slice(0,-1);return e.startsWith(n)}return t===e}):!0}function qk(){let e=window.ph?.renown?.user,t=window.ph?.allowList;return t?{isAllowedToCreateDocuments:t.includes(e?.address??``),isAllowedToEditDocuments:t.includes(e?.address??``)}:{isAllowedToCreateDocuments:!0,isAllowedToEditDocuments:!0}}var Jk=new Set([`auth`]),Yk=new Set([`auth`,`document`]);async function Xk(e,t,n){let r=window.ph?.reactorClient;if(!r)return{isDuplicate:!1};let i;try{i=await r.get(t)}catch{return{isDuplicate:!1}}let a=i.state.global.nodes.find(t=>t.id===e.header.id);if(a&&a.parentFolder===(n??null))return{isDuplicate:!0,duplicateType:`id`,nodeId:a.id};let o=i.state.global.nodes.find(t=>Mr(t)&&t.name===e.header.name&&t.documentType===e.header.documentType&&t.parentFolder===(n??null));return o?{isDuplicate:!0,duplicateType:`name`,nodeId:o.id}:{isDuplicate:!1}}function Zk(e){switch(e.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`:{let t=e.state.global?.type;return t===`analytics`?`analytics-processor`:t===`relational`?`relational-processor`:t===`codegen`?`codegen-processor`:void 0}default:return}}async function Qk(e,t){try{let n=await p(e),r=new Blob([new Uint8Array(n)],{type:`application/zip`}),i=window.document.createElement(`a`);i.style.display=`none`,i.href=URL.createObjectURL(r),i.download=t,window.document.body.appendChild(i),i.click(),window.document.body.removeChild(i)}catch(e){E.error(e instanceof Error?e.message:String(e))}}async function $k(e){let t=e.header.documentType,n;if(t===`powerhouse/document-model`)n=e.state.global?.extension;else{let e=window.ph?.reactorClient;if(e){let{results:r}=await e.getDocumentModelModules();n=r.find(e=>e.documentModel.global.id===t)?.utils.fileExtension}}return(n??``).replace(/^\.+|\.+$/g,``)}async function eA(e,t,n=100){let r=Object.keys(t.state).filter(e=>!Jk.has(e)),i={};for(let e of r)i[e]=[];let a=``;do{let o=await e.getOperations(t.header.id,{scopes:r},void 0,{cursor:a,limit:n});for(let e of o.results){let t=e.action.scope??`global`;i[t]&&i[t].push(e)}a=o.nextCursor??``}while(a);return i}function tA(e){let t=e.find(e=>e.action.type===`UPGRADE_DOCUMENT`);if(!t)throw Error(`No UPGRADE_DOCUMENT operation found — document is invalid`);let n=t.action.input,r=n.initialState??n.state;if(!r)throw Error(`UPGRADE_DOCUMENT operation has no initialState — document is invalid`);return r}function nA(e){return Object.fromEntries(Object.entries(e).filter(([e])=>!Yk.has(e)))}async function rA(e,t){let n=window.ph?.reactorClient;if(!n)throw Error(`ReactorClient not initialized`);let r=await eA(n,e),i=tA(r.document??[]),a={...e,operations:r,initialState:i},o=await $k(a),s=t||a.header.name||`Untitled`,c=o?`${s}.${o}.phd`:`${s}.phd`;if(!window.showSaveFilePicker)return await Qk(a,c);try{let e=await window.showSaveFilePicker({suggestedName:c});return await ne(a,e),e}catch(e){if(!(e instanceof DOMException&&e.name===`AbortError`))throw e}}async function iA(e){let t=await oe(e,e=>e,{checkHashes:!0}),n=window.ph?.reactorClient;if(!n)throw Error(`ReactorClient not initialized`);let r=t.header.documentType,{results:i}=await n.getDocumentModelModules(),a=i.filter(e=>e.documentModel.global.id===r);if(a.length===0)throw new Uk(r);let o={};for(let e of a)o[e.version??1]=e.reducer;let s=window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry,c;if(s)try{c=s.getUpgradeManifest(r)}catch{}return re(e,{reducers:o,upgradeManifest:c})}async function aA(e,t,n,r,i,a,o){let{isAllowedToCreateDocuments:s}=qk();if(!s)throw Error(`User is not allowed to create documents`);let c=window.ph?.reactorClient;if(!c)throw Error(`ReactorClient not initialized`);let l=await c.getDocumentModelModule(n),u=i??l.utils.createDocument();u.header.name=t,o&&(u.header.meta={...u.header.meta,preferredEditor:o});let d;try{d=await c.drives.addFile(e,u,r)}catch(e){throw E.error(`Error adding document: @error`,e),Error(`There was an error adding document`,{cause:e})}return{id:d.header.id,name:d.header.name,documentType:n,parentFolder:r??null,kind:`file`}}async function oA(e,t,n,r){E.verbose(`addFile(drive: ${t}, name: ${n}, folder: ${r})`);let{isAllowedToCreateDocuments:i}=qk();if(!i)throw Error(`User is not allowed to create files`);let a=await iA(e),o=!1,s=window.ph?.reactorClient;if(!s)throw Error(`ReactorClient not initialized`);try{await s.get(a.header.id),o=!0}catch{}let c=o?g():a.header.id,l=ue(c,a.header.documentType);l.lastModifiedAtUtcIso=a.header.createdAtUtcIso,l.meta=a.header.meta,l.name=n||a.header.name;let u={...a,header:l,state:a.initialState,operations:Object.keys(a.operations).reduce((e,t)=>(e[t]=[],e),{})};await aA(t,n||a.header.name,a.header.documentType,r,u,c,a.header.meta?.preferredEditor),await lf(c,nA(a.operations),cf)}async function sA(e,t,n,r,i,a,o){E.verbose(`addFileWithProgress(drive: ${t}, name: ${n}, folder: ${r})`);let s=window.ph?.reactorClient;if(!s)return;let{isAllowedToCreateDocuments:c}=qk();if(!c)throw Error(`User is not allowed to create files`);try{i?.({stage:`loading`,progress:0});let c;try{c=await iA(e)}catch(s){let c=window.ph?.packageDiscoveryService;if(c&&Uk.isError(s)){cA(c,s.documentType,e,t,n,r,i,a,o);return}throw s}let l=await Xk(c,t,r);if(l.isDuplicate&&!o){i?.({stage:`conflict`,progress:0,duplicateType:l.duplicateType});return}let u=Zk(c);if(u?i?.({stage:`loading`,progress:10,documentType:u}):i?.({stage:`loading`,progress:10}),!Kk(c.header.documentType,a))throw i?.({stage:`unsupported-document-type`,progress:100,error:`Document type ${c.header.documentType} is not supported`}),new Hk(c.header.documentType);await s.getDocumentModelModule(c.header.documentType),i?.({stage:`initializing`,progress:10});let d=!1;try{await s.get(c.header.id),d=!0}catch{}let f=d?g():c.header.id,p=ue(f,c.header.documentType);p.lastModifiedAtUtcIso=c.header.createdAtUtcIso,p.meta=c.header.meta,p.name=n||c.header.name;let m={...c,header:p,state:c.initialState,operations:Object.keys(c.operations).reduce((e,t)=>(e[t]=[],e),{})},h=await aA(t,n||c.header.name,c.header.documentType,r,m,f,c.header.meta?.preferredEditor);if(!h)throw Error(`There was an error adding file`);return i?.({stage:`initializing`,progress:20}),await s.get(f),console.log(`Document created, starting upload of operations`),await lf(f,nA(c.operations),cf,{onProgress:e=>{if(e.totalOperations&&e.uploadedOperations!==void 0){let t=e.totalOperations>0?e.uploadedOperations/e.totalOperations:0,n=20+Math.round(t*80);i?.({stage:`uploading`,progress:n,totalOperations:e.totalOperations,uploadedOperations:e.uploadedOperations})}}}),i?.({stage:`complete`,progress:100,fileNode:h}),h}catch(e){if(!Hk.isError(e)){let t=e instanceof Error?e.message:`Unknown error occurred`;i?.({stage:`failed`,progress:100,error:t})}throw e}}async function cA(e,t,n,r,i,a,o,s,c){if(e){try{await e.load(t)}catch{o?.({stage:`unsupported-document-type`,progress:100,error:`Document type ${t} is not supported`});return}await sA(n,r,i,a,o,s,c)}}async function lA(e,t,n){let{isAllowedToCreateDocuments:r}=qk();if(!r)throw Error(`User is not allowed to create folders`);let i=window.ph?.reactorClient;if(!i)throw Error(`ReactorClient not initialized`);await i.get(e);let a=g(),o=(await i.execute(e,`main`,[sr({id:a,name:t,parentFolder:n})])).state.global.nodes.find(e=>e.id===a);if(!o||!Nr(o))throw Error(`There was an error adding folder`);return o}async function uA(e,t){let{isAllowedToCreateDocuments:n}=qk();if(!n)throw Error(`User is not allowed to delete documents`);let r=window.ph?.reactorClient;if(!r)throw Error(`ReactorClient not initialized`);await r.drives.removeNode(e,t)}async function dA(e,t,n){let{isAllowedToCreateDocuments:r}=qk();if(!r)throw Error(`User is not allowed to rename documents`);let i=window.ph?.reactorClient;if(!i)throw Error(`ReactorClient not initialized`);if((await i.execute(t,`main`,[m({name:n})])).header.name!==n)throw Error(`There was an error renaming the node`);let a=(await i.execute(e,`main`,[ur({id:t,name:n})])).state.global.nodes.find(e=>e.id===t);if(!a)throw Error(`There was an error renaming node in the drive`);return a}async function fA(e,t,n){let{isAllowedToCreateDocuments:r}=qk();if(!r)throw Error(`User is not allowed to rename documents`);let i=window.ph?.reactorClient;if(!i)throw Error(`ReactorClient not initialized`);if((await i.execute(t,`main`,[m({name:n})])).header.name!==n)throw Error(`There was an error renaming the node`);return await i.execute(e,`main`,[ur({id:t,name:n})]),(await i.get(e)).state.global.nodes.find(e=>e.id===t)}async function pA(e,t,n){let{isAllowedToCreateDocuments:r}=qk();if(!r)throw Error(`User is not allowed to move documents`);let i=window.ph?.reactorClient;if(!i)throw Error(`ReactorClient not initialized`);return await i.execute(e,`main`,[fr({srcFolder:t.id,targetParentFolder:n?.id})])}async function mA(e,t,n=g()){let r=t.header.documentType,{results:i}=await e.getDocumentModelModules(),o=i.filter(e=>e.documentModel.global.id===r),s={};for(let e of o)s[e.version??1]=e.reducer;if(Object.keys(s).length===0)throw Error(`Document model module not found for type: ${r}`);let c=window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry,l;if(c)try{l=c.getUpgradeManifest(r)}catch{}let u={reducers:s,upgradeManifest:l},d=ue(n,r);return a(t.initialState,t.operations,u,d)}async function hA(e,t,n){let r=window.ph?.reactorClient;if(!r)return;let{isAllowedToCreateDocuments:i}=qk();if(!i)throw Error(`User is not allowed to copy documents`);let a=await r.get(e),o=Fr({srcId:t.id,targetParentFolder:n?.id,targetName:t.name},()=>g(),a.state.global.nodes),s=new Map;for(let e of o){let t=a.state.global.nodes.find(t=>t.id===e.srcId);if(t){let n=Rr({nodes:a.state.global.nodes,srcName:e.targetName||t.name,srcKind:Mr(t)?`file`:`folder`,targetParentFolder:e.targetParentFolder||null});s.set(e.targetId,n)}}let c=o.filter(e=>{let t=a.state.global.nodes.find(t=>t.id===e.srcId);return t!==void 0&&Mr(t)});for(let t of c)try{let i=await mA(r,await r.get(t.srcId),t.targetId),a=s.get(t.targetId);a&&(i.header.name=a),await r.drives.addFile(e,i,n?.id)}catch(e){E.error(`Error copying document ${t.srcId}: ${String(e)}`)}return await sf(a,o.map(e=>dr(e)))}var gA=k(`modal`),_A=gA.useValue,vA=gA.setValue,yA=gA.addEventHandler;function bA(e){vA(e)}function xA(){vA(void 0)}function SA(e){vA({type:`createDocument`,documentType:e})}function CA(e){vA({type:`deleteItem`,id:typeof e==`string`?e:e.id})}var wA=3e4;function TA(e){let t=e instanceof Error?e.message:String(e);return/forbidden|unauthorized|insufficient permissions|\b401\b|\b403\b/i.test(t)}var EA=new Map;async function DA(e,t,n){let r=n?.timeoutMs??wA,i=n?.signal;return new Promise((n,a)=>{let o=!1,s,c,l,u=e=>{o||(o=!0,s?.(),c&&clearTimeout(c),l&&i&&i.removeEventListener(`abort`,l),e())};if(s=e.subscribe({ids:[t]},e=>{e.type===Ii.Created&&u(()=>n())}),e.find({ids:[t]}).then(e=>{e.results.length>0&&u(()=>n())}).catch(()=>{}),i){if(i.aborted){u(()=>a(new DOMException(`Aborted`,`AbortError`)));return}l=()=>{u(()=>a(new DOMException(`Aborted`,`AbortError`)))},i.addEventListener(`abort`,l)}c=setTimeout(()=>{u(()=>a(Error(`Timed out after ${r}ms waiting for document ${t}`)))},r)})}async function OA(e,t){let{isAllowedToCreateDocuments:n}=qk();if(!n)throw Error(`User is not allowed to create drives`);let r=window.ph?.reactorClient;if(!r)throw Error(`ReactorClient not initialized`);let i=Gr({global:{name:e.global.name||``,icon:e.global.icon??null,nodes:[]}});return t&&(i.header.meta={preferredEditor:t}),await r.create(i)}async function kA(e,t,n){let r=window.ph?.reactorClient;if(!r)throw Error(`ReactorClient not initialized`);let i=window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;if(!i)throw Error(`Sync not initialized`);let a=await fetch(e);if(!a.ok)throw Error(`Failed to resolve drive info from ${e}`);let o=await a.json(),s=t??o.id,c=Ae.forDrive(s),l=EA.get(c.key);try{if(l)await l;else if(!i.list().find(e=>e.collectionId.equals(c))){let e=crypto.randomUUID(),t=i.add(e,c,{type:`gql`,parameters:{url:o.graphqlEndpoint}},void 0,n?.pollBehavior?{pollBehavior:n.pollBehavior}:void 0).finally(()=>EA.delete(c.key));EA.set(c.key,t),await t}}catch(e){throw TA(e)&&bA({type:`driveAuthRequired`}),e}return n?.awaitInitialSync&&await DA(r,s,{timeoutMs:n.initialSyncTimeoutMs,signal:n.signal}),s}async function AA(e){let{isAllowedToCreateDocuments:t}=qk();if(!t)throw Error(`User is not allowed to delete drives`);let n=window.ph?.reactorClient;if(!n)throw Error(`ReactorClient not initialized`);let r=window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;if(r){let t=Ae.forDrive(e),n=r.list().filter(e=>e.collectionId.equals(t));for(let e of n)await r.remove(e.name)}await n.deleteDocument(e,Di.Cascade)}async function jA(e,t){let{isAllowedToCreateDocuments:n}=qk();if(!n)throw Error(`User is not allowed to rename drives`);let r=window.ph?.reactorClient;if(!r)throw Error(`ReactorClient not initialized`);return await r.rename(e,t)}async function MA(e,t){let{isAllowedToCreateDocuments:n}=qk();if(!n)throw Error(`User is not allowed to change drive availability`);let r=window.ph?.reactorClient;if(!r)throw Error(`ReactorClient not initialized`);return await r.execute(e,`main`,[gr({availableOffline:t})])}async function NA(e,t){let{isAllowedToCreateDocuments:n}=qk();if(!n)throw Error(`User is not allowed to change drive sharing type`);let r=window.ph?.reactorClient;if(!r)throw Error(`ReactorClient not initialized`);return await r.execute(e,`main`,[hr({type:t})])}async function PA(e,t){let{isAllowedToCreateDocuments:n}=qk();if(!n)throw Error(`User is not allowed to update drive metadata`);let r=window.ph?.reactorClient;if(!r)throw Error(`ReactorClient not initialized`);let i=[];if(t.name&&i.push(pr({name:t.name})),t.icon!==void 0&&t.icon!==null&&i.push(mr({icon:t.icon})),i.length!==0)return await r.execute(e,`main`,i)}var FA=`powerhouse/generic-drive-explorer`;Object.values({DocumentModel:fe,DocumentDrive:Kr,ReactorDrive:eO});var IA=`http://localhost:4001/graphql`,LA=k(`isExternalControlsEnabled`),RA=LA.setValue,zA=LA.useValue,BA=LA.addEventHandler,VA=k(`isDragAndDropEnabled`),HA=VA.setValue,UA=VA.useValue,WA=VA.addEventHandler,GA=k(`allowedDocumentTypes`),KA=GA.setValue;function qA(){return GA.useValue()}var JA=GA.addEventHandler,YA={allowedDocumentTypes:KA,isDragAndDropEnabled:HA},XA={isExternalControlsEnabled:RA},ZA={allowedDocumentTypes:qA,isDragAndDropEnabled:UA},QA={isExternalControlsEnabled:zA},{useValue:$A,setValue:ej,addEventHandler:tj}=k(`routerBasename`),{useValue:nj,setValue:rj,addEventHandler:ij}=k(`version`),{useValue:aj,setValue:oj,addEventHandler:sj}=k(`requiresHardRefresh`),{useValue:cj,setValue:lj,addEventHandler:uj}=k(`warnOutdatedApp`),{useValue:dj,setValue:fj,addEventHandler:pj}=k(`studioMode`),{useValue:mj,setValue:hj,addEventHandler:gj}=k(`basePath`),{useValue:_j,setValue:vj,addEventHandler:yj}=k(`versionCheckInterval`),{useValue:bj,setValue:xj,addEventHandler:Sj}=k(`cliVersion`),{useValue:Cj,setValue:wj,addEventHandler:Tj}=k(`fileUploadOperationsChunkSize`),{useValue:Ej,setValue:Dj,addEventHandler:Oj}=k(`isDocumentModelSelectionSettingsEnabled`),{useValue:kj,setValue:Aj,addEventHandler:jj}=k(`gaTrackingId`),{useValue:Mj,setValue:Nj,addEventHandler:Pj}=k(`defaultDrivesUrl`),{useValue:Fj,setValue:Ij,addEventHandler:Lj}=k(`drivesPreserveStrategy`),{useValue:Rj,setValue:zj,addEventHandler:Bj}=k(`isLocalDrivesEnabled`),{useValue:Vj,setValue:Hj,addEventHandler:Uj}=k(`isAddDriveEnabled`),{useValue:Wj,setValue:Gj,addEventHandler:Kj}=k(`isPublicDrivesEnabled`),{useValue:qj,setValue:Jj,addEventHandler:Yj}=k(`isAddPublicDrivesEnabled`),{useValue:Xj,setValue:Zj,addEventHandler:Qj}=k(`isDeletePublicDrivesEnabled`),{useValue:$j,setValue:eM,addEventHandler:tM}=k(`isCloudDrivesEnabled`),{useValue:nM,setValue:rM,addEventHandler:iM}=k(`isAddCloudDrivesEnabled`),{useValue:aM,setValue:oM,addEventHandler:sM}=k(`isDeleteCloudDrivesEnabled`),{useValue:cM,setValue:lM,addEventHandler:uM}=k(`isLocalDrivesEnabled`),{useValue:dM,setValue:fM,addEventHandler:pM}=k(`isAddLocalDrivesEnabled`),{useValue:mM,setValue:hM,addEventHandler:gM}=k(`isDeleteLocalDrivesEnabled`),{useValue:_M,setValue:vM,addEventHandler:yM}=k(`isEditorDebugModeEnabled`),{useValue:bM,setValue:xM,addEventHandler:SM}=k(`isEditorReadModeEnabled`),{useValue:CM,setValue:wM,addEventHandler:TM}=k(`isAnalyticsDatabaseWorkerEnabled`),{useValue:EM,setValue:DM,addEventHandler:OM}=k(`isDiffAnalyticsEnabled`),{useValue:kM,setValue:AM,addEventHandler:jM}=k(`isDriveAnalyticsEnabled`),{useValue:MM,setValue:NM,addEventHandler:PM}=k(`renownUrl`),{useValue:FM,setValue:IM,addEventHandler:LM}=k(`renownNetworkId`),{useValue:RM,setValue:zM,addEventHandler:BM}=k(`renownChainId`),{useValue:VM,setValue:HM,addEventHandler:UM}=k(`sentryRelease`),{useValue:WM,setValue:GM,addEventHandler:KM}=k(`sentryDsn`),{useValue:qM,setValue:JM,addEventHandler:YM}=k(`sentryEnv`),{useValue:XM,setValue:ZM,addEventHandler:QM}=k(`isSentryTracingEnabled`),{useValue:$M,setValue:eN,addEventHandler:tN}=k(`isExternalProcessorsEnabled`),{useValue:nN,setValue:rN,addEventHandler:iN}=k(`isExternalPackagesEnabled`),aN=k(`enabledEditors`),oN=aN.setValue,sN=aN.useValue,cN=aN.addEventHandler,lN=k(`disabledEditors`),uN=lN.setValue,dN=lN.useValue,fN=lN.addEventHandler,pN=k(`isRelationalProcessorsEnabled`),mN=pN.setValue,hN=pN.useValue,gN=pN.addEventHandler,_N=k(`isExternalRelationalProcessorsEnabled`),vN=_N.setValue,yN=_N.useValue,bN=_N.addEventHandler,xN=k(`isAnalyticsEnabled`),SN=xN.setValue,CN=xN.useValue,wN=xN.addEventHandler,TN=k(`isAnalyticsExternalProcessorsEnabled`),EN=TN.setValue,DN=TN.useValue,ON=TN.addEventHandler,kN=k(`analyticsDatabaseName`),AN=kN.setValue,jN=kN.useValue,MN=kN.addEventHandler,NN=k(`logLevel`),PN=NN.setValue,FN=NN.useValue,IN=NN.addEventHandler,LN=k(`allowList`),RN=LN.setValue,zN=LN.useValue,BN=LN.addEventHandler,VN={routerBasename:ej,version:rj,requiresHardRefresh:oj,warnOutdatedApp:lj,studioMode:fj,basePath:hj,versionCheckInterval:vj,cliVersion:xj,fileUploadOperationsChunkSize:wj,isDocumentModelSelectionSettingsEnabled:Dj,gaTrackingId:Aj,defaultDrivesUrl:Nj,drivesPreserveStrategy:Ij,isLocalDrivesEnabled:zj,isAddDriveEnabled:Hj,isPublicDrivesEnabled:Gj,isAddPublicDrivesEnabled:Jj,isDeletePublicDrivesEnabled:Zj,isCloudDrivesEnabled:eM,isAddCloudDrivesEnabled:rM,isDeleteCloudDrivesEnabled:oM,isAddLocalDrivesEnabled:fM,isDeleteLocalDrivesEnabled:hM,isEditorDebugModeEnabled:vM,isEditorReadModeEnabled:xM,isRelationalProcessorsEnabled:mN,isExternalRelationalProcessorsEnabled:vN,isAnalyticsEnabled:SN,analyticsDatabaseName:AN,isAnalyticsExternalProcessorsEnabled:EN,isAnalyticsDatabaseWorkerEnabled:wM,isDiffAnalyticsEnabled:DM,isDriveAnalyticsEnabled:AM,renownUrl:NM,renownNetworkId:IM,renownChainId:zM,sentryRelease:HM,sentryDsn:GM,sentryEnv:JM,isSentryTracingEnabled:ZM,isExternalProcessorsEnabled:eN,isExternalPackagesEnabled:rN,allowList:RN,logLevel:PN,disabledEditors:uN,enabledEditors:oN},HN={...YA,...XA,...VN},UN={routerBasename:$A,version:nj,requiresHardRefresh:aj,warnOutdatedApp:cj,studioMode:dj,basePath:mj,versionCheckInterval:_j,cliVersion:bj,fileUploadOperationsChunkSize:Cj,isDocumentModelSelectionSettingsEnabled:Ej,gaTrackingId:kj,defaultDrivesUrl:Mj,drivesPreserveStrategy:Fj,isAddDriveEnabled:Vj,isPublicDrivesEnabled:Wj,isAddPublicDrivesEnabled:qj,isDeletePublicDrivesEnabled:Xj,isCloudDrivesEnabled:$j,isAddCloudDrivesEnabled:nM,isDeleteCloudDrivesEnabled:aM,isLocalDrivesEnabled:Rj,isAddLocalDrivesEnabled:dM,isDeleteLocalDrivesEnabled:mM,isEditorDebugModeEnabled:_M,isEditorReadModeEnabled:bM,isAnalyticsDatabaseWorkerEnabled:CM,isDiffAnalyticsEnabled:EM,isDriveAnalyticsEnabled:kM,renownUrl:MM,renownNetworkId:FM,renownChainId:RM,sentryRelease:VM,sentryDsn:WM,sentryEnv:qM,isSentryTracingEnabled:XM,isExternalProcessorsEnabled:$M,isExternalPackagesEnabled:nN,allowList:zN,isAnalyticsEnabled:CN,isAnalyticsExternalProcessorsEnabled:DN,isRelationalProcessorsEnabled:hN,isExternalRelationalProcessorsEnabled:yN,analyticsDatabaseName:jN,logLevel:FN,disabledEditors:dN,enabledEditors:sN};({...ZA,...QA,...UN});var WN=k(`attachmentService`);WN.useValue;var GN=WN.setValue,KN=WN.addEventHandler,qN=k(`features`);qN.useValue;var JN=qN.setValue,YN=qN.addEventHandler;function XN(e){return new URL(e.replace(/^\/+/,``),window.location.origin+(window.ph?.basePath??`/`)).pathname}function ZN(e){let t=window.ph?.basePath??`/`;return e.replace(t,t.endsWith(`/`)?`/`:``)}function QN(e){if(!e)return``;let t=e.name;return $(t?`${t}-${e.id}`:e.id)}function $N(e){let t=ZN(e);return/^\/d\/[^/]+\/([^/]+)$/.exec(t)?.[1]}function eP(e){if(e)return/\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(e)?.[0]}function tP(e){return eP(e)}function nP(e){let t=ZN(e);return/^\/d\/([^/]+)/.exec(t)?.[1]??``}function rP(e){return eP(e)}function iP(e){return rP(nP(e))}function aP(e){let t=window.location.search;return t?`${e}${t}`:e}var oP=k(`drives`),sP=oP.useValue,cP=oP.setValue,lP=oP.addEventHandler,uP=k(`selectedNodeId`),dP=uP.useValue,fP=uP.setValue,pP=uP.addEventHandler;function mP(e){let t=typeof e==`string`?e:QN(e);fP(tP(t));let n=nP(window.location.pathname);if(!n)return;if(!t){let e=XN(`/d/${n}`);if(e===window.location.pathname)return;window.history.pushState(null,``,aP(e));return}let r=XN(`/d/${n}/${t}`);r!==window.location.pathname&&window.history.pushState(null,``,aP(r))}function hP(){window.addEventListener(`ph:selectedDriveIdUpdated`,()=>{fP(void 0)})}function gP(){window.addEventListener(`popstate`,()=>{let e=window.location.pathname,t=$N(e);tP(t)!==window.ph?.selectedNodeId&&mP(t)})}var _P=k(`selectedDriveId`),vP=_P.useValue,yP=_P.setValue,bP=_P.addEventHandler;function xP(){let e=SP();if(!e[0])throw Error(`There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?`);return e}function SP(){let e=vP(),t=sP()?.find(t=>t.header.id===e),[n,r]=kf(t);return t?[n,r]:[void 0,void 0]}function CP(e){let t=typeof e==`string`?e:e?.header.slug,n=window.ph?.drives,r=(typeof e==`object`&&e?e:n?.find(e=>e.header.slug===t))?.header.id;if(!r&&t&&nP(window.location.pathname)===t){window.ph?.selectedDriveId&&yP(void 0),AP(t);return}if(kP(),yP(r),!r){let e=XN(`/`);if(e===window.location.pathname)return;window.history.pushState(null,``,aP(e));return}let i=XN(`/d/${t}`);i!==window.location.pathname&&window.history.pushState(null,``,aP(i))}var wP=2e3,TP=15e3;function EP(){let e=window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();return e?.length?e.some(e=>{try{let t=e.channel.getConnectionState();return t.receivingPages||!t.lastSuccessUtcMs&&t.state!==`error`}catch{return!1}}):!1}var DP,OP;function kP(){DP&&=(window.removeEventListener(`ph:drivesUpdated`,DP),void 0),OP&&=(clearTimeout(OP),void 0)}function AP(e){kP();let t=$N(window.location.pathname),n=()=>{window.ph?.drives?.find(t=>t.header.slug===e)&&(kP(),CP(e),mP(t))};DP=n,window.addEventListener(`ph:drivesUpdated`,n);let r=Date.now()+TP,i=()=>{OP=setTimeout(()=>{if(Date.now()<r&&EP()){i();return}kP();let e=XN(`/`);e!==window.location.pathname&&window.history.pushState(null,``,aP(e))},wP)};i()}function jP(){window.addEventListener(`popstate`,()=>{let e=window.location.pathname,t=iP(e);t!==window.ph?.selectedDriveId&&CP(t)})}function MP(){let[e,t]=At(!1),n=UA(),r=en(()=>t(!0),{triggerAt:`start`,minQuietPeriodMs:100}),i=en(()=>t(!1),{triggerAt:`start`,minQuietPeriodMs:100});function a(){n&&(i.cancel(),r.call())}function o(){n&&(r.cancel(),i.call())}return{isDropTarget:e,setTarget:a,unsetTarget:o}}var NP=k(`draggingNode`);NP.useValue;var PP=NP.setValue,FP=NP.addEventHandler;en(e=>PP(e),{reducer:(e,t)=>t,triggerAt:`start`,minQuietPeriodMs:100}),en(()=>PP(void 0),{triggerAt:`start`,minQuietPeriodMs:100});var IP=k(`reactorGraphQLClient`);IP.useValue,IP.setValue;var LP=IP.addEventHandler,RP=k(`packageDiscoveryService`),zP=RP.useValue,BP=RP.setValue,VP=RP.addEventHandler,HP=k(`reactorClientModule`),UP=k(`reactorClient`),WP=HP.useValue,GP=HP.setValue,KP=HP.addEventHandler,qP=UP.useValue,JP=UP.setValue,YP=UP.addEventHandler,XP=()=>WP()?.reactorModule?.syncModule?.syncManager,ZP=()=>XP()?.list()??[],QP=()=>WP()?.reactorModule?.database,$P=()=>WP()?.pg,eF=k(`revisionHistoryVisible`),tF=eF.useValue,nF=eF.setValue,rF=eF.addEventHandler;function iF(){nF(!0)}function aF(e){return e?e.kind.toUpperCase()===`FILE`:!1}function oF(e){return e?e.kind.toUpperCase()===`FOLDER`:!1}function sF(){let[e]=SP();return e?.state.global.nodes}function cF(){return sF()?.filter(e=>aF(e))}function lF(){return sF()?.filter(e=>oF(e))}function uF(){let e=cF()?.map(e=>e.id);return jf(e)}function dF(){return(uF()?.filter(fF))?.map(e=>e.state.global.id)}function fF(e){return e.header.documentType===`powerhouse/document-model`}function pF(){let e=dP();return sF()?.find(t=>t.id===e)}var mF=k(`selectedTimelineItem`),hF=mF.useValue;mF.setValue;var gF=mF.addEventHandler,_F=k(`selectedTimelineRevision`);_F.useValue,_F.setValue;var vF=_F.addEventHandler,yF=k(`toast`),bF=yF.useValue,xF=yF.setValue,SF=yF.addEventHandler,CF=k(`vetraPackageManager`),wF=CF.useValue,TF=()=>{let e=wF();return jt(t=>e?e.subscribe(t):()=>{},()=>e?.packages??[])},EF=CF.addEventHandler;function DF(e){CF.setValue(e),OF(e.packages),kF(e.packages),e.subscribe(({packages:e})=>{OF(e),kF(e)})}function OF(e){let t=e.flatMap(e=>e.documentModels),n=window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;if(!n||t.length===0)return;let r=n.registerModules(...t),i=[];for(let e of r)e.status===`error`&&(we.isError(e.error)?i.push(e):console.error(`Failed to register document model module:`,e.error));if(i.length>0){let e=i.map(e=>e.item.documentModel.global.id);n.unregisterModules(...e),n.registerModules(...i.map(e=>e.item))}}function kF(e){let t=e.flatMap(e=>e.upgradeManifests).filter(e=>e!==void 0),n=window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;if(!n||t.length===0)return;let r=n.registerUpgradeManifests(...t),i=[];for(let e of r)e.status===`error`&&(Ie.isError(e.error)?i.push(e):console.error(`Failed to register upgrade manifest:`,e.error));if(i.length>0){let e=i.map(e=>e.item.documentType).filter(e=>!!e);n.unregisterUpgradeManifests(...e),n.registerUpgradeManifests(...i.map(e=>e.item))}}var AF={loading:gD,drives:lP,selectedDriveId:()=>{bP(),jP(),hP()},selectedNodeId:()=>{pP(),gP()},documentCache:Tf,reactorGraphQLClient:LP,draggingNode:FP,reactorClientModule:KP,reactorClient:YP,attachmentService:KN,features:YN,modal:yA,renown:vD,vetraPackageManager:EF,packageDiscoveryService:VP,selectedTimelineRevision:vF,revisionHistoryVisible:rF,selectedTimelineItem:gF,routerBasename:tj,version:ij,logLevel:IN,requiresHardRefresh:sj,warnOutdatedApp:uj,studioMode:pj,basePath:gj,versionCheckInterval:yj,cliVersion:Sj,fileUploadOperationsChunkSize:Tj,isDocumentModelSelectionSettingsEnabled:Oj,gaTrackingId:jj,allowList:BN,defaultDrivesUrl:Pj,drivesPreserveStrategy:Lj,allowedDocumentTypes:JA,enabledEditors:cN,disabledEditors:fN,isAddDriveEnabled:Uj,isLocalDrivesEnabled:Bj,isPublicDrivesEnabled:Kj,isAddPublicDrivesEnabled:Yj,isDeletePublicDrivesEnabled:Qj,isCloudDrivesEnabled:tM,isAddCloudDrivesEnabled:iM,isDeleteCloudDrivesEnabled:sM,isAddLocalDrivesEnabled:pM,isDeleteLocalDrivesEnabled:gM,isDragAndDropEnabled:WA,isExternalControlsEnabled:BA,isEditorDebugModeEnabled:yM,isEditorReadModeEnabled:SM,isRelationalProcessorsEnabled:gN,isExternalRelationalProcessorsEnabled:bN,isAnalyticsEnabled:wN,isAnalyticsExternalProcessorsEnabled:ON,analyticsDatabaseName:MN,isAnalyticsDatabaseWorkerEnabled:TM,isDiffAnalyticsEnabled:OM,isDriveAnalyticsEnabled:jM,renownUrl:PM,renownNetworkId:LM,renownChainId:BM,sentryRelease:UM,sentryDsn:KM,sentryEnv:YM,isSentryTracingEnabled:QM,isExternalProcessorsEnabled:tN,isExternalPackagesEnabled:iN,toast:SF};function jF(){MF(AF)}function MF(e){Xt(e,e=>e())}function NF(){return TF().flatMap(e=>e.documentModels).filter((e,t,n)=>n.findIndex(t=>t.documentModel.global.id===e.documentModel.global.id&&t.version===e.version)===t)}function PF(e){return NF()?.find(t=>t.documentModel.global.id===e)}function FF(){let e=pF();if(oF(e))return e}function IF(e,t){let n=HN[e];n(t)}function LF(e){for(let t of Object.keys(e))IF(t,e[t])}function RF(e){for(let t of Object.keys(e))IF(t,e[t])}function zF(e){for(let t of Object.keys(e))IF(t,e[t])}function BF(e){let[t,n]=At(!1);Dt(()=>{t||(RF(e),n(!0))},[e,t])}function VF(e){let[t,n]=At(!1);Dt(()=>{t||(zF(e),n(!0))},[e,t])}function HF(){let e=XP(),[t,n]=At(()=>UF(e)),r=kt([]);return Dt(()=>{if(!e)return;function t(){for(let e of r.current)e();r.current=[];let t=e.list();for(let i of t){let t=i.channel.onConnectionStateChange(()=>{n(UF(e))});r.current.push(t)}n(UF(e))}t();let i=setInterval(t,5e3);return()=>{clearInterval(i);for(let e of r.current)e();r.current=[]}},[e]),t}function UF(e){let t=new Map;if(!e)return t;for(let n of e.list())t.set(n.name,n.channel.getConnectionState());return t}function WF(e,t){let[n,r]=Af(e),i=PF(t);if(!e||!t)return[];if(!n)throw Error(`Document not found: ${e}`);if(!i)throw new Le(t);if(n.header.documentType!==t)throw new Wk(e,t,n.header.documentType);return[n,r]}function GF(e){let t=qP(),n=kt(!1),[r,i]=At(()=>({globalOperations:[],localOperations:[],isLoading:!!e,error:void 0})),a=Et(async(r=0)=>{if(!e||!t){i({globalOperations:[],localOperations:[],isLoading:!1,error:void 0});return}i(e=>({...e,isLoading:!0,error:void 0}));let o=[],s=[],c;try{o=(await t.getOperations(e,{scopes:[`global`]})).results}catch(e){c=e instanceof Error?e:Error(String(e))}if(!c)try{s=(await t.getOperations(e,{scopes:[`local`]})).results}catch(e){c=e instanceof Error?e:Error(String(e))}if(!c&&o.length===0&&s.length===0&&r<5)return await new Promise(e=>setTimeout(e,500)),a(r+1);i({globalOperations:o,localOperations:s,isLoading:!1,error:c}),n.current=!0},[e,t]);Dt(()=>{e&&t?a():e||(i({globalOperations:[],localOperations:[],isLoading:!1,error:void 0}),n.current=!1)},[e,t,a]);let o=Et(()=>{a(0)},[a]);return{...r,refetch:o}}function KF(){return NF()?.map(e=>e.documentModel.global.id)}function qF(){let e=qA(),t=KF();return e??t}var JF=e=>{let t=[];if(e.header.documentType!==`powerhouse/document-model`)return t;let n=e,r=n.state.global.specifications[0],i=Object.keys(r.state).reduce((e,t)=>{let n=t;return[...e,...h(r.state[n].initialValue,n!==`global`).map(e=>({...e,message:`${e.message}. Scope: ${n}`,details:{...e.details,scope:n}}))]},[]),a=Object.keys(r.state).reduce((e,t)=>{let i=t,a=i===`global`;return[...e,...l(r.state[i].schema,n.state.global?.name||n.header.name||``,a?``:i,!a).map(e=>({...e,message:`${e.message}. Scope: ${i}`,details:{...e.details,scope:i}}))]},[]),o=s(r.modules);return[...i,...a,...o]};function YF(e){console.error(`Failed to export document: ${e.message}`)}function XF(e){return!Vt(JF(e),1)}function ZF(e,t=YF){if(e){if(!XF(e)){bA({type:`downloadDocumentWithErrors`,documentId:e.header.id});return}rA(e).catch(e=>t(QO(e)))}}function QF(e){let t=Of(),n=bF();return async()=>{if(!e)return;let r=e=>n?.(`Failed to export document: ${e.message}`);try{ZF(await t(e),r)}catch(e){r(e)}}}function $F(e){let t=sP()?.find(t=>t.header.id===e),[n,r]=kf(t);if(!t)throw Error(`Drive with id ${e} not found`);return[n,r]}function eI(){return TF().flatMap(e=>e.editors).filter(e=>!e.documentTypes.includes(`powerhouse/document-drive`))}function tI(){return TF().flatMap(e=>e.editors).filter(e=>e.documentTypes.includes(`powerhouse/document-drive`))}function nI(e){let t=eI();if(e&&t?.length!==0)return t?.filter(t=>t.documentTypes.includes(e))?.[0]}function rI(e){return tI()?.find(t=>t.config.id===e)}function iI(){return rI(FA)}function aI(e){return eI()?.find(t=>t.config.id===e)}var oI=[`zip`,`phd`,`phdm`],sI=e=>nn(qt(e,e=>an(e,`Files`))),cI=e=>Pt(e.dataTransfer.types,[tn,Vt(1),sI]),lI=`data-accepts-files`,uI=e=>{let t=e.target;return t instanceof Element?t.closest(`[${lI}]`)!==null:!1},dI=e=>Lt(e,e=>e.name,mn(`.`),cn(),rn(oI)),fI=e=>Lt([...e.dataTransfer.items],Ut(e=>an(e.kind,`file`)),un(e=>e.getAsFile()),Ut(sn));function pI(e){let{isDropTarget:t,setTarget:n,unsetTarget:r}=MP(),i=UA(),a=FF();function o(e,t){if(i&&cI(e)){if(uI(e)){r();return}e.preventDefault(),e.stopPropagation(),t?.()}}let s=t=>Promise.all(Lt(t,fI,Ut(dI),un(t=>e(t,a))));return{onDragEnter:e=>o(e),onDragOver:e=>o(e,n),onDragLeave:e=>o(e,r),onDrop:e=>o(e,pn(()=>{r(),s(e).catch(console.error)})),isDropTarget:t}}function mI(e){return lF()?.find(t=>t.id===e)}function hI(){let e=FF(),t=sF();if(!(!e||!t))return t.filter(t=>t.parentFolder===e.id)}function gI(){let e=hI();if(e)return e.filter(e=>aF(e))}function _I(){let e=uF(),t=gI()?.map(e=>e.id);return e?.filter(e=>t?.includes(e.header.id))}function vI(e,t){return t?.id===e?void 0:t}function yI(){let[e]=SP(),t=FF(),n=mI(pF()?.parentFolder),r=e?.header.id,i=sP();async function a(e,t){if(r)return oA(e,r,e.name.replace(/\..+/gim,``),vI(r,t)?.id)}async function o(e,t){if(r)return lA(r,e,vI(r,t)?.id)}async function s(e,t){if(r){if(!vI(r,t)){console.error(`Node ${t.id} not found`);return}return await dA(r,t.id,e)}}async function c(e,t){if(!r)return;let n=vI(r,e);if(!n){console.error(`Node ${e.id} not found`);return}await hA(r,n,vI(r,t))}async function l(e,t){if(!r)return;let n=vI(r,e);if(!n){console.error(`Node ${e.id} not found`);return}let i=vI(r,t);!i?.id&&!e.parentFolder||i?.id===e.parentFolder||await pA(r,n,i)}async function u(e){if(!r)return;let i=vI(r,e);if(!i){console.error(`Node ${e.id} not found`);return}await hA(r,i,vI(r,t??n))}async function d(e){if(!e||!r)return;let i=vI(r,t??n);if(!i)return;let a=await o(e,i);a&&mP(a)}async function f(e,t){if(!i)return;let n=i.filter(e=>e.state.global.nodes.some(e=>e.id===t));await Promise.all(n.map(n=>fA(n.header.id,t,e)))}return{onAddFile:a,onAddFolder:o,onRenameNode:s,onCopyNode:c,onMoveNode:l,onDuplicateNode:u,onAddAndSelectNewFolder:d,onRenameDriveNodes:f}}function bI(e){return sF()?.find(t=>t.id===e)}function xI(e){return mI(bI(e)?.parentFolder)}function SI(){return xI(pF()?.id)}function CI(){let e=pF();return e&&Mr(e)?e.id:void 0}function wI(){let[e,t]=Af(CI());if(!e)throw new Gk;return[e,t]}function TI(){return Af(CI())}var EI=`ph:theme`,DI=`ph:updateStoredTheme`,OI=`ph:storedThemeUpdated`,kI=`ph:systemThemeUpdated`,AI=typeof window>`u`;function jI(e){AI||localStorage.setItem(EI,e)}function MI(e){if(AI)return;let t=new CustomEvent(DI,{detail:{storedTheme:e}});window.dispatchEvent(t)}function NI(e){if(AI)return;let t=e.detail.storedTheme;jI(t);let n=new CustomEvent(OI,{detail:{storedTheme:t}});window.dispatchEvent(n)}function PI(){if(!AI)return localStorage.getItem(EI)??void 0}function FI(){if(!AI)return window.matchMedia(`(prefers-color-scheme: dark)`)}function II(){return AI?!1:!!FI()?.matches}function LI(){return AI?`light`:II()?`dark`:`light`}function RI(e){let t=e.matches?`dark`:`light`,n=new CustomEvent(kI,{detail:{systemTheme:t}});window.dispatchEvent(n)}function zI(e){AI||document.documentElement.classList.toggle(`dark`,e)}function BI(){AI||Dt(()=>{window.addEventListener(DI,NI);let e=FI();return e?.addEventListener(`change`,RI),()=>{window.removeEventListener(DI,NI),e?.removeEventListener(`change`,RI)}},[])}function VI(e){return AI?()=>{}:(window.addEventListener(OI,e),()=>{window.removeEventListener(OI,e)})}function HI(e){return AI?()=>{}:(window.addEventListener(kI,e),()=>{window.removeEventListener(kI,e)})}function UI(){let e=jt(VI,()=>PI(),()=>`system`),t=jt(HI,()=>LI(),()=>`light`),n=e===void 0||e===`system`,r=n?t:e,i=r===`dark`;return Dt(()=>{zI(i)},[i]),{theme:r,isSystem:n,setTheme:MI}}function WI(e){try{let t=new URL(e);return t.search=``,t.hash=``,t.pathname.endsWith(`/graphql/r`)?t.pathname=t.pathname.slice(0,-10)+`/graphql/system`:t.pathname=`/graphql/system`,t.toString()}catch{return null}}var GI=new Map;function KI(e){let t=ZP(),n=e?.header.id,r=Ot(()=>{if(!n)return null;let e=(t.find(e=>e.collectionId.equals(Ae.forDrive(n)))?.channel)?.config.url;return typeof e==`string`?WI(e):null},[t,n]),[i,a]=At(()=>r?GI.get(r)??{status:`loading`}:{status:`local`});return Dt(()=>{if(!r){a({status:`local`});return}let e=GI.get(r);if(e&&e.status!==`loading`){a(e);return}a({status:`loading`}),GI.set(r,{status:`loading`});let t=new AbortController;return fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({query:`{ system { version gitHash gitUrl } }`}),signal:t.signal}).then(async e=>{let t=await e.json();if(t.errors?.length)throw Error(t.errors.map(e=>e.message).join(`; `));let n=t.data?.system;if(!n)throw Error(`Missing system in response`);let i={status:`ready`,version:n.version,gitHash:n.gitHash,gitUrl:n.gitUrl??null,host:new URL(r).host};GI.set(r,i),a(i)}).catch(e=>{if(t.signal.aborted)return;let n=e instanceof Error?e.message:String(e);console.error(n);let i={status:`error`,message:n};GI.set(r,i),a(i)}),()=>t.abort()},[r]),i}oo.Synced,oo.Outgoing,oo.Incoming,oo.OutgoingAndIncoming,oo.Error;async function qI(e){return(await e.find({type:`powerhouse/document-drive`})).results}var JI=(e,t,n=[])=>{if(!e||!t)return 0;let r=n.find(n=>{let r=new Date(n.timestampUtcMs);return r>=e&&r<=t});return r?r.index:0};function YI(e){let t=e.split(`/`);return t.pop(),t.pop(),t.push(`graphql`),t.join(`/`)}function XI(){let e=em.loc;if(!e)throw Error(`GetDocumentWithOperationsDocument is misconfigured, loc is missing.`);return e.source.body}function ZI(e,t){let n=XI(),r={identifier:e},i=t?{Authorization:`Bearer ${t}`}:void 0,a={document:n.trim(),variables:JSON.stringify(r,null,2)};return i&&(a.headers=JSON.stringify(i)),ok.compressToEncodedURIComponent(JSON.stringify(a))}function QI(e,t,n){return`${e}?explorerURLState=${ZI(t,n)}`}function $I(e){let[t]=SP(),n=ZP(),r=Ot(()=>nn(t)?n.some(e=>e.collectionId.equals(Ae.forDrive(t.header.id))):!1,[n,t]),i=Ot(()=>{if(!nn(t))return null;try{let e=(n.find(e=>e.collectionId.equals(Ae.forDrive(t.header.id)))?.channel)?.config.url;return typeof e==`string`?e:null}catch(e){return console.error(`Error determining remote URL:`,e),null}},[n,t]),a=yD(),o=xD();return Ot(()=>!r||!e?.header.id||!i?null:async()=>{let t=o?.address?await a?.getBearerToken({expiresIn:600,aud:i}):void 0;return QI(i,e.header.id,t)},[r,i,e,o,a])}var eL=e=>{let t=vP(),n=FF(),r=qF();return async(i,a,o)=>{if(!t){console.warn(`No selected drive - upload skipped`);return}let s=i.name.replace(/\..+/gim,``),c=n?.id;return await sA(i,t,s,c,a,e??r,o)}},tL=200,nL=1e3;async function rL(e){e&&cP((await e.find({type:`powerhouse/document-drive`})).results)}function iL(e=tL,t=nL){let n=null,r=0;return(i,a=!1)=>{let o=Date.now(),s=o-r;return n!==null&&clearTimeout(n),a||s>=t?(r=o,rL(i)):new Promise(t=>{n=setTimeout(()=>{r=Date.now(),rL(i).then(t)},e)})}}var aL=iL();function oL(e){return e.endsWith(`/`)?e.slice(0,-1):e}async function sL(e){let t=await fetch(`${oL(e)}/packages`);if(!t.ok)throw Error(`Registry error: HTTP ${t.status}`);return await t.json()}async function cL(e,t){let n=encodeURIComponent(t),r=await fetch(`${oL(e)}/packages/by-document-type?type=${n}`);if(!r.ok)throw Error(`Registry error: HTTP ${r.status}`);return await r.json()}function lL(e){return e.replace(/\/-\/cdn\/?$/,``)}var uL=class{apiUrl;constructor(e){this.apiUrl=lL(e)}async getPackages(){return await sL(this.apiUrl)}async getPackagesByDocumentType(e){return await cL(this.apiUrl,e)}async searchPackages(e){let t=await this.getPackages();if(!e)return t;let n=e.toLowerCase();return t.filter(e=>e.name.toLowerCase().includes(n)||e.manifest?.description?.toLowerCase().includes(n))}onPublish(e){let t=new EventSource(`${this.apiUrl}/-/events`);return t.addEventListener(`publish`,t=>{e(JSON.parse(t.data))}),()=>{t.close()}}},dL=class{[Symbol.iterator](){return this.entries()}forEach(e){for(let[t,n]of this)e(n,t,this)}},fL=class extends dL{#e;#t=window.localStorage;constructor(e){super(),this.#e=e}#n(){let e=this.#t.getItem(this.#e);return e?new Map(JSON.parse(e)):new Map}#r(e){this.#t.setItem(this.#e,JSON.stringify(Array.from(e.entries())))}get(e){return this.#n().get(e)}set(e,t){let n=this.#n();n.set(e,t),this.#r(n)}delete(e){let t=this.#n(),n=t.delete(e);return n&&this.#r(t),n}has(e){return this.#n().has(e)}clear(){this.#t.removeItem(this.#e)}entries(){return this.#n().entries()}keys(){return this.#n().keys()}values(){return this.#n().values()}[Symbol.iterator](){return this.#n().entries()}};export{dF as $,HE as $t,zF as A,Nt as An,hF as At,CA as B,DA as Bt,MA as C,rn as Cn,wI as Ct,JN as D,Ut as Dn,vP as Dt,cP as E,en as En,xP as Et,nF as F,ZP as Ft,tI as G,DD as Gt,iF as H,Rk as Ht,CP as I,UI as It,iI as J,yD as Jt,HF as K,wD as Kt,mP as L,wF as Lt,BP as M,VF as Mt,JP as N,KF as Nt,PN as O,Vt as On,SP as Ot,GP as P,XP as Pt,GF as Q,zE as Qt,DF as R,TF as Rt,LF as S,an as Sn,tF as St,NA as T,tn as Tn,TI as Tt,oL as U,OD as Ut,bA as V,Vk as Vt,rI as W,ED as Wt,NF as X,sD as Xt,PF as Y,xD as Yt,WF as Z,pD as Zt,YI as _,ai as _n,_A as _t,OA as a,wf as an,sP as at,jA as b,un as bn,SI as bt,xA as c,Ii as cn,nI as ct,rA as d,ma as dn,UA as dt,Fp as en,uF as et,nP as f,vo as fn,yI as ft,JI as g,$r as gn,$P as gt,sL as h,ei as hn,eL as ht,aA as i,_f as in,KI as it,xF as j,BF as jt,RF as k,Lt as kn,FF as kt,AA as l,So as ln,$I as lt,qI as m,ha as mn,xI as mt,IA as n,Lp as nn,QF as nt,jF as o,Af as on,pI as ot,$N as p,bo as pn,bI as pt,QP as q,bD as qt,uL as r,xf as rn,$F as rt,kA as s,pa as sn,aI as st,fL as t,Ip as tn,_I as tt,uA as u,sa as un,Vj as ut,BI as v,Mr as vn,bF as vt,PA as w,nn as wn,CI as wt,GN as x,sn as xn,WP as xt,aL as y,zr as yn,zP as yt,SA as z,JF as zt};
|
|
942
|
-
//# sourceMappingURL=dist-
|
|
942
|
+
//# sourceMappingURL=dist-t-ezfpxv.js.map
|