sanoma 0.11.21 → 0.11.23
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/README.md +55 -14
- package/app/README.md +12 -8
- package/app/dist/api.d.ts +191 -5
- package/app/dist/api.js +125 -4
- package/app/dist/api.js.map +1 -1
- package/app/dist/build.d.ts +28 -3
- package/app/dist/build.js +154 -15
- package/app/dist/build.js.map +1 -1
- package/app/dist/bundle-build.d.ts +32 -0
- package/app/dist/bundle-build.js +127 -67
- package/app/dist/bundle-build.js.map +1 -1
- package/app/dist/client/assets/ArrowDown.es-BVRf--PS.js +1 -0
- package/app/dist/client/assets/CaretDown.es-D12mWb2j.js +1 -0
- package/app/dist/client/assets/CatchBoundary-Cb__yx-s.js +1 -0
- package/app/dist/client/assets/Check.es-b7BdqO2s.js +1 -0
- package/app/dist/client/assets/CheckCircle.es-DKXiWmAT.js +1 -0
- package/app/dist/client/assets/Copy.es-CvUujKw7.js +1 -0
- package/app/dist/client/assets/DialogTitle-5oboyLiq.js +1 -0
- package/app/dist/client/assets/FloppyDisk.es-CDyDob8p.js +1 -0
- package/app/dist/client/assets/Globe.es-C1pgZCGM.js +1 -0
- package/app/dist/client/assets/MagnifyingGlass.es-CZ3i6pz0.js +1 -0
- package/app/dist/client/assets/Play.es-DGJ1CGhp.js +1 -0
- package/app/dist/client/assets/Plug.es-BPhGL8MK.js +1 -0
- package/app/dist/client/assets/Plus.es-i3Vaa2WW.js +1 -0
- package/app/dist/client/assets/Separator-Cu9cQDBN.js +1 -0
- package/app/dist/client/assets/X.es-B7rq0E_-.js +1 -0
- package/app/dist/client/assets/_id-0_Y-lz6G.js +1 -0
- package/app/dist/client/assets/_id-3tGIwJ5T.js +1 -0
- package/app/dist/client/assets/_id-CgPVeQe8.js +1 -0
- package/app/dist/client/assets/_id-DFlFuBDE.js +1 -0
- package/app/dist/client/assets/_id-QNnNLGx_.js +1 -0
- package/app/dist/client/assets/_name-6k1yqjX8.js +1 -0
- package/app/dist/client/assets/_name-B4Qba2-o.js +4 -0
- package/app/dist/client/assets/_name-BfPXcP49.js +1 -0
- package/app/dist/client/assets/_name-CqBzHz7c.js +1 -0
- package/app/dist/client/assets/_vendor-CfHRJBG8.js +1 -0
- package/app/dist/client/assets/_vendor-Dj7KCZ74.js +1 -0
- package/app/dist/client/assets/app-chrome-CFH47gLL.js +5 -0
- package/app/dist/client/assets/app-scope-Z_2GE9oz.js +1 -0
- package/app/dist/client/assets/approval-CgksyU5L.js +1 -0
- package/app/dist/client/assets/apps-BDsPVmMY.js +1 -0
- package/app/dist/client/assets/button-D5kdANef.js +1 -0
- package/app/dist/client/assets/change-glance-D6N6Xaqu.js +1 -0
- package/app/dist/client/assets/changes-B6xxBiC0.js +1 -0
- package/app/dist/client/assets/changes-BS7eJI5T.js +1 -0
- package/app/dist/client/assets/chat-Bw3WhRE9.js +14 -0
- package/app/dist/client/assets/chat-button-DNusaP5n.js +1 -0
- package/app/dist/client/assets/chat-prompt-z0XJPDtH.js +1 -0
- package/app/dist/client/assets/{code-BVYaiQEr.js → code-CT4-YDKq.js} +2 -2
- package/app/dist/client/assets/common-DZLdx_jS.js +3 -0
- package/app/dist/client/assets/composite-CoGyvQjv.js +1 -0
- package/app/dist/client/assets/connect-BMk-KP-f.js +1 -0
- package/app/dist/client/assets/connections-TbS_jeiy.js +5 -0
- package/app/dist/client/assets/connectors-CgRpyRdd.js +1 -0
- package/app/dist/client/assets/credentials-Dxpl8sUw.js +1 -0
- package/app/dist/client/assets/css-BGIxQoYs.js +1 -0
- package/app/dist/client/assets/css-DgaLhXQH.js +1 -0
- package/app/dist/client/assets/data-lKkklNeo.js +1 -0
- package/app/dist/client/assets/decidable-w2VGgZwN.js +1 -0
- package/app/dist/client/assets/declaration-form-CAwox7F1.js +1 -0
- package/app/dist/client/assets/dialog-DDAfDsGh.js +1 -0
- package/app/dist/client/assets/diff-woXpYk--.js +1 -0
- package/app/dist/client/assets/engine-CBuzy-Ik.js +1 -0
- package/app/dist/client/assets/existing-2kDivy4p.js +1 -0
- package/app/dist/client/assets/fence-BdtS5gi0.js +157 -0
- package/app/dist/client/assets/github-dark-C-LZuMrd.js +1 -0
- package/app/dist/client/assets/github-light-EUqPIrTm.js +1 -0
- package/app/dist/client/assets/graph-BqVQ68hK.js +7 -0
- package/app/dist/client/assets/grid-diff-Jj1nTy52.js +1 -0
- package/app/dist/client/assets/held-card-DjBO8PTe.js +1 -0
- package/app/dist/client/assets/highlighted-body-JLMTFACH-Co7ss_Ht.js +1 -0
- package/app/dist/client/assets/hosting-DC7Pftfb.js +1 -0
- package/app/dist/client/assets/html-BHZv6uqE.js +1 -0
- package/app/dist/client/assets/import-DhVQArmJ.js +1 -0
- package/app/dist/client/assets/inbox-5h39e_tI.js +1 -0
- package/app/dist/client/assets/inbox-CUNaP4uz.js +1 -0
- package/app/dist/client/assets/index-CA_5CFb4.js +10 -0
- package/app/dist/client/assets/item-vV00RYfb.js +1 -0
- package/app/dist/client/assets/javascript-BzbQS41l.js +1 -0
- package/app/dist/client/assets/javascript-CpIGwZ_Y.js +1 -0
- package/app/dist/client/assets/json-qhed-kSA.js +1 -0
- package/app/dist/client/assets/jsx-Bz0zcwM4.js +1 -0
- package/app/dist/client/assets/kit-BZcdh1Xm.js +1 -0
- package/app/dist/client/assets/lazyRouteComponent-C2a8bGcK.js +1 -0
- package/app/dist/client/assets/markdown-BYOwaDjH.js +1 -0
- package/app/dist/client/assets/markdown-bsqylRZb.js +164 -0
- package/app/dist/client/assets/mermaid-WFAXDIZX-CYMnek4e.js +1 -0
- package/app/dist/client/assets/motion-D6e1hqz4.js +1 -0
- package/app/dist/client/assets/people-Bn8GAJ3z.js +1 -0
- package/app/dist/client/assets/permissions-Csf87P7b.js +2 -0
- package/app/dist/client/assets/permissions-grid-CzK64E29.js +1 -0
- package/app/dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
- package/app/dist/client/assets/python-gzcpVVnB.js +1 -0
- package/app/dist/client/assets/queries-XJ-fmuYb.js +57 -0
- package/app/dist/client/assets/react-dom-D6fTz1bt.js +1 -0
- package/app/dist/client/assets/review-BjpH-tT4.js +1 -0
- package/app/dist/client/assets/route-CD2oErox.js +1 -0
- package/app/dist/client/assets/route-CRwDZE-c.js +1 -0
- package/app/dist/client/assets/routes-gbZbqIhO.js +1 -0
- package/app/dist/client/assets/runs-table-nkQLXJxG.js +1 -0
- package/app/dist/client/assets/scenario-CZ7tmap7.js +1 -0
- package/app/dist/client/assets/scenario-graph-W2XcWuur.js +1 -0
- package/app/dist/client/assets/separator-Bdtc7rou.js +1 -0
- package/app/dist/client/assets/{sheet-BYL9XU5s.js → sheet-P-hJsTeq.js} +1 -1
- package/app/dist/client/assets/shellscript-CLZ0U2zV.js +1 -0
- package/app/dist/client/assets/site-icon-1Mcc1UIb.js +1 -0
- package/app/dist/client/assets/sites.index-CXcRF_R0.js +1 -0
- package/app/dist/client/assets/spinner-XaRXIj9W.js +1 -0
- package/app/dist/client/assets/sql-CEbI0hMM.js +1 -0
- package/app/dist/client/assets/start-form-6whPfUoW.js +1 -0
- package/app/dist/client/assets/store-BT988jIX.js +1 -0
- package/app/dist/client/assets/style-DaqPHcI1.css +2 -0
- package/app/dist/client/assets/table-B81tv0LG.js +1 -0
- package/app/dist/client/assets/textarea-CRpYU-qx.js +1 -0
- package/app/dist/client/assets/tsx-udAQXfEw.js +1 -0
- package/app/dist/client/assets/typescript-bsJCZSQ-.js +1 -0
- package/app/dist/client/assets/useLoaderData-BIegJC9y.js +1 -0
- package/app/dist/client/assets/useOpenInteractionType-UhakpAXY.js +1 -0
- package/app/dist/client/assets/useRegisterFieldControl-CT8iqvDE.js +1 -0
- package/app/dist/client/assets/useValueChanged-DBqn456b.js +1 -0
- package/app/dist/client/assets/utils-BRvE9-Fo.js +1 -0
- package/app/dist/client/assets/who-are-you-_7OehU_o.js +1 -0
- package/app/dist/client/assets/workflow-DSNK0oFo.js +1 -0
- package/app/dist/client/assets/workflow-view-VFD3onJL.js +1 -0
- package/app/dist/client/assets/workflows-CT9wqMl2.js +1 -0
- package/app/dist/client/assets/yaml-rwi0_p6S.js +1 -0
- package/app/dist/components/grid/plan.d.ts +46 -262
- package/app/dist/components/grid/plan.js +134 -138
- package/app/dist/components/grid/plan.js.map +1 -1
- package/app/dist/demo-build.d.ts +58 -0
- package/app/dist/demo-build.js +440 -0
- package/app/dist/demo-build.js.map +1 -0
- package/app/dist/handler.d.ts +9 -7
- package/app/dist/handler.js +10 -10
- package/app/dist/handler.js.map +1 -1
- package/app/dist/index.d.ts +4 -4
- package/app/dist/index.js +52 -35
- package/app/dist/index.js.map +1 -1
- package/app/dist/lib/chat.d.ts +67 -20
- package/app/dist/lib/chat.js +54 -18
- package/app/dist/lib/chat.js.map +1 -1
- package/app/dist/lib/names.d.ts +7 -0
- package/app/dist/lib/names.js +6 -2
- package/app/dist/lib/names.js.map +1 -1
- package/app/dist/login/page.d.ts +1 -10
- package/app/dist/login/page.js +0 -14
- package/app/dist/login/page.js.map +1 -1
- package/app/dist/login/staff.js +3 -3
- package/app/dist/login/staff.js.map +1 -1
- package/app/dist/server/assets/{_id-wuJIq2ZZ.js → _id-B6iAc90c.js} +2 -2
- package/app/dist/server/assets/{_id-Dt9tTylX.js → _id-BlceO2iK.js} +3 -3
- package/app/dist/server/assets/{_id-wB8khGTz.js → _id-Cc0uBuJb.js} +12 -7
- package/app/dist/server/assets/{_id-ce1EGp7Y.js → _id-DYfvgveB.js} +2 -2
- package/app/dist/server/assets/{_id-BViXAagq.js → _id-Dvn0wB-1.js} +15 -330
- package/app/dist/server/assets/{_name-BGagGBjX.js → _name-3AGcE6tj.js} +7 -7
- package/app/dist/server/assets/{_name-DntbHE-b.js → _name-BIcmcEwj.js} +11 -11
- package/app/dist/server/assets/{_name-BqFwnyf7.js → _name-CfoydEzk.js} +2 -2
- package/app/dist/server/assets/{_name-D_-MhjNf.js → _name-VpcPszKf.js} +210 -63
- package/app/dist/server/assets/{_tanstack-start-manifest_v-BljuBM-G.js → _tanstack-start-manifest_v-DUL7FcJk.js} +119 -91
- package/app/dist/server/assets/{_vendor-CcEviOki.js → _vendor-Bwis2sPx.js} +2 -2
- package/app/dist/server/assets/{_vendor-CNB03LWX.js → _vendor-DUtH-Z9W.js} +8 -8
- package/app/dist/server/assets/{actor-D6iA0pDg.js → actor-DAOPjcdj.js} +1 -1
- package/app/dist/server/assets/app-chrome-B8oA4uXZ.js +2298 -0
- package/app/dist/server/assets/{app-scope-CXIgOFmi.js → app-scope-BxuIu0xV.js} +2 -2
- package/app/dist/server/assets/{apply-plan-ybBda6vQ.js → apply-plan-CHJ_Hr71.js} +8 -7
- package/app/dist/server/assets/{approval-Su315ikC.js → approval-DR_9mBcx.js} +17 -14
- package/app/dist/server/assets/{apps-xwQAehch.js → apps-CtPev5RI.js} +7 -7
- package/app/dist/server/assets/button-Xwx3rpQ0.js +43 -0
- package/app/dist/server/assets/change-glance-DGqh7Pxb.js +54 -0
- package/app/dist/server/assets/{change-glance-CpArIbGS.js → changes-C3qjEBZP.js} +2 -54
- package/app/dist/server/assets/{changes-Bc_OiDBD.js → changes-DfOnO87K.js} +8 -7
- package/app/dist/server/assets/{chat-DMN_hoKm.js → chat-B19X0_8f.js} +133 -34
- package/app/dist/server/assets/{chat-button-LtA80MoR.js → chat-button-SluTWK8R.js} +2 -2
- package/app/dist/server/assets/{code-COyt8L-n.js → code-hVpCkmAZ.js} +1 -1
- package/app/dist/server/assets/{common-CWHLj7KV.js → common-JUUJLp4v.js} +30 -82
- package/app/dist/server/assets/{connect-BpPiu5s6.js → connect-DKu1UgY-.js} +11 -10
- package/app/dist/server/assets/{connections-DBgb1bvX.js → connections-Dyedl4qi.js} +12 -11
- package/app/dist/server/assets/{connectors-5a5_SlHO.js → connectors-yojQH7WS.js} +8 -8
- package/app/dist/server/assets/{credentials-ud_Y68hx.js → credentials-2Z6EHitQ.js} +10 -9
- package/app/dist/server/assets/{data-aEdhwcqy.js → data-1padc_i_.js} +7 -7
- package/app/dist/server/assets/{declaration-form-Dfg1yNuY.js → declaration-form-MAnn_M8g.js} +7 -6
- package/app/dist/server/assets/{dialog-BGjiw3Dx.js → dialog-T0bzlKzs.js} +2 -2
- package/app/dist/server/assets/{dropdown-menu-DAC3LWas.js → dropdown-menu-RGvPORm4.js} +1 -1
- package/app/dist/server/assets/{existing-B4d4NrC8.js → existing-BZjX_7Aa.js} +8 -7
- package/app/dist/server/assets/fence-BvNu3YNO.js +130 -0
- package/app/dist/server/assets/{field-C0Xx_90s.js → field-DFpkT1id.js} +1 -1
- package/app/dist/server/assets/{functions-BvFYzabD.js → functions-wlvFaDkF.js} +246 -44
- package/app/dist/server/assets/{graph-qYOdoz2s.js → graph-DjANDk1P.js} +5 -5
- package/app/dist/server/assets/{grid-diff-jTvp-8wS.js → grid-diff-D5bQDKl2.js} +1 -1
- package/app/dist/server/assets/held-card-CCEypEau.js +75 -0
- package/app/dist/server/assets/{hosting-bbn9UvDc.js → hosting-Csr6AVC7.js} +321 -42
- package/app/dist/server/assets/{import-DIwvzHb6.js → import-CtPlwdIl.js} +12 -10
- package/app/dist/server/assets/{inbox-Dj-5FleF.js → inbox-9-WMgjdU.js} +2 -2
- package/app/dist/server/assets/{inbox-D6R6sWBB.js → inbox-BYKHV9Yh.js} +8 -8
- package/app/dist/server/assets/{input-D63gF3G2.js → input-CF-vX8Xp.js} +1 -1
- package/app/dist/server/assets/{item-BDSXoEr_.js → item-LBDNja5f.js} +1 -1
- package/app/dist/server/assets/{kit-D6EulwBe.js → kit-D5moAfcg.js} +57 -4
- package/app/dist/server/assets/markdown-B9odAiMy.js +116 -0
- package/app/dist/server/assets/{middleware-B8JRLyxx.js → middleware-C4Wn6uHO.js} +325 -285
- package/app/dist/server/assets/{native-select-DLa-He0n.js → native-select-etaMvR-i.js} +2 -9
- package/app/dist/server/assets/{people-CkU_AxrV.js → people-LpcYXtEq.js} +13 -12
- package/app/dist/server/assets/{permissions-BfMcQqQb.js → permissions-M0kzvVVm.js} +9 -8
- package/app/dist/server/assets/{permissions-grid-DWP9FAAS.js → permissions-grid-CwWWdcQA.js} +4 -4
- package/app/dist/server/assets/{button-f9Lc8qLl.js → queries-BDuQsTdU.js} +141 -59
- package/app/dist/server/assets/review-BFZCPdVZ.js +355 -0
- package/app/dist/server/assets/{route-CF_8jQYY.js → route-BJLQf4ik.js} +2 -2
- package/app/dist/server/assets/{route-BTT7nMJq.js → route-C3uFABee.js} +2 -2
- package/app/dist/server/assets/{router-BvYtxrVN.js → router-Dx7Gu0CN.js} +175 -147
- package/app/dist/server/assets/routes-iVrnGFaR.js +227 -0
- package/app/dist/server/assets/{runs-table-BBudn12Y.js → runs-table-g3QYggO3.js} +6 -6
- package/app/dist/server/assets/{scenario-BXGTSTiP.js → scenario-B5dGlEGF.js} +5 -5
- package/app/dist/server/assets/{separator-8MZ7vR3f.js → separator-Cf98V8ie.js} +1 -1
- package/app/dist/server/assets/{sheet-5Cyp-4UW.js → sheet-DTOG7OHQ.js} +2 -2
- package/app/dist/server/assets/sites.index-BNeYUQnQ.js +165 -0
- package/app/dist/server/assets/{spinner-C1ZW08lp.js → spinner-016IPVi-.js} +1 -1
- package/app/dist/server/assets/{start-CSU4irVK.js → start-CIKqNkKp.js} +2 -2
- package/app/dist/server/assets/{start-form-DI60UOrc.js → start-form-BXAi2lVm.js} +10 -9
- package/app/dist/server/assets/{table-DtPk_h_5.js → table-y-dGlLx6.js} +1 -1
- package/app/dist/server/assets/{textarea-f0Ip5ed1.js → textarea-B02joDnr.js} +1 -1
- package/app/dist/server/assets/utils-CHesvfjo.js +138 -0
- package/app/dist/server/assets/{who-are-you-ZGyMnpVi.js → who-are-you-CavnVMGe.js} +16 -10
- package/app/dist/server/assets/{workflow-Z99QWO42.js → workflow-BXhqp6S1.js} +5 -5
- package/app/dist/server/assets/{workflow-view-C8X8U11S.js → workflow-view-go1rbTSF.js} +14 -13
- package/app/dist/server/assets/{workflows-C0kJoGf1.js → workflows-BCcXZtN-.js} +14 -14
- package/app/dist/server/chat.d.ts +6 -1
- package/app/dist/server/chat.js +39 -20
- package/app/dist/server/chat.js.map +1 -1
- package/app/dist/server/core.d.ts +24 -9
- package/app/dist/server/core.js +58 -119
- package/app/dist/server/core.js.map +1 -1
- package/app/dist/server/go-live.d.ts +11 -2
- package/app/dist/server/go-live.js +27 -27
- package/app/dist/server/go-live.js.map +1 -1
- package/app/dist/server/server.js +68 -48
- package/app/dist/server/setup.js +1 -1
- package/app/dist/server/setup.js.map +1 -1
- package/app/dist/server/token-redeem.d.ts +8 -0
- package/app/dist/server/token-redeem.js +45 -0
- package/app/dist/server/token-redeem.js.map +1 -0
- package/app/dist/site-path.d.ts +15 -0
- package/app/dist/site-path.js +26 -0
- package/app/dist/site-path.js.map +1 -1
- package/app/dist/snapshot-build.js +1 -0
- package/app/dist/snapshot-build.js.map +1 -1
- package/app/dist/steps/agent/acp.d.ts +3 -97
- package/app/dist/steps/agent/acp.js +19 -49
- package/app/dist/steps/agent/acp.js.map +1 -1
- package/app/dist/steps/agent/checkout.d.ts +18 -1
- package/app/dist/steps/agent/checkout.js +17 -0
- package/app/dist/steps/agent/checkout.js.map +1 -1
- package/app/dist/steps/agent/harness.d.ts +2 -4
- package/app/dist/steps/agent/harness.js +45 -61
- package/app/dist/steps/agent/harness.js.map +1 -1
- package/app/dist/steps/agent/prompt.d.ts +1 -1
- package/app/dist/steps/agent/prompt.js +37 -16
- package/app/dist/steps/agent/prompt.js.map +1 -1
- package/app/dist/steps/agent/transcript.d.ts +10 -1
- package/app/dist/steps/agent/transcript.js +75 -2
- package/app/dist/steps/agent/transcript.js.map +1 -1
- package/app/dist/steps/agent/turn.d.ts +4 -6
- package/app/dist/steps/agent/turn.js +14 -16
- package/app/dist/steps/agent/turn.js.map +1 -1
- package/app/dist/steps/index.js +2 -2
- package/app/dist/steps/index.js.map +1 -1
- package/app/dist/steps/writes.d.ts +21 -7
- package/app/dist/steps/writes.js +100 -23
- package/app/dist/steps/writes.js.map +1 -1
- package/app/dist/stylesheet.json +1 -1
- package/app/src/api.ts +188 -4
- package/app/src/build.ts +177 -14
- package/app/src/bundle-build.ts +132 -63
- package/app/src/components/app-chrome.tsx +28 -13
- package/app/src/components/approval.tsx +1 -1
- package/app/src/components/common.tsx +18 -88
- package/app/src/components/data-grid.tsx +2 -1
- package/app/src/components/go-live-cloud.tsx +44 -0
- package/app/src/components/go-live.tsx +51 -13
- package/app/src/components/grid/columns.tsx +175 -53
- package/app/src/components/grid/grid.tsx +4 -2
- package/app/src/components/grid/plan.ts +153 -164
- package/app/src/components/grid/review.tsx +108 -118
- package/app/src/components/home.tsx +199 -0
- package/app/src/components/import/match.tsx +2 -1
- package/app/src/components/import/sheet.ts +2 -1
- package/app/src/components/kit.tsx +55 -1
- package/app/src/components/logo.tsx +25 -0
- package/app/src/components/record-form.tsx +12 -5
- package/app/src/components/shell/bar.tsx +35 -26
- package/app/src/components/shell/chat-parts.tsx +185 -126
- package/app/src/components/shell/chat-prompt.ts +6 -2
- package/app/src/components/shell/chat.tsx +154 -220
- package/app/src/components/shell/composer.tsx +140 -0
- package/app/src/components/shell/connect-agent.tsx +157 -0
- package/app/src/components/shell/draft-card.tsx +192 -45
- package/app/src/components/shell/engine-mark.tsx +9 -0
- package/app/src/components/shell/fence.tsx +25 -0
- package/app/src/components/shell/held-card.tsx +58 -0
- package/app/src/components/shell/markdown.tsx +152 -0
- package/app/src/components/shell/nav-user.tsx +11 -1
- package/app/src/components/shell/prefs.ts +12 -1
- package/app/src/components/shell/thread.tsx +174 -0
- package/app/src/components/store-move.tsx +2 -1
- package/app/src/components/ui/bubble.tsx +117 -0
- package/app/src/components/ui/code-block.tsx +235 -0
- package/app/src/components/ui/input-group.tsx +136 -0
- package/app/src/components/ui/marker.tsx +67 -0
- package/app/src/components/ui/message-scroller.tsx +117 -0
- package/app/src/components/ui/message.tsx +74 -0
- package/app/src/components/ui/radio-group.tsx +26 -0
- package/app/src/components/ui/trace.tsx +133 -0
- package/app/src/components/who-are-you.tsx +8 -3
- package/app/src/demo/api.ts +42 -0
- package/app/src/demo/client-rpc.ts +16 -0
- package/app/src/demo/demo.css +31 -0
- package/app/src/demo/mount.tsx +97 -0
- package/app/src/demo/root.tsx +31 -0
- package/app/src/demo/tailwind.css +4 -0
- package/app/src/demo-build.ts +525 -0
- package/app/src/env.d.ts +12 -0
- package/app/src/functions.ts +50 -7
- package/app/src/handler.ts +20 -14
- package/app/src/hooks/use-highlighted-code.ts +72 -0
- package/app/src/index.ts +55 -36
- package/app/src/lib/chat.ts +113 -23
- package/app/src/lib/cn-tables.ts +23 -23
- package/app/src/lib/company-state.ts +73 -0
- package/app/src/lib/highlighter.tsx +114 -0
- package/app/src/lib/names.ts +13 -2
- package/app/src/login/page.ts +1 -21
- package/app/src/login/staff.ts +3 -3
- package/app/src/queries.ts +121 -18
- package/app/src/routes/__root.tsx +24 -7
- package/app/src/routes/changes/$id.tsx +4 -3
- package/app/src/routes/connectors/index.tsx +1 -1
- package/app/src/routes/data/$name/import.tsx +2 -1
- package/app/src/routes/data/$name/index.tsx +1 -2
- package/app/src/routes/hosting/index.tsx +277 -60
- package/app/src/routes/index.tsx +15 -4
- package/app/src/routes/sites.index.tsx +41 -3
- package/app/src/routes/workflows/$name/runs/$id.tsx +3 -1
- package/app/src/server/chat.ts +41 -19
- package/app/src/server/columns.ts +44 -18
- package/app/src/server/company-state.ts +76 -0
- package/app/src/server/core.ts +72 -116
- package/app/src/server/go-live.ts +35 -27
- package/app/src/server/setup-progress.ts +28 -0
- package/app/src/server/setup.ts +1 -1
- package/app/src/server/token-redeem.ts +49 -0
- package/app/src/site-api.ts +10 -0
- package/app/src/site-path.ts +29 -0
- package/app/src/site.ts +1 -1
- package/app/src/snapshot-build.ts +1 -0
- package/app/src/steps/agent/acp.ts +10 -80
- package/app/src/steps/agent/checkout.ts +30 -0
- package/app/src/steps/agent/harness.ts +53 -78
- package/app/src/steps/agent/prompt.ts +45 -17
- package/app/src/steps/agent/transcript.ts +90 -3
- package/app/src/steps/agent/turn.ts +18 -16
- package/app/src/steps/index.ts +2 -2
- package/app/src/steps/writes.ts +121 -31
- package/app/src/worker/app.ts +17 -14
- package/dist/check.js +2 -2
- package/dist/check.js.map +1 -1
- package/dist/cli.js +81 -22
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +8 -1
- package/dist/config.js +49 -8
- package/dist/config.js.map +1 -1
- package/dist/events.d.ts +15 -1
- package/dist/events.js +7 -0
- package/dist/events.js.map +1 -1
- package/dist/init.d.ts +27 -14
- package/dist/init.js +87 -39
- package/dist/init.js.map +1 -1
- package/dist/serve.d.ts +6 -2
- package/dist/serve.js +71 -9
- package/dist/serve.js.map +1 -1
- package/dist/source.d.ts +5 -0
- package/dist/source.js +113 -23
- package/dist/source.js.map +1 -1
- package/dist/worker-port.d.ts +16 -2
- package/dist/worker-port.js +44 -5
- package/dist/worker-port.js.map +1 -1
- package/invoices/README.md +66 -0
- package/invoices/dist/calculate.d.ts +37 -0
- package/invoices/dist/calculate.js +97 -0
- package/invoices/dist/calculate.js.map +1 -0
- package/invoices/dist/index.d.ts +4 -0
- package/invoices/dist/index.js +5 -0
- package/invoices/dist/index.js.map +1 -0
- package/invoices/dist/logo.d.ts +2 -0
- package/invoices/dist/logo.js +89 -0
- package/invoices/dist/logo.js.map +1 -0
- package/invoices/dist/pdf.d.ts +33 -0
- package/invoices/dist/pdf.js +215 -0
- package/invoices/dist/pdf.js.map +1 -0
- package/invoices/dist/schema.d.ts +156 -0
- package/invoices/dist/schema.js +88 -0
- package/invoices/dist/schema.js.map +1 -0
- package/oxlint.json +18 -0
- package/package.json +42 -7
- package/template/.env.example +15 -4
- package/template/AGENTS.md +10 -6
- package/template/package.json +6 -1
- package/template/policies/policy.cedar +5 -5
- package/template/resources/people.ts +5 -13
- package/template/resources/sanoma/infra.ts +8 -0
- package/template/sanoma.config.ts +18 -11
- package/template/scenarios/record-lead/record.feature +14 -0
- package/template/secrets.ts +13 -0
- package/template/tsconfig.json +1 -0
- package/template/workflows/record-lead.ts +30 -0
- package/testing/README.md +4 -4
- package/testing/dist/build.d.ts +3 -3
- package/testing/dist/build.js +4 -4
- package/testing/dist/build.js.map +1 -1
- package/testing/dist/host.d.ts +38 -21
- package/testing/dist/host.js +159 -77
- package/testing/dist/host.js.map +1 -1
- package/testing/dist/scenarios.d.ts +2 -1
- package/testing/dist/scenarios.js +14 -4
- package/testing/dist/scenarios.js.map +1 -1
- package/workflows/CLOUD-IDENTITY.md +15 -20
- package/workflows/README.md +54 -19
- package/workflows/dist/app-steps.js +8 -0
- package/workflows/dist/app-steps.js.map +1 -1
- package/workflows/dist/app-workflows.d.ts +172 -6
- package/workflows/dist/app-workflows.js +57 -9
- package/workflows/dist/app-workflows.js.map +1 -1
- package/workflows/dist/approvals.d.ts +3 -1
- package/workflows/dist/approvals.js +3 -1
- package/workflows/dist/approvals.js.map +1 -1
- package/workflows/dist/call.d.ts +8 -40
- package/workflows/dist/call.js +24 -135
- package/workflows/dist/call.js.map +1 -1
- package/workflows/dist/change-steps.d.ts +7 -0
- package/workflows/dist/change-steps.js +37 -13
- package/workflows/dist/change-steps.js.map +1 -1
- package/workflows/dist/change-workflow.d.ts +22 -10
- package/workflows/dist/change-workflow.js +30 -12
- package/workflows/dist/change-workflow.js.map +1 -1
- package/workflows/dist/change.d.ts +233 -7
- package/workflows/dist/change.js +27 -9
- package/workflows/dist/change.js.map +1 -1
- package/workflows/dist/client.d.ts +32 -5
- package/workflows/dist/client.js +94 -35
- package/workflows/dist/client.js.map +1 -1
- package/workflows/dist/cloud-identity.d.ts +5 -2
- package/workflows/dist/cloud-identity.js +7 -4
- package/workflows/dist/cloud-identity.js.map +1 -1
- package/workflows/dist/collection-driver.d.ts +20 -0
- package/workflows/dist/collection-driver.js +201 -0
- package/workflows/dist/collection-driver.js.map +1 -0
- package/workflows/dist/collection.d.ts +126 -14
- package/workflows/dist/collection.js +45 -168
- package/workflows/dist/collection.js.map +1 -1
- package/workflows/dist/company-file.d.ts +22 -0
- package/workflows/dist/company-file.js +82 -0
- package/workflows/dist/company-file.js.map +1 -0
- package/workflows/dist/config.d.ts +34 -6
- package/workflows/dist/config.js +58 -45
- package/workflows/dist/config.js.map +1 -1
- package/workflows/dist/ctx.d.ts +101 -0
- package/workflows/dist/ctx.js +171 -0
- package/workflows/dist/ctx.js.map +1 -0
- package/workflows/dist/db/company.d.ts +115 -1
- package/workflows/dist/db/company.js +14 -1
- package/workflows/dist/db/company.js.map +1 -1
- package/workflows/dist/db/dbos.d.ts +17 -0
- package/workflows/dist/db/dbos.js +2 -0
- package/workflows/dist/db/dbos.js.map +1 -1
- package/workflows/dist/db/identity.d.ts +2 -2
- package/workflows/dist/db/identity.js +2 -2
- package/workflows/dist/db/identity.js.map +1 -1
- package/workflows/dist/db.d.ts +1 -1
- package/workflows/dist/db.js +10 -6
- package/workflows/dist/db.js.map +1 -1
- package/workflows/dist/deadlines.d.ts +14 -8
- package/workflows/dist/deadlines.js +22 -11
- package/workflows/dist/deadlines.js.map +1 -1
- package/workflows/dist/define.d.ts +0 -8
- package/workflows/dist/define.js +1 -24
- package/workflows/dist/define.js.map +1 -1
- package/workflows/dist/describe.d.ts +1 -1
- package/workflows/dist/describe.js +18 -5
- package/workflows/dist/describe.js.map +1 -1
- package/workflows/dist/description.d.ts +408 -2
- package/workflows/dist/description.js +130 -5
- package/workflows/dist/description.js.map +1 -1
- package/workflows/dist/drift.d.ts +5 -2
- package/workflows/dist/drift.js +5 -3
- package/workflows/dist/drift.js.map +1 -1
- package/workflows/dist/errors.d.ts +11 -11
- package/workflows/dist/errors.js +17 -36
- package/workflows/dist/errors.js.map +1 -1
- package/workflows/dist/fake.d.ts +0 -26
- package/workflows/dist/fake.js +0 -123
- package/workflows/dist/fake.js.map +1 -1
- package/workflows/dist/fakes.d.ts +2 -0
- package/workflows/dist/fakes.js +5 -0
- package/workflows/dist/fakes.js.map +1 -0
- package/workflows/dist/givens.d.ts +51 -0
- package/workflows/dist/givens.js +89 -0
- package/workflows/dist/givens.js.map +1 -0
- package/workflows/dist/host.d.ts +8 -7
- package/workflows/dist/host.js +1 -1
- package/workflows/dist/host.js.map +1 -1
- package/workflows/dist/identity-provisioning.d.ts +2 -5
- package/workflows/dist/identity-provisioning.js +16 -20
- package/workflows/dist/identity-provisioning.js.map +1 -1
- package/workflows/dist/import.d.ts +2 -0
- package/workflows/dist/import.js +7 -6
- package/workflows/dist/import.js.map +1 -1
- package/workflows/dist/index.d.ts +8 -7
- package/workflows/dist/index.js +4 -3
- package/workflows/dist/index.js.map +1 -1
- package/workflows/dist/ledger.js +8 -17
- package/workflows/dist/ledger.js.map +1 -1
- package/workflows/dist/lint.d.ts +2 -2
- package/workflows/dist/lint.js +8 -4
- package/workflows/dist/lint.js.map +1 -1
- package/workflows/dist/load.js +1 -1
- package/workflows/dist/load.js.map +1 -1
- package/workflows/dist/log.d.ts +0 -2
- package/workflows/dist/log.js +0 -11
- package/workflows/dist/log.js.map +1 -1
- package/workflows/dist/op.d.ts +103 -3
- package/workflows/dist/op.js +56 -6
- package/workflows/dist/op.js.map +1 -1
- package/workflows/dist/page-run.d.ts +40 -0
- package/workflows/dist/page-run.js +317 -0
- package/workflows/dist/page-run.js.map +1 -0
- package/workflows/dist/paths.d.ts +0 -13
- package/workflows/dist/paths.js +2 -46
- package/workflows/dist/paths.js.map +1 -1
- package/workflows/dist/renewal.d.ts +1 -1
- package/workflows/dist/renewal.js +1 -1
- package/workflows/dist/run.d.ts +4 -1
- package/workflows/dist/run.js.map +1 -1
- package/workflows/dist/runtime-ops.d.ts +19 -4
- package/workflows/dist/runtime-ops.js +34 -5
- package/workflows/dist/runtime-ops.js.map +1 -1
- package/workflows/dist/sandbox-runner.cjs +4 -4
- package/workflows/dist/sandbox.d.ts +0 -20
- package/workflows/dist/sandbox.js +23 -85
- package/workflows/dist/sandbox.js.map +1 -1
- package/workflows/dist/scenario.d.ts +19 -1
- package/workflows/dist/scenario.js +82 -21
- package/workflows/dist/scenario.js.map +1 -1
- package/workflows/dist/schedules.d.ts +1 -1
- package/workflows/dist/schedules.js +1 -1
- package/workflows/dist/secret.d.ts +4 -5
- package/workflows/dist/secret.js +7 -6
- package/workflows/dist/secret.js.map +1 -1
- package/workflows/dist/shared.d.ts +84 -7
- package/workflows/dist/shared.js +255 -8
- package/workflows/dist/shared.js.map +1 -1
- package/workflows/dist/sites.d.ts +5 -0
- package/workflows/dist/sites.js +7 -0
- package/workflows/dist/sites.js.map +1 -1
- package/workflows/dist/source.d.ts +40 -1
- package/workflows/dist/source.js +3 -3
- package/workflows/dist/source.js.map +1 -1
- package/workflows/dist/supervisor.d.ts +21 -18
- package/workflows/dist/supervisor.js +20 -22
- package/workflows/dist/supervisor.js.map +1 -1
- package/workflows/dist/tokens.d.ts +34 -0
- package/workflows/dist/tokens.js +70 -9
- package/workflows/dist/tokens.js.map +1 -1
- package/workflows/dist/vendor-info.d.ts +12 -3
- package/workflows/dist/vendor-info.js +21 -5
- package/workflows/dist/vendor-info.js.map +1 -1
- package/workflows/dist/version.js +1 -1
- package/workflows/dist/version.js.map +1 -1
- package/workflows/dist/wakeup-driver.js +1 -1
- package/workflows/dist/wakeup-driver.js.map +1 -1
- package/workflows/dist/wakeup-fake.d.ts +27 -0
- package/workflows/dist/wakeup-fake.js +125 -0
- package/workflows/dist/wakeup-fake.js.map +1 -0
- package/workflows/dist/wakeup-service.js +8 -24
- package/workflows/dist/wakeup-service.js.map +1 -1
- package/workflows/dist/wakeup-type.js +1 -1
- package/workflows/dist/wakeup-type.js.map +1 -1
- package/workflows/dist/worker.d.ts +19 -1
- package/workflows/dist/worker.js +67 -49
- package/workflows/dist/worker.js.map +1 -1
- package/workflows/drizzle/company/0007_token_handoffs.sql +8 -0
- package/workflows/drizzle/company/meta/0007_snapshot.json +1281 -0
- package/workflows/drizzle/company/meta/_journal.json +7 -0
- package/workflows/src/app-steps.ts +11 -0
- package/workflows/src/app-workflows.ts +100 -10
- package/workflows/src/approvals.ts +4 -2
- package/workflows/src/call.ts +37 -186
- package/workflows/src/change-steps.ts +43 -14
- package/workflows/src/change-workflow.ts +45 -16
- package/workflows/src/change.ts +39 -10
- package/workflows/src/client.ts +137 -62
- package/workflows/src/cloud-identity.ts +7 -4
- package/workflows/src/collection-driver.ts +230 -0
- package/workflows/src/collection.ts +62 -186
- package/workflows/src/company-file.ts +82 -0
- package/workflows/src/config.ts +97 -56
- package/workflows/src/ctx.ts +266 -0
- package/workflows/src/db/company.ts +15 -1
- package/workflows/src/db/dbos.ts +2 -0
- package/workflows/src/db/identity.ts +2 -2
- package/workflows/src/db.ts +10 -6
- package/workflows/src/deadlines.ts +31 -17
- package/workflows/src/define.ts +1 -24
- package/workflows/src/describe.ts +27 -5
- package/workflows/src/description.ts +152 -5
- package/workflows/src/drift.ts +8 -4
- package/workflows/src/errors.ts +19 -45
- package/workflows/src/fake.ts +4 -139
- package/workflows/src/fakes.ts +4 -0
- package/workflows/src/givens.ts +141 -0
- package/workflows/src/host.ts +8 -7
- package/workflows/src/identity-provisioning.ts +19 -30
- package/workflows/src/import.ts +8 -6
- package/workflows/src/index.ts +13 -2
- package/workflows/src/ledger.ts +8 -16
- package/workflows/src/lint.ts +12 -6
- package/workflows/src/load.ts +1 -1
- package/workflows/src/log.ts +0 -11
- package/workflows/src/op.ts +147 -12
- package/workflows/src/page-run.ts +437 -0
- package/workflows/src/paths.ts +2 -46
- package/workflows/src/renewal.ts +1 -1
- package/workflows/src/run.ts +4 -1
- package/workflows/src/runtime-ops.ts +36 -6
- package/workflows/src/sandbox.ts +31 -109
- package/workflows/src/scenario.ts +102 -19
- package/workflows/src/schedules.ts +1 -1
- package/workflows/src/secret.ts +8 -7
- package/workflows/src/shared.ts +304 -10
- package/workflows/src/sites.ts +8 -0
- package/workflows/src/source.ts +31 -5
- package/workflows/src/supervisor.ts +40 -38
- package/workflows/src/tokens.ts +100 -9
- package/workflows/src/vendor-info.ts +21 -6
- package/workflows/src/version.ts +1 -1
- package/workflows/src/wakeup-driver.ts +1 -1
- package/workflows/src/wakeup-fake.ts +138 -0
- package/workflows/src/wakeup-service.ts +8 -24
- package/workflows/src/wakeup-type.ts +1 -1
- package/workflows/src/worker.ts +121 -58
- package/app/dist/client/assets/ArrowUp.es-DOgvoS0P.js +0 -1
- package/app/dist/client/assets/Copy.es-B0D5SwiQ.js +0 -1
- package/app/dist/client/assets/DialogTitle-BgjYK22C.js +0 -1
- package/app/dist/client/assets/FloppyDisk.es-DnuNe_a8.js +0 -1
- package/app/dist/client/assets/Globe.es-B6x2e4-a.js +0 -1
- package/app/dist/client/assets/MagnifyingGlass.es-DoNoHEhT.js +0 -1
- package/app/dist/client/assets/Play.es-BwXalGBh.js +0 -1
- package/app/dist/client/assets/Plug.es-CaZsN5P-.js +0 -1
- package/app/dist/client/assets/Plus.es-w9VPpTJB.js +0 -1
- package/app/dist/client/assets/Separator-BAhKFgSd.js +0 -1
- package/app/dist/client/assets/X.es-DKMYClf-.js +0 -1
- package/app/dist/client/assets/_id-BSRAaWtO.js +0 -1
- package/app/dist/client/assets/_id-BjDP-cPH.js +0 -1
- package/app/dist/client/assets/_id-BudM76zX.js +0 -1
- package/app/dist/client/assets/_id-C37U5bBa.js +0 -1
- package/app/dist/client/assets/_id-lmg24JVh.js +0 -2
- package/app/dist/client/assets/_name-CylqFo_t.js +0 -1
- package/app/dist/client/assets/_name-D8Gl8iwy.js +0 -4
- package/app/dist/client/assets/_name-DdPCU8pt.js +0 -1
- package/app/dist/client/assets/_name-TteWQXe0.js +0 -1
- package/app/dist/client/assets/_vendor-BLxW83yk.js +0 -1
- package/app/dist/client/assets/_vendor-Bq3uZU4-.js +0 -1
- package/app/dist/client/assets/app-chrome-H8uZ4dHI.js +0 -16
- package/app/dist/client/assets/app-scope-BeUW_8Qh.js +0 -1
- package/app/dist/client/assets/approval-DpgmTc63.js +0 -1
- package/app/dist/client/assets/apps-CoWzNm8M.js +0 -1
- package/app/dist/client/assets/change-glance-DbYcBT7H.js +0 -1
- package/app/dist/client/assets/changes-DIJvP7wQ.js +0 -1
- package/app/dist/client/assets/chat-button-BgpOfYh1.js +0 -1
- package/app/dist/client/assets/chat-prompt-hiawXcK0.js +0 -1
- package/app/dist/client/assets/common-Dw2i6XKZ.js +0 -3
- package/app/dist/client/assets/composite-D9GNDzFj.js +0 -1
- package/app/dist/client/assets/connect-CIq2KJTz.js +0 -1
- package/app/dist/client/assets/connections-iqd2XbWQ.js +0 -5
- package/app/dist/client/assets/connectors-rI8_D1n1.js +0 -1
- package/app/dist/client/assets/credentials-26vu6Fv5.js +0 -1
- package/app/dist/client/assets/data-sDMlKaLV.js +0 -1
- package/app/dist/client/assets/decidable-zcYI7bY8.js +0 -1
- package/app/dist/client/assets/declaration-form-BtSVvxhq.js +0 -1
- package/app/dist/client/assets/dialog-DskpUgkl.js +0 -1
- package/app/dist/client/assets/existing-BD3VgJ_8.js +0 -1
- package/app/dist/client/assets/graph-Prxl3c55.js +0 -7
- package/app/dist/client/assets/grid-diff-SMsvea6t.js +0 -1
- package/app/dist/client/assets/hosting-BBHUppH-.js +0 -1
- package/app/dist/client/assets/import-B92fd4Tl.js +0 -1
- package/app/dist/client/assets/inbox-57oGZtxE.js +0 -1
- package/app/dist/client/assets/inbox-B2AMNtk5.js +0 -1
- package/app/dist/client/assets/index-Bn3XeKy8.js +0 -10
- package/app/dist/client/assets/kit-BsK6VZTQ.js +0 -1
- package/app/dist/client/assets/lazyRouteComponent-Uri98HNq.js +0 -1
- package/app/dist/client/assets/motion-C8lNeYvK.js +0 -1
- package/app/dist/client/assets/people-ISOMYCTu.js +0 -1
- package/app/dist/client/assets/permissions-Cenat84K.js +0 -2
- package/app/dist/client/assets/permissions-grid-B2GtGwzv.js +0 -1
- package/app/dist/client/assets/route-BP1XwaTB.js +0 -1
- package/app/dist/client/assets/route-KVU6QgwJ.js +0 -1
- package/app/dist/client/assets/runs-table-35lNzKLn.js +0 -1
- package/app/dist/client/assets/scenario-DSwsavxS.js +0 -1
- package/app/dist/client/assets/scenario-graph-CAzWOtqV.js +0 -1
- package/app/dist/client/assets/separator-BlwkzEY0.js +0 -1
- package/app/dist/client/assets/site-icon-DZvOfBvU.js +0 -1
- package/app/dist/client/assets/sites.index-CcNo6N8u.js +0 -1
- package/app/dist/client/assets/spinner-BGy6LWIW.js +0 -1
- package/app/dist/client/assets/start-form-Bgo9I63s.js +0 -1
- package/app/dist/client/assets/store-BGu0d2Ld.js +0 -57
- package/app/dist/client/assets/style-CCDLLPgG.css +0 -2
- package/app/dist/client/assets/table-DjbI5VTn.js +0 -1
- package/app/dist/client/assets/textarea-DXO0eUdp.js +0 -1
- package/app/dist/client/assets/useLoaderData-BQd5yMlA.js +0 -1
- package/app/dist/client/assets/useOpenInteractionType-Bin8RjM5.js +0 -1
- package/app/dist/client/assets/useRegisterFieldControl-CQPTOU7Z.js +0 -1
- package/app/dist/client/assets/useValueChanged-DMkuvFZG.js +0 -1
- package/app/dist/client/assets/utils-CMsCvwYQ.js +0 -1
- package/app/dist/client/assets/who-are-you-Bt1WI3Cz.js +0 -1
- package/app/dist/client/assets/workflow-BJpO61A-.js +0 -1
- package/app/dist/client/assets/workflow-view-DP-UlRiH.js +0 -1
- package/app/dist/client/assets/workflows-BLCBgxbx.js +0 -1
- package/app/dist/server/assets/app-chrome-BYS81Vnx.js +0 -1410
- package/app/dist/server/assets/sites.index-1l0BtgVf.js +0 -138
- package/app/dist/server/assets/utils-wksS9pYh.js +0 -138
- package/template/scenarios/publish-post/publish.feature +0 -28
- package/template/workflows/publish-post.ts +0 -20
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{i as e,r as t,s as n}from"./engine-CBuzy-Ik.js";import{t as r}from"./react-dom-D6fTz1bt.js";import{$t as i,Ar as a,B as o,D as s,F as c,Hn as l,Jn as u,Ln as d,Lt as f,Mr as p,O as m,Ot as h,Q as g,Qn as _,U as v,Un as y,W as b,Wn as x,Xi as S,Xn as C,Y as w,Yn as T,Z as E,Zn as D,bn as ee,br as te,dr as O,er as k,fi as A,hi as j,hn as M,ir as ne,j as N,k as re,ln as P,lt as ie,mi as ae,nr as F,ot as I,pi as L,qt as oe,rn as se,rr as ce,s as R,sn as le,st as ue,tn as de,tr as fe,ut as pe,vi as me,wn as he,zr as z}from"./queries-XJ-fmuYb.js";import{B,Ct as V,Dt as ge,Et as H,J as _e,T as ve,ht as ye,m as be,p as xe,s as Se,vt as Ce}from"./common-DZLdx_jS.js";import{H as we,J as Te,L as Ee,U,W as De,a as Oe,d as ke,f as Ae,h as je,m as W,n as Me,o as Ne,p as Pe,q as Fe,s as Ie,t as Le}from"./kit-BZcdh1Xm.js";import{n as Re,r as ze}from"./Play.es-DGJ1CGhp.js";import{a as Be,c as Ve,i as He,l as Ue,n as We,o as Ge,s as Ke,t as qe}from"./start-form-6whPfUoW.js";import{Et as Je,F as Ye,Ht as Xe,Mt as Ze,P as Qe,an as $e,hn as et,pn as tt,zt as nt}from"./store-BT988jIX.js";import{V as rt,_ as it,c as at,d as ot,f as st,h as ct,i as lt,s as ut,t as dt,u as ft,v as pt}from"./button-D5kdANef.js";import{n as G,t as mt}from"./utils-BRvE9-Fo.js";import{u as ht}from"./composite-CoGyvQjv.js";import{a as gt,c as _t,d as vt,f as yt,i as bt,n as xt,o as St,p as Ct,r as wt,s as Tt,t as Et}from"./ArrowDown.es-BVRf--PS.js";import{a as Dt,c as Ot,i as kt,n as At,o as jt,r as Mt,s as Nt,t as Pt}from"./useRegisterFieldControl-CT8iqvDE.js";import{t as Ft}from"./useValueChanged-DBqn456b.js";import{t as It}from"./CaretDown.es-D12mWb2j.js";import{t as Lt}from"./spinner-XaRXIj9W.js";import{a as Rt,i as zt,n as Bt,o as Vt,r as Ht}from"./table-B81tv0LG.js";import{A as Ut,C as Wt,E as Gt,M as Kt,O as qt,S as Jt,T as Yt,at as Xt,i as Zt,j as Qt,k as $t,w as en,x as tn}from"./index-CA_5CFb4.js";import{t as nn}from"./X.es-B7rq0E_-.js";import{t as rn}from"./Plus.es-i3Vaa2WW.js";import{t as an}from"./textarea-CRpYU-qx.js";import{a as on,i as sn,n as cn,o as ln,r as un,s as dn,t as fn}from"./dialog-DDAfDsGh.js";import{r as pn}from"./review-BjpH-tT4.js";import{i as mn,n as hn,r as gn,t as _n}from"./clipboard-Zb0yr0Ja.js";import{t as vn}from"./MagnifyingGlass.es-CZ3i6pz0.js";import{a as yn,i as bn,n as xn,s as Sn,t as Cn}from"./schema-BpqanhX0.js";import{t as wn}from"./FloppyDisk.es-CDyDob8p.js";function Tn(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();let n=En(e);if(n.length!==En(t).length)return!1;for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(t,n[r])||!Object.is(e[n[r]],t[n[r]]))return!1;return!0}function En(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}var K=n(e(),1);function Dn(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if(`shouldBlockFn`in e)return e;if(typeof e==`function`){let n=!!(t??!0);return{shouldBlockFn:async()=>n?await e():!1,enableBeforeUnload:n,withResolver:!1}}let n=!!(e.condition??!0),r=e.blockerFn;return{shouldBlockFn:async()=>n&&r!==void 0?await r():n,enableBeforeUnload:n,withResolver:r===void 0}}function On(e,t){let{shouldBlockFn:n,enableBeforeUnload:r=!0,disabled:i=!1,withResolver:a=!1}=Dn(e,t),o=j(),{history:s}=o,[c,l]=K.useState({status:`idle`,current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return K.useEffect(()=>i?void 0:s.block({blockerFn:async e=>{function t(e){let t=o.parseLocation(e),[,n,r]=o.getMatchedRoutes(t.pathname);return r===void 0?{routeId:`__notFound__`,fullPath:t.pathname,pathname:t.pathname,params:n,search:o.options.parseSearch(e.search)}:{routeId:r.id,fullPath:r.fullPath,pathname:t.pathname,params:n,search:o.options.parseSearch(e.search)}}let r=t(e.currentLocation),i=t(e.nextLocation);if(r.routeId===`__notFound__`&&i.routeId!==`__notFound__`)return!1;let s=await n({action:e.action,current:r,next:i});if(!a)return s;if(!s)return!1;let c=await new Promise(t=>{l({status:`blocked`,current:r,next:i,action:e.action,proceed:()=>t(!1),reset:()=>t(!0)})});return l({status:`idle`,current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),c},enableBeforeUnload:r}),[n,r,i,a,s,o]),c}var kn=K.createContext(void 0);function An(e=!1){let t=K.useContext(kn);if(!t&&!e)throw Error(ct(86));return t}Object.keys(Nt);function jn(e,t){return e.matches(`:disabled`)?!1:!t||e.form===t||e.form===null&&!e.hasAttribute(`form`)}function Mn(e){if(e==null)return``;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}var Nn=new Map([[`bold`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M228,144v64a12,12,0,0,1-12,12H40a12,12,0,0,1-12-12V144a12,12,0,0,1,24,0v52H204V144a12,12,0,0,1,24,0ZM96.49,80.49,116,61v83a12,12,0,0,0,24,0V61l19.51,19.52a12,12,0,1,0,17-17l-40-40a12,12,0,0,0-17,0l-40,40a12,12,0,1,0,17,17Z`}))],[`duotone`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M216,48V208H40V48A16,16,0,0,1,56,32H200A16,16,0,0,1,216,48Z`,opacity:`0.2`}),K.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0ZM93.66,77.66,120,51.31V144a8,8,0,0,0,16,0V51.31l26.34,26.35a8,8,0,0,0,11.32-11.32l-40-40a8,8,0,0,0-11.32,0l-40,40A8,8,0,0,0,93.66,77.66Z`}))],[`fill`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0ZM88,80h32v64a8,8,0,0,0,16,0V80h32a8,8,0,0,0,5.66-13.66l-40-40a8,8,0,0,0-11.32,0l-40,40A8,8,0,0,0,88,80Z`}))],[`light`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M222,144v64a6,6,0,0,1-6,6H40a6,6,0,0,1-6-6V144a6,6,0,0,1,12,0v58H210V144a6,6,0,0,1,12,0ZM92.24,76.24,122,46.49V144a6,6,0,0,0,12,0V46.49l29.76,29.75a6,6,0,0,0,8.48-8.48l-40-40a6,6,0,0,0-8.48,0l-40,40a6,6,0,0,0,8.48,8.48Z`}))],[`regular`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0ZM93.66,77.66,120,51.31V144a8,8,0,0,0,16,0V51.31l26.34,26.35a8,8,0,0,0,11.32-11.32l-40-40a8,8,0,0,0-11.32,0l-40,40A8,8,0,0,0,93.66,77.66Z`}))],[`thin`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M220,144v64a4,4,0,0,1-4,4H40a4,4,0,0,1-4-4V144a4,4,0,0,1,8,0v60H212V144a4,4,0,0,1,8,0ZM90.83,74.83,124,41.66V144a4,4,0,0,0,8,0V41.66l33.17,33.17a4,4,0,1,0,5.66-5.66l-40-40a4,4,0,0,0-5.66,0l-40,40a4,4,0,0,0,5.66,5.66Z`}))]]),Pn=K.forwardRef((e,t)=>K.createElement(rt,{ref:t,...e,weights:Nn}));Pn.displayName=`UploadSimpleIcon`;var Fn=new Map([[`bold`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M120.49,167.51a12,12,0,0,1,0,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L68,179V48a12,12,0,0,1,24,0V179l11.51-11.52A12,12,0,0,1,120.49,167.51Zm96-96-32-32a12,12,0,0,0-17,0l-32,32a12,12,0,0,0,17,17L164,77V208a12,12,0,0,0,24,0V77l11.51,11.52a12,12,0,0,0,17-17Z`}))],[`duotone`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M176,48V208H80V48Z`,opacity:`0.2`}),K.createElement(`path`,{d:`M117.66,170.34a8,8,0,0,1,0,11.32l-32,32a8,8,0,0,1-11.32,0l-32-32a8,8,0,0,1,11.32-11.32L72,188.69V48a8,8,0,0,1,16,0V188.69l18.34-18.35A8,8,0,0,1,117.66,170.34Zm96-96-32-32a8,8,0,0,0-11.32,0l-32,32a8,8,0,0,0,11.32,11.32L168,67.31V208a8,8,0,0,0,16,0V67.31l18.34,18.35a8,8,0,0,0,11.32-11.32Z`}))],[`fill`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M119.39,172.94a8,8,0,0,1-1.73,8.72l-32,32a8,8,0,0,1-11.32,0l-32-32A8,8,0,0,1,48,168H72V48a8,8,0,0,1,16,0V168h24A8,8,0,0,1,119.39,172.94Zm94.27-98.6-32-32a8,8,0,0,0-11.32,0l-32,32A8,8,0,0,0,144,88h24V208a8,8,0,0,0,16,0V88h24a8,8,0,0,0,5.66-13.66Z`}))],[`light`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M116.24,171.76a6,6,0,0,1,0,8.48l-32,32a6,6,0,0,1-8.48,0l-32-32a6,6,0,0,1,8.48-8.48L74,193.51V48a6,6,0,0,1,12,0V193.51l21.76-21.75A6,6,0,0,1,116.24,171.76Zm96-96-32-32a6,6,0,0,0-8.48,0l-32,32a6,6,0,0,0,8.48,8.48L170,62.49V208a6,6,0,0,0,12,0V62.49l21.76,21.75a6,6,0,0,0,8.48-8.48Z`}))],[`regular`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M117.66,170.34a8,8,0,0,1,0,11.32l-32,32a8,8,0,0,1-11.32,0l-32-32a8,8,0,0,1,11.32-11.32L72,188.69V48a8,8,0,0,1,16,0V188.69l18.34-18.35A8,8,0,0,1,117.66,170.34Zm96-96-32-32a8,8,0,0,0-11.32,0l-32,32a8,8,0,0,0,11.32,11.32L168,67.31V208a8,8,0,0,0,16,0V67.31l18.34,18.35a8,8,0,0,0,11.32-11.32Z`}))],[`thin`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M114.83,173.17a4,4,0,0,1,0,5.66l-32,32a4,4,0,0,1-5.66,0l-32-32a4,4,0,0,1,5.66-5.66L76,198.34V48a4,4,0,0,1,8,0V198.34l25.17-25.17A4,4,0,0,1,114.83,173.17Zm96-96-32-32a4,4,0,0,0-5.66,0l-32,32a4,4,0,0,0,5.66,5.66L172,57.66V208a4,4,0,0,0,8,0V57.66l25.17,25.17a4,4,0,1,0,5.66-5.66Z`}))]]),In=K.forwardRef((e,t)=>K.createElement(rt,{ref:t,...e,weights:Fn}));In.displayName=`ArrowsDownUpIcon`;var Ln=new Map([[`bold`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M56.88,31.93A12,12,0,1,0,39.12,48.07l16,17.65C20.67,88.66,5.72,121.58,5,123.13a12.08,12.08,0,0,0,0,9.75c.37.82,9.13,20.26,28.49,39.61C59.37,198.34,92,212,128,212a131.34,131.34,0,0,0,51-10l20.09,22.1a12,12,0,0,0,17.76-16.14ZM128,188c-29.59,0-55.47-10.73-76.91-31.88A130.69,130.69,0,0,1,29.52,128c5.27-9.31,18.79-29.9,42-44.29l90.09,99.11A109.33,109.33,0,0,1,128,188Zm123-55.12c-.36.81-9,20-28,39.16a12,12,0,1,1-17-16.9A130.48,130.48,0,0,0,226.48,128a130.36,130.36,0,0,0-21.57-28.12C183.46,78.73,157.59,68,128,68c-3.35,0-6.7.14-10,.42a12,12,0,1,1-2-23.91c3.93-.34,8-.51,12-.51,36,0,68.63,13.67,94.49,39.52,19.35,19.35,28.11,38.8,28.48,39.61A12.08,12.08,0,0,1,251,132.88Z`}))],[`duotone`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M128,56C48,56,16,128,16,128s32,72,112,72,112-72,112-72S208,56,128,56Zm0,112a40,40,0,1,1,40-40A40,40,0,0,1,128,168Z`,opacity:`0.2`}),K.createElement(`path`,{d:`M53.92,34.62A8,8,0,1,0,42.08,45.38L61.32,66.55C25,88.84,9.38,123.2,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208a127.11,127.11,0,0,0,52.07-10.83l22,24.21a8,8,0,1,0,11.84-10.76Zm47.33,75.84,41.67,45.85a32,32,0,0,1-41.67-45.85ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.16,133.16,0,0,1,25,128c4.69-8.79,19.66-33.39,47.35-49.38l18,19.75a48,48,0,0,0,63.66,70l14.73,16.2A112,112,0,0,1,128,192Zm6-95.43a8,8,0,0,1,3-15.72,48.16,48.16,0,0,1,38.77,42.64,8,8,0,0,1-7.22,8.71,6.39,6.39,0,0,1-.75,0,8,8,0,0,1-8-7.26A32.09,32.09,0,0,0,134,96.57Zm113.28,34.69c-.42.94-10.55,23.37-33.36,43.8a8,8,0,1,1-10.67-11.92A132.77,132.77,0,0,0,231.05,128a133.15,133.15,0,0,0-23.12-30.77C185.67,75.19,158.78,64,128,64a118.37,118.37,0,0,0-19.36,1.57A8,8,0,1,1,106,49.79,134,134,0,0,1,128,48c34.88,0,66.57,13.26,91.66,38.35,18.83,18.83,27.3,37.62,27.65,38.41A8,8,0,0,1,247.31,131.26Z`}))],[`fill`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M96.68,57.87a4,4,0,0,1,2.08-6.6A130.13,130.13,0,0,1,128,48c34.88,0,66.57,13.26,91.66,38.35,18.83,18.83,27.3,37.62,27.65,38.41a8,8,0,0,1,0,6.5c-.35.79-8.82,19.57-27.65,38.4q-4.28,4.26-8.79,8.07a4,4,0,0,1-5.55-.36ZM213.92,210.62a8,8,0,1,1-11.84,10.76L180,197.13A127.21,127.21,0,0,1,128,208c-34.88,0-66.57-13.26-91.66-38.34C17.51,150.83,9,132.05,8.69,131.26a8,8,0,0,1,0-6.5C9,124,17.51,105.18,36.34,86.35a135,135,0,0,1,25-19.78L42.08,45.38A8,8,0,1,1,53.92,34.62Zm-65.49-48.25-52.69-58a40,40,0,0,0,52.69,58Z`}))],[`light`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M52.44,36A6,6,0,0,0,43.56,44L64.44,67c-37.28,21.9-53.23,57-53.92,58.57a6,6,0,0,0,0,4.88c.34.77,8.66,19.22,27.24,37.8C55,185.47,84.62,206,128,206a124.91,124.91,0,0,0,52.57-11.25l23,25.29a6,6,0,0,0,8.88-8.08Zm48.62,71.32,45,49.52a34,34,0,0,1-45-49.52ZM128,194c-31.38,0-58.78-11.42-81.45-33.93A134.57,134.57,0,0,1,22.69,128c4.29-8.2,20.1-35.18,50-51.91L92.89,98.3a46,46,0,0,0,61.35,67.48l17.81,19.6A113.47,113.47,0,0,1,128,194Zm6.4-99.4a6,6,0,0,1,2.25-11.79,46.17,46.17,0,0,1,37.15,40.87,6,6,0,0,1-5.42,6.53l-.56,0a6,6,0,0,1-6-5.45A34.1,34.1,0,0,0,134.4,94.6Zm111.08,35.85c-.41.92-10.37,23-32.86,43.12a6,6,0,1,1-8-8.94A134.07,134.07,0,0,0,233.31,128a134.67,134.67,0,0,0-23.86-32.07C186.78,73.42,159.38,62,128,62a120.19,120.19,0,0,0-19.69,1.6,6,6,0,1,1-2-11.83A131.12,131.12,0,0,1,128,50c43.38,0,73,20.54,90.24,37.76,18.58,18.58,26.9,37,27.24,37.81A6,6,0,0,1,245.48,130.45Z`}))],[`regular`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M53.92,34.62A8,8,0,1,0,42.08,45.38L61.32,66.55C25,88.84,9.38,123.2,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208a127.11,127.11,0,0,0,52.07-10.83l22,24.21a8,8,0,1,0,11.84-10.76Zm47.33,75.84,41.67,45.85a32,32,0,0,1-41.67-45.85ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.16,133.16,0,0,1,25,128c4.69-8.79,19.66-33.39,47.35-49.38l18,19.75a48,48,0,0,0,63.66,70l14.73,16.2A112,112,0,0,1,128,192Zm6-95.43a8,8,0,0,1,3-15.72,48.16,48.16,0,0,1,38.77,42.64,8,8,0,0,1-7.22,8.71,6.39,6.39,0,0,1-.75,0,8,8,0,0,1-8-7.26A32.09,32.09,0,0,0,134,96.57Zm113.28,34.69c-.42.94-10.55,23.37-33.36,43.8a8,8,0,1,1-10.67-11.92A132.77,132.77,0,0,0,231.05,128a133.15,133.15,0,0,0-23.12-30.77C185.67,75.19,158.78,64,128,64a118.37,118.37,0,0,0-19.36,1.57A8,8,0,1,1,106,49.79,134,134,0,0,1,128,48c34.88,0,66.57,13.26,91.66,38.35,18.83,18.83,27.3,37.62,27.65,38.41A8,8,0,0,1,247.31,131.26Z`}))],[`thin`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M51,37.31A4,4,0,0,0,45,42.69L67.59,67.5C29.34,89,13,124.81,12.34,126.38a4.08,4.08,0,0,0,0,3.25c.34.77,8.52,18.89,26.83,37.2,17,17,46.14,37.17,88.83,37.17a122.59,122.59,0,0,0,53.06-11.69l24,26.38a4,4,0,1,0,5.92-5.38ZM149.1,157.16A36,36,0,0,1,101,104.22ZM128,196c-32,0-59.89-11.65-83-34.62A135.81,135.81,0,0,1,20.44,128c3.65-7.23,20.09-36.81,52.68-54.43l22.45,24.7a44,44,0,0,0,59,64.83l20.89,23A114.94,114.94,0,0,1,128,196Zm6.78-103.36a4,4,0,0,1,1.49-7.86,44.15,44.15,0,0,1,35.54,39.09,4,4,0,0,1-3.61,4.35l-.38,0a4,4,0,0,1-4-3.63A36.1,36.1,0,0,0,134.78,92.64Zm108.88,37c-.41.91-10.2,22.58-32.38,42.45a4,4,0,0,1-2.67,1,4,4,0,0,1-2.67-7A136.71,136.71,0,0,0,235.56,128,136.07,136.07,0,0,0,211,94.62C187.89,71.65,160,60,128,60a122,122,0,0,0-20,1.63,4,4,0,0,1-1.32-7.89A129.3,129.3,0,0,1,128,52c42.7,0,71.87,20.22,88.83,37.18,18.31,18.31,26.49,36.44,26.83,37.2A4.08,4.08,0,0,1,243.66,129.63Z`}))]]),Rn=K.forwardRef((e,t)=>K.createElement(rt,{ref:t,...e,weights:Ln}));Rn.displayName=`EyeSlashIcon`;function zn(){try{return!1}catch{return!1}}function Bn(e,t){return Array.isArray(e)?`[${e.map(e=>Bn(e,!0)??`"[object]"`).join(`,`)}]`:e instanceof Error?t?void 0:JSON.stringify(e.message):typeof e==`symbol`||typeof e==`bigint`||t&&(e===void 0||typeof e==`number`&&!Number.isFinite(e))?JSON.stringify(String(e)):e===void 0||typeof e==`number`&&!Number.isFinite(e)?String(e):typeof e!=`object`||!e?JSON.stringify(e):void 0}function q(e,t={},n=`error`){let r=Object.entries(t).flatMap(([e,t])=>{try{let n=Bn(t,!1);return n===void 0?[]:[`${e}=${n}`]}catch{return[]}}).join(`, `).replace(/[\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16)}`);return`TanStack DB ${n} ${e}${r&&` (${r})`}: https://tanstack.com/db/latest/docs/errors#${n}-${e}`}function Vn(e,t){return q(e,t,`warning`)}var Hn=Symbol(`refProxy`);function Un(e){if(e&&typeof e==`object`)try{let t=e[Hn];return t===!0||Array.isArray(t)?t:void 0}catch{return}}function Wn(e){return e&&typeof e==`object`&&Un(e)!==void 0}var Gn=`__includes_scalar__`,Kn=0,qn=0,Jn=class{},Yn=class extends Jn{constructor(e,t,n){super(),this.type=`collectionRef`,this.#e=`source-${++Kn}`,this.collection=e,this.alias=t,this.#t=n??`binding-${++qn}`}#e;#t;get sourceId(){return this.#e}get bindingId(){return this.#t}},Xn=class extends Jn{constructor(e,t,n){super(),this.descriptor=e,this.alias=t,this.type=`descriptorRef`,this.#e=`source-${++Kn}`,this.#t=n??`binding-${++qn}`}#e;#t;get sourceId(){return this.#e}get bindingId(){return this.#t}};function Zn(e){if(e.type===`descriptorRef`)throw Error(q(113,{alias:e.alias}));return e.collection}var Qn=class extends Jn{constructor(e,t,n){super(),this.query=e,this.alias=t,this.type=`queryRef`,this.#e=n??`binding-${++qn}`}#e;get bindingId(){return this.#e}},$n=class extends Jn{constructor(e){super(),this.sources=e,this.type=`unionFrom`}get alias(){return this.sources[0]?.alias??``}},er=class extends Jn{constructor(e){super(),this.queries=e,this.type=`unionAll`}get alias(){return``}},J=class extends Jn{constructor(e,t,n){super(),this.path=e,this.type=`ref`,t!==void 0&&(this.sourceAlias=t),n!==void 0&&Object.defineProperty(this,"bindingId",{value:n,enumerable:!1})}};function tr(e){return e.sourceAlias!==void 0&&e.path[0]===e.sourceAlias?e.sourceAlias:void 0}function nr(e){return tr(e)===void 0?e.path:e.path.slice(1)}var rr=class extends Jn{constructor(e){super(),this.value=e,this.type=`val`}},ir=class extends Jn{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}},ar=class extends Jn{constructor(e,t,n){super(),this.name=e,this.args=t,this.grouping=n,this.type=`agg`}};function or(e){return e.type===`ref`?[e]:e.type===`func`||e.type===`agg`?e.args.flatMap(or):[]}var sr=class extends Jn{constructor(e,t,n,r,i,a,o,s=`collection`,c){super(),this.query=e,this.correlationField=t,this.childCorrelationField=n,this.fieldName=r,this.runtime=i,this.parentFilters=a,this.parentProjection=o,this.materialization=s,this.scalarField=c,this.type=`includesSubquery`}},cr=class extends Jn{constructor(e,t){super(),this.branches=e,this.defaultValue=t,this.type=`conditionalSelect`}};function lr(e){return e instanceof ar||e instanceof ir||e instanceof J||e instanceof rr}function ur(e){return lr(e)||e instanceof cr||e instanceof sr}function dr(e,t){let n=[],r=new Set,i=0,a=e=>{e.type===`collectionRef`||e.type===`descriptorRef`?r.has(e.sourceId)||(r.add(e.sourceId),n.push(e),i>0&&t?.add(e.sourceId)):e.type===`queryRef`?s(e.query):e.type===`unionFrom`?e.sources.forEach(a):e.queries.forEach(s)},o=e=>{e instanceof sr?(i++,s(e.query),i--):e instanceof cr?(e.branches.forEach(e=>o(e.value)),e.defaultValue!==void 0&&o(e.defaultValue)):typeof e==`object`&&e&&!Array.isArray(e)&&!ur(e)&&!Wn(e)&&Object.values(e).forEach(o)},s=e=>{a(e.from),e.join?.forEach(({from:e})=>a(e)),e.select&&Object.values(e.select).forEach(o)};return s(e),n}function fr(e){return dr(e).map(e=>e.type===`descriptorRef`?Zn(e):e)}function pr(e){return typeof e==`object`&&`expression`in e?e.expression:e}function mr(e){return typeof e==`object`&&`expression`in e?e.expression:e}function hr(e){return typeof e==`object`&&`expression`in e&&e.residual===!0}function gr(e){return{expression:e,residual:!0}}function _r(e){return e.type===`unionFrom`?e.sources:e.type===`unionAll`?[]:[e]}function vr(e,t,n){for(let r of _r(e.from))if(r.alias===t&&(n===void 0||r.bindingId===n))return r;for(let r of e.join||[])if(r.from.alias===t&&(n===void 0||r.from.bindingId===n))return r.from}function yr(e,t,n){let r=tr(t);if(r!==void 0){let i=vr(e,r,t.bindingId);if(!i)return;let a=nr(t);return i.type===`queryRef`?yr(i.query,new J(a),n):{collection:Zn(i),path:a,alias:r,sourceId:i.sourceId}}if(t.path.length!==0){if(t.path.length===1){let r=t.path[0];if(e.select){let t=e.select[r];if(t)return t.type===`ref`?yr(e,t,n):void 0}let i=_r(e.from)[0];return i?.type===`queryRef`?yr(i.query,new J([r]),n):i?.type===`collectionRef`?{collection:n,path:[r],alias:i.alias,sourceId:i.sourceId}:void 0}if(t.path.length>1){let[r,...i]=t.path,a=vr(e,r,t.bindingId);return a?a.type===`queryRef`?yr(a.query,new J(i),n):{collection:Zn(a),path:i,alias:r,sourceId:a.sourceId}:void 0}}}var br=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function xr(e){let t=e[Symbol.toStringTag];return typeof t==`string`&&br.has(t)&&Object.getPrototypeOf(e)?.[Symbol.toStringTag]===t}var Sr=3e4;function Cr(e,t){if(t.length<=Sr)e.push(...t);else for(let n=0;n<t.length;n+=Sr){let r=t.slice(n,n+Sr);e.push(...r)}}function wr(e,t,n){let r=0,i=e.length;for(;r<i;){let a=Math.floor((r+i)/2),o=n(e[a],t);if(o<0)r=a+1;else if(o>0)i=a;else return a}return r}function Tr(e,t){if(typeof e==typeof t){if(typeof e==`number`){let n=Number.isNaN(e),r=Number.isNaN(t);if(n||r)return n&&r?0:n?1:-1}return e<t?-1:+(e>t)}return typeof e==`string`?-1:1}function Er(e){return Dr(e,new Set)?JSON.stringify(Or(e)):`~${JSON.stringify(kr(e,new Set))}`}function Dr(e,t){if(e===null)return!0;switch(typeof e){case`boolean`:case`string`:return!0;case`number`:return Number.isFinite(e);case`undefined`:case`bigint`:case`symbol`:case`function`:return!1}return jr(e,t,()=>e instanceof Date||e instanceof RegExp||e instanceof Uint8Array||xr(e)||e instanceof Map||e instanceof Set?!1:Array.isArray(e)?e.every(e=>Dr(e,t)):Object.keys(e).every(n=>Dr(e[n],t)))}function Or(e){return e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:Array.isArray(e)?e.map(Or):Object.fromEntries(Object.keys(e).sort().map(t=>[t,Or(e[t])]))}function kr(e,t){if(e===void 0)return[`undefined`];if(e===null)return[`null`];switch(typeof e){case`boolean`:return[`boolean`,e];case`number`:return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:[`number`,e===0?0:e];case`bigint`:return[`bigint`,e.toString()];case`string`:return[`string`,e];case`symbol`:case`function`:throw TypeError(`Cannot serialize ${typeof e} as a structural relation key`)}return jr(e,t,()=>{if(e instanceof Date){let t=e.getTime();return Number.isNaN(t)?[`date`,`Invalid`]:[`date`,t]}if(e instanceof RegExp)return[`regexp`,e.source,e.flags];if(e instanceof Uint8Array)return[`bytes`,Array.from(e)];if(xr(e))return[`temporal`,e[Symbol.toStringTag],e.toString()];if(Array.isArray(e))return[`array`,e.map(e=>kr(e,t))];if(e instanceof Map){let n=[...e.entries()].map(([e,n])=>[kr(e,t),kr(n,t)]);return n.sort((e,t)=>Ar(JSON.stringify(e),JSON.stringify(t))),[`map`,n]}if(e instanceof Set){let n=[...e].map(e=>kr(e,t));return n.sort((e,t)=>Ar(JSON.stringify(e),JSON.stringify(t))),[`set`,n]}return[`object`,Object.keys(e).sort().map(n=>[n,kr(e[n],t)])]})}function Ar(e,t){return e<t?-1:+(e>t)}function jr(e,t,n){if(t.has(e))throw TypeError(`Cannot serialize a cyclic structural relation key`);t.add(e);try{return n()}finally{t.delete(e)}}var Mr=Hr(),Nr=Hr(),Pr=Hr(),Fr=Hr(),Ir=Hr(),Lr=Vr(),Rr=new Map,zr=0;function Br(e){let t=Symbol.keyFor(e);if(t!==void 0){let e=Rr.get(t);return e===void 0&&(e=++zr,Rr.set(t,e)),e}let n=Lr.get(e);return n===void 0&&(n=++zr,Lr.set(e,n)),n}function Vr(){let e=new WeakMap,t=Symbol();try{if(e.set(t,0),e.get(t)===0)return e}catch{}return new Map}function Hr(){return Math.random()*(2**31-1)>>>0}var Ur=new DataView(new ArrayBuffer(8)),Wr=class{constructor(){this.hash=Mr,this.length=0,this.carry=0,this.carryBytes=0}_mix(e){e=Math.imul(e,3432918353),e=e<<15|e>>>17,e=Math.imul(e,461845907),this.hash^=e,this.hash=this.hash<<13|this.hash>>>19,this.hash=Math.imul(this.hash,5)+3864292196}writeByte(e){this.carry|=(e&255)<<8*this.carryBytes,this.carryBytes++,this.length++,this.carryBytes===4&&(this._mix(this.carry>>>0),this.carry=0,this.carryBytes=0)}writeWord(e){if(this.length+=4,this.carryBytes===0){this._mix(e>>>0);return}let t=8*this.carryBytes;this._mix((this.carry|e<<t)>>>0),this.carry=e>>>32-t}update(e){switch(typeof e){case`symbol`:this.update(Ir),this.update(Br(e));return;case`string`:this.update(Nr);{let t=e.length-e.length%2;for(let n=0;n<t;n+=2)this.writeWord(e.charCodeAt(n)|e.charCodeAt(n+1)<<16);if(t<e.length){let n=e.charCodeAt(t);this.writeByte(n&255),this.writeByte(n>>>8&255)}}return;case`number`:Ur.setFloat64(0,e,!0),this.writeWord(Ur.getUint32(0,!0)),this.writeWord(Ur.getUint32(4,!0));return;case`bigint`:{let t=e;for(t<0n?(t=-t,this.update(Fr)):this.update(Pr);t>0n;)this.writeByte(Number(t&255n)),t>>=8n;e===0n&&this.writeByte(0);return}default:throw TypeError(`Unsupported input type: ${typeof e}`)}}digest(){if(this.carryBytes>0){let e=this.carry>>>0;e=Math.imul(e,3432918353),e=e<<15|e>>>17,e=Math.imul(e,461845907),this.hash^=e}return this.hash^=this.length,this.hash^=this.hash>>>16,this.hash=Math.imul(this.hash,2246822507),this.hash^=this.hash>>>13,this.hash=Math.imul(this.hash,3266489909),this.hash^=this.hash>>>16,this.hash>>>0}},Gr=Hr(),Kr=Hr(),qr=Hr(),Jr=Hr(),Yr=Hr(),Xr=Hr(),Zr={hash:Hr()},Qr={hash:Hr()},$r={hash:Hr()},ei={hash:Hr()},ti={hash:Hr()},ni={hash:Hr()},ri={hash:Hr()},ii={hash:Hr()},ai=1e6,oi=768,si=128,ci=new WeakMap,li=new WeakSet;function ui(e){Si(e)}function di(e){let t=new Wr;return mi(t,e),t.digest()}function fi(e,t){if(t.activeObjects.size>=oi)throw RangeError(`Value is too complex to hash safely: structural depth`);t.activeObjects.add(e);let n;try{let[r,i,a]=pi(e),o=new Wr;o.update(r.hash);for(let e of i)a?mi(o,e,t):o.update(e);if(a){let e=Object.keys(a);(!Array.isArray(a)||e.length!==a.length||e.length!==0&&e[e.length-1]!==String(a.length-1))&&e.sort(),e.push(...Object.getOwnPropertySymbols(a).filter(e=>Object.prototype.propertyIsEnumerable.call(a,e)).sort((e,t)=>Br(e)-Br(t)));for(let n of e)o.update(Yr),o.update(n),mi(o,a[n],t)}n=o.digest()}finally{t.activeObjects.delete(e)}return t.pendingHashes.set(e,n),n}function pi(e){if(e instanceof Date){let t=e.getTime();return[Zr,[Number.isNaN(t)?`invalid`:t]]}return _i(e)?[ri,[String.fromCharCode.apply(null,e)]]:xr(e)?[ii,[e[Symbol.toStringTag],e.toString()]]:e instanceof RegExp?[Qr,[e.source,e.flags,e.lastIndex],e]:e instanceof Map?[ti,[],[...e.entries()]]:e instanceof Set?[ni,[],[...e.values()]]:e instanceof Array?[ei,[e.length],e]:[$r,[],e]}function mi(e,t,n){if(n&&++n.work>ai)throw RangeError(`Value is too complex to hash safely: structural work`);if(t===null)e.update(qr);else switch(typeof t){case`undefined`:e.update(Jr);return;case`boolean`:e.update(t?Gr:Kr);return;case`number`:e.update(isNaN(t)?NaN:t===0?0:t);return;case`bigint`:case`string`:case`symbol`:e.update(t);return;case`object`:e.update(hi(t,n));return;case`function`:e.update(Si(t))}}function hi(e,t){let n=ci.get(e)??t?.pendingHashes.get(e);if(n!==void 0)return n;if(gi(e))return Si(e);if(t){if(t.activeObjects.has(e))throw TypeError(`Cannot hash cyclic structural values`);return fi(e,t)}let r={activeObjects:new Set,work:0,pendingHashes:new Map},i=fi(e,r);for(let[e,t]of r.pendingHashes)ci.set(e,t);return i}function gi(e){return li.has(e)||typeof File<`u`&&e instanceof File||_i(e)&&e.byteLength>si}function _i(e){return typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array}function vi(e,t){return bi(e,t)}function yi(e){return Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function bi(e,t,n,r){if(!n&&e===t||Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`||gi(e)||gi(t)||Array.isArray(e)&&Array.isArray(t)&&e.length!==t.length)return!1;let i=r?.get(e);if(i?.has(t))return!0;let[a,o,s]=pi(e),[c,l,u]=pi(t);if(a!==c||!o.every((e,t)=>e===l[t]))return!1;if(!s||!u)return!0;i?i.add(t):(r??=new Map).set(e,new Set([t]));let d=yi(s);return d.length===yi(u).length&&d.every(e=>Object.prototype.propertyIsEnumerable.call(u,e)&&bi(s[e],u[e],n,r))}var xi=1;function Si(e){let t=ci.get(e);return t===void 0&&(t=xi^Xr,xi++,ci.set(e,t),li.add(e)),t}var Ci=class e{#e;constructor(e=[]){this.#e=e}toString(e=!1){return`MultiSet(${JSON.stringify(this.#e,null,e?2:void 0)})`}toJSON(){return JSON.stringify(Array.from(this.getInner()))}static fromJSON(t){return new e(JSON.parse(t))}map(t){return new e(this.#e.map(([e,n])=>[t(e),n]))}filter(t){return new e(this.#e.filter(([e,n])=>t(e)))}negate(){return new e(this.#e.map(([e,t])=>[e,-t]))}concat(t){let n=[];return Cr(n,this.#e),Cr(n,t.getInner()),new e(n)}consolidate(){let e=this.#e;if(e.every(([e])=>Array.isArray(e)&&e.length===2&&(typeof e[0]==`string`||typeof e[0]==`number`)))return wi(e);let t;return e.some(([e])=>{let n=typeof e;return n!==`string`&&n!==`number`||(t??=n,n!==t)})?Ti(e,di):Ti(e,e=>e,!0)}extend(t){let n=t instanceof e?t.getInner():t;Cr(this.#e,n)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}};function wi(e){let t=new Map,n=new Map,r=[];for(let[i,a]of e){let[e,o]=i,s;if(Array.isArray(o)&&o.length===2){let t=n.get(e);t||n.set(e,t=new Map);let a=t.get(o[0]);a||t.set(o[0],a=new Map),s=a.get(o[1]),s||(a.set(o[1],s=[i,0]),r.push(s))}else{let n=t.get(e);n||t.set(e,n=new Map),s=n.get(o),s||(n.set(o,s=[i,0]),r.push(s))}s[1]+=a}return new Ci(r.filter(([,e])=>e!==0))}function Ti(e,t,n=!1){let r=new Map;for(let[n,i]of e){let e=t(n),a=r.get(e);a?a[1]+=i:r.set(e,[n,i])}let i=[];for(let[e,[t,a]]of r)a!==0&&i.push([n?e:t,a]);return new Ci(i)}var Ei=class{#e;constructor(e){this.#e=e}drain(){let e=[...this.#e].reverse();return this.#e.length=0,e}isEmpty(){return this.#e.length===0}},Di=class{#e=[];sendData(e){e instanceof Ci||(e=new Ci(e));for(let t of this.#e)t.unshift(e)}newReader(){let e=[];return this.#e.push(e),new Ei(e)}},Oi=class{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}},ki=class extends Oi{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}},Ai=class extends Oi{constructor(e,t,n,r){super(e,[t,n],r),this.id=e}inputAMessages(){return this.inputs[0].drain()}inputBMessages(){return this.inputs[1].drain()}},ji=class extends ki{run(){for(let e of this.inputMessages())this.output.sendData(this.inner(e))}},Mi=class{#e=[];#t=0;#n=!1;constructor(){}#r(){if(this.#n)throw Error(`Graph already finalized`)}getNextOperatorId(){return this.#r(),this.#t++}newInput(){this.#r();let e=new Di;return new Pi(this,e)}addOperator(e){this.#r(),this.#e.push(e)}finalize(){this.#r(),this.#n=!0}step(){if(!this.#n)throw Error(`Graph not finalized`);for(let e of this.#e)e.run()}pendingWork(){return this.#e.some(e=>e.hasPendingWork())}run(){if(!this.#n)throw Error(`Graph not finalized`);let e=!0;for(;e;){e=!1;for(let t of this.#e)t.hasPendingWork()&&(t.run(),e=!0)}}},Ni=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}connectReader(){return this.#t.newReader()}get writer(){return this.#t}get graph(){return this.#e}pipe(...e){return e.reduce((e,t)=>t(e),this)}},Pi=class extends Ni{sendData(e){this.writer.sendData(e)}},Fi=class extends Ai{run(){for(let e of this.inputAMessages())this.output.sendData(e);for(let e of this.inputBMessages())this.output.sendData(e)}};function Ii(e){return t=>{if(t.graph!==e.graph)throw Error(`Cannot concat streams from different graphs`);let n=new Ni(t.graph,new Di),r=new Fi(t.graph.getNextOperatorId(),t.connectReader(),e.connectReader(),n.writer);return t.graph.addOperator(r),n}}function Li(e,...t){return n=>{let r=new Ni(n.graph,new Di);return n.graph.addOperator(new e(n.graph.getNextOperatorId(),n.connectReader(),r.writer,...t)),r}}var Ri=class extends ki{run(){let e=this.inputMessages();if(e.length===0)return;let t=new Ci;for(let n of e)t.extend(n);let n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}};function zi(){return Li(Ri)}var Bi=class extends ki{#e;#t=new Map;#n=0;constructor(e,t,n,r=e=>e){super(e,t,n),this.#e=r}run(){let e=new Set;for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let t=this.#e(n),i=di(t),a=this.#t.get(i);a||this.#t.set(i,a=[]);let o=a.find(([e])=>vi(e,t));o||(o=[t,[a.length?--this.#n:i,n[1]],0,!1],a.push(o)),e.add(i),o[2]+=r}let t=[];for(let n of e){let e=this.#t.get(n),r=0;for(let n of e){let[,i,a,o]=n,s=a>0;s!==o&&t.push([i,s?1:-1]),n[3]=s,a!==0&&(e[r++]=n)}e.length=r,r===0&&this.#t.delete(n)}t.length>0&&this.output.sendData(new Ci(t))}};function Vi(e){return Li(Bi,e)}var Hi=class extends ji{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}};function Ui(e){return Li(Hi,e)}var Wi=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,Gi=new Map;function Ki(e){let t=Gi.get(e);if(t===void 0){t=new Uint8Array(256);for(let n=0;n<e.length;n++)t[e.charCodeAt(n)]=n;Gi.set(e,t)}return t}function qi(e,t,n,r){let i=n[0];if(t!=null&&e>=t)throw Error(e+` >= `+t);if(e.slice(-1)===i||t&&t.slice(-1)===i)throw Error(`trailing zero`);if(t){let a=0;for(;(e[a]||i)===t[a];)a++;if(a>0)return t.slice(0,a)+qi(e.slice(a),t.slice(a),n,r)}let a=e?r[e.charCodeAt(0)]:0,o=t==null?n.length:r[t.charCodeAt(0)];return o-a>1?n[Math.round(.5*(a+o))]:t&&t.length>1?t.slice(0,1):n[a]+qi(e.slice(1),null,n,r)}function Ji(e,t){if(e.length!==Yi(e[0],t))throw Error(`invalid integer part of order key: `+e)}function Yi(e,t){if(t===void 0){let t=e.charCodeAt(0);if(t>=97&&t<=122)return t-97+2;if(t>=65&&t<=90)return 90-t+2}else{let n=t.indexOf(e);if(n!==-1){let e=t.length/2;return n<e?e-n+1:n-e+2}}throw Error(`invalid order key head: `+e)}function Xi(e,t){let n=Yi(e[0],t);if(n>e.length)throw Error(`invalid order key: `+e);return e.slice(0,n)}function Zi(e,t,n){if(ta(e,t,n))throw Error(`invalid order key: `+e);let r=Xi(e,n);if(e.slice(r.length).slice(-1)===t[0])throw Error(`invalid order key: `+e)}function Qi(e,t,n,r){Ji(e,r);let i=e[0],a=t[0],o=``;for(let r=e.length-1;r>=1;r--){let s=n[e.charCodeAt(r)]+1;if(s===t.length)o=a+o;else return i+e.slice(1,r)+t[s]+o}if(r===void 0){if(i===`Z`)return`a`+a;if(i===`z`)return null;let e=String.fromCharCode(i.charCodeAt(0)+1);return e+(e>`a`?o+a:o.slice(1))}let s=r.indexOf(i);if(s===r.length-1)return null;let c=r[s+1],l=Yi(c,r)-Yi(i,r);return c+(l>0?o+a:l<0?o.slice(1):o)}function $i(e,t,n,r){Ji(e,r);let i=e[0],a=t[t.length-1],o=``;for(let r=e.length-1;r>=1;r--){let s=n[e.charCodeAt(r)]-1;if(s===-1)o=a+o;else return i+e.slice(1,r)+t[s]+o}if(r===void 0){if(i===`a`)return`Z`+a;if(i===`A`)return null;let e=String.fromCharCode(i.charCodeAt(0)-1);return e+(e<`Z`?o+a:o.slice(1))}let s=r.indexOf(i);if(s===0)return null;let c=r[s-1],l=Yi(c,r)-Yi(i,r);return c+(l>0?o+a:l<0?o.slice(1):o)}var ea=new Map;function ta(e,t,n=``){let r=ea.get(n);r===void 0&&(r=new Map,ea.set(n,r));let i=t.charCodeAt(0),a=r.get(i);return a===void 0&&(a=n===``?`A`+t[0].repeat(26):n[0]+t[0].repeat(n.length/2),r.set(i,a)),e===a}function na(e){for(let t=1;t<e.length;t++)if(e.charCodeAt(t-1)>=e.charCodeAt(t))return!1;return!0}function ra(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}var ia=new Set;function aa(e){if(!ia.has(e)){if(e.length<2||!na(e))throw Error(`digits must be at least 2 characters in strictly ascending character code order: `+e);if(!ra(e))throw Error(`digits must be single-byte (char code 0-255): `+e);ia.add(e)}}var oa=new Set;function sa(e){if(!oa.has(e)){if(e.length<2||e.length%2!=0||!na(e))throw Error(`intDigits must be an even number of at least 2 characters in strictly ascending character code order: `+e);if(!ra(e))throw Error(`intDigits must be single-byte (char code 0-255): `+e);oa.add(e)}}function ca(e,t,n=Wi,r=void 0){aa(n),r!==void 0&&sa(r);let i=Ki(n);if(e!=null&&Zi(e,n,r),t!=null&&Zi(t,n,r),e!=null&&t!=null&&e>t){let n=e;e=t,t=n}if(e==null){if(t==null)return(r===void 0?`a`:r[r.length/2])+n[0];let e=Xi(t,r),a=t.slice(e.length);if(ta(e,n,r))return e+qi(``,a,n,i);if(e<t)return e;let o=$i(e,n,i,r);if(o==null)throw Error(`cannot decrement any more`);return o}if(t==null){let t=Xi(e,r),a=e.slice(t.length);return Qi(t,n,i,r)??t+qi(a,null,n,i)}let a=Xi(e,r),o=e.slice(a.length),s=Xi(t,r),c=t.slice(s.length);if(a===s)return a+qi(o,c,n,i);let l=Qi(a,n,i,r);if(l==null)throw Error(`cannot increment any more`);return l<t?l:a+qi(o,null,n,i)}function la(e){return([t,n],[r,i])=>{let a=e(n,i);return a===0?Tr(t,r):a}}var ua=class{#e=[];#t;#n;#r;get#i(){return this.#n+this.#r}constructor(e,t,n){this.#n=e,this.#r=t,this.#t=([e],t)=>n(e,t)}get size(){return Math.max(0,Math.min(this.#i,this.#e.length)-Math.max(0,this.#n))}countLeadingInWindow(e){let t=0,n=Math.max(0,this.#n),r=Math.min(this.#i,this.#e.length);for(let i=n;i<r&&e(this.#e[i][0]);i++)t++;return t}move({offset:e,limit:t}){let n=this.#n,r=this.#r,i=this.#i;this.#n=e??n,this.#r=t??r;let a=(e,t)=>this.#e.slice(Math.max(0,e),Math.max(0,t)),o=(e,t,n,r)=>a(e,Math.min(t,n)).concat(a(Math.max(e,r),t));return{moveIns:o(this.#n,this.#i,n,i),moveOuts:o(n,i,this.#n,this.#i),changes:(r>0||this.#r>0)&&(n!==this.#n||r!==this.#r)}}insert(e){let t=wr(this.#e,e,this.#t),n=[e,ca(this.#e[t-1]?.[1]??null,this.#e[t]?.[1]??null)];return this.#e.splice(t,0,n),this.#a(t,!0)}delete(e){let t=wr(this.#e,e,this.#t),[n]=this.#e.splice(t,1);return this.#a(t,!1,n)}#a(e,t,n){let r=this.#n,i=this.#i;return r===i||e>=i?{moveIn:null,moveOut:null}:{moveIn:this.#e[t?Math.max(e,r):i-1]??null,moveOut:(t?this.#e[i]:e<r?this.#e[r-1]:n)??null}}};function*da(e){let t=new Map;for(let n of e)for(let[e,r]of n.getInner()){let n=t.get(e[0]);if(!n){t.set(e[0],[[e,r]]);continue}let i=n.find(([t])=>bi(t[1],e[1],!0));i?i[1]+=r:n.push([e,r])}for(let e of t.values())for(let t of e)t[1]<0&&(yield t);for(let e of t.values())for(let t of e)t[1]>0&&(yield t)}var fa=class extends ua{#e=new Map;get isEmpty(){return this.#e.size===0}processElement(e,t,n,r){let i=this.#e.get(e)??0,a=i+n;if(n!==0&&(a===0?this.#e.delete(e):this.#e.set(e,a)),i>0!=a>0){let n=a>0?super.insert([e,t]):super.delete([e,t]);pa(n.moveIn,r,1),pa(n.moveOut,r,-1)}}moveWindow(e,t){let n=super.move(e);for(let e of n.moveIns)pa(e,t,1);for(let e of n.moveOuts)pa(e,t,-1);return n.changes}};function pa(e,t,n){if(e){let[[r,i],a]=e;t.push([[r,[i,a]],n])}}var ma=class extends ki{#e=new Map;#t;#n;#r;constructor(e,t,n,r,i){super(e,t,n),this.#t=i.groupKeyFn,this.#r={limit:i.limit??1/0,offset:i.offset??0},this.#n=la(r),i.setSizeCallback?.(()=>{let e=0;for(let t of this.#e.values())e+=t.size;return e}),i.setWindowFn?.(({offset:e=this.#r.offset,limit:t=this.#r.limit})=>{this.#r={offset:e,limit:t};let n=[],r=!1;for(let e of this.#e.values())e.moveWindow(this.#r,n)&&(r=!0);r&&this.output.sendData(n)})}run(){let e=[];for(let[[t,n],r]of da(this.inputMessages())){let i=this.#t(t,n),a=this.#e.get(i);a||(a=new fa(this.#r.offset,this.#r.limit,this.#n),this.#e.set(i,a)),a.processElement(t,n,r,e),a.isEmpty&&this.#e.delete(i)}e.length>0&&this.output.sendData(e)}};function ha(e,t){return Li(ma,e,t)}var ga=Symbol(`NO_PREFIX`),_a=class extends Map{addValue(e,t,n=!1){if(t===0)return this.size===0;let r=xa(e),i=this.get(r);if(Sa(i)){let[a,o]=i;if(!ba(xa(a),r))throw Error(`Mismatching prefixes, this should never happen`);if(a===e||n&&r!==ga||di(a)===di(e)){let n=o+t;n===0?this.delete(r):this.set(r,[e,n])}else{let n=new va;n.set(di(a),i),n.set(di(e),[e,t]),this.set(r,n)}}else i===void 0?this.set(r,[e,t]):i.addValue(e,t)&&this.delete(r);return this.size===0}},va=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=di(e),r=this.get(n);if(r){let[,i]=r,a=i+t;a===0?this.delete(n):this.set(n,[e,a])}else this.set(n,[e,t]);return this.size===0}},ya=class e{#e;#t;#n;constructor(e){this.#e=new Map,(e?.trackPresence??!0)&&(this.#t=new Map),this.#n=e?.prefixIdentity??!1}static fromMultiSets(t){let n=new e;for(let e of t)for(let[t,r]of e.getInner()){let[e,i]=t;n.addValue(e,[i,r])}return n}toString(e=!1){return`Index(${JSON.stringify([...this.entries()],void 0,e?2:void 0)})`}get size(){return this.#e.size}#r(){if(this.#t===void 0)throw Error(`This Index does not track presence`);return this.#t}has(e){return this.#e.has(e)}hasPresence(e){return(this.#r().get(e)||0)!==0}getConsolidatedMultiplicity(e){return this.#r().get(e)||0}getPresenceKeys(){return this.#r().keys()}get(e){let t=this.#e.get(e);if(t===void 0)return[];if(Sa(t))return[t];if(t instanceof va)return[...t.values()];let n=[];for(let e of t.values())if(Sa(e))n.push(e);else for(let t of e.values())n.push(t);return n}*getIterator(e){let t=this.#e.get(e);if(Sa(t))yield t;else if(t===void 0)return;else if(t instanceof va)for(let e of t.values())yield e;else for(let e of t.values())if(Sa(e))yield e;else for(let t of e.values())yield t}*entries(){for(let e of this.#e.keys())for(let t of this.getIterator(e))yield[e,t]}*entriesIterators(){for(let e of this.#e.keys())yield[e,this.getIterator(e)]}addValue(e,t){let[n,r]=t;if(r===0)return;let i=this.#t;if(i){let t=(i.get(e)||0)+r;t===0?i.delete(e):i.set(e,t)}let a=this.#e.get(e);if(a===void 0)this.#e.set(e,t);else if(Sa(a))this.#i(e,a,n,r);else if(a instanceof va){let i=xa(n);if(i!==ga){let n=new _a;n.set(ga,a),n.set(i,t),this.#e.set(e,n)}else a.addValue(n,r)&&this.#e.delete(e)}else a.addValue(n,r,this.#n)&&this.#e.delete(e)}#i(e,t,n,r){let[i,a]=t;if(i===n){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}let o=xa(n),s=xa(i);if(ba(s,o)&&(this.#n&&o!==ga||di(i)===di(n))){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t])}else if(s===ga&&o===ga){let a=new va;a.set(di(i),t),a.set(di(n),[n,r]),this.#e.set(e,a)}else{let a=new _a;if(ba(s,o)){let e=new va;e.set(di(i),t),e.set(di(n),[n,r]),a.set(s,e)}else a.set(s,t),a.set(o,[n,r]);this.#e.set(e,a)}}append(e){for(let[t,n]of e.entries())this.addValue(t,n)}join(e){let t=[];if(this.size<=e.size)for(let[n,r]of this.entriesIterators()){if(!e.has(n))continue;let i=e.get(n);for(let[e,a]of r)for(let[r,o]of i)a!==0&&o!==0&&t.push([[n,[e,r]],a*o])}else for(let[n,r]of e.entriesIterators()){if(!this.has(n))continue;let e=this.get(n);for(let[i,a]of r)for(let[r,o]of e)o!==0&&a!==0&&t.push([[n,[r,i]],o*a])}return new Ci(t)}};function ba(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function xa(e){return Array.isArray(e)&&(typeof e[0]==`string`||typeof e[0]==`number`||typeof e[0]==`bigint`)?e[0]:ga}function Sa(e){return Array.isArray(e)}var Ca=class extends Ai{#e=new ya;#t=new ya;#n;constructor(e,t,n,r,i=`inner`){super(e,t,n,r),this.#n=i}run(){let e=ya.fromMultiSets(this.inputAMessages()),t=ya.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;let n=new Ci;this.#n!==`anti`&&this.emitInnerResults(e,t,n),(this.#n===`left`||this.#n===`full`||this.#n===`anti`)&&this.emitLeftOuterResults(e,t,n),(this.#n===`right`||this.#n===`full`)&&this.emitRightOuterResults(e,t,n),this.#e.append(e),this.#t.append(t),n.getInner().length>0&&this.output.sendData(n)}emitInnerResults(e,t,n){e.size>0&&n.extend(e.join(this.#t)),t.size>0&&n.extend(this.#e.join(t)),e.size>0&&t.size>0&&n.extend(e.join(t))}emitLeftOuterResults(e,t,n){if(e.size>0){for(let[r,i]of e.entriesIterators())if(this.#t.getConsolidatedMultiplicity(r)+t.getConsolidatedMultiplicity(r)===0)for(let[e,t]of i)t!==0&&n.add([r,[e,null]],t)}if(t.size>0)for(let e of t.getPresenceKeys()){let r=this.#t.getConsolidatedMultiplicity(e),i=t.getConsolidatedMultiplicity(e);if(i===0)continue;let a=r+i;if(r===0==(a===0))continue;let o=r===0;for(let[t,r]of this.#e.getIterator(e))r!==0&&n.add([e,[t,null]],o?-r:+r)}}emitRightOuterResults(e,t,n){if(t.size>0){for(let[r,i]of t.entriesIterators())if(this.#e.getConsolidatedMultiplicity(r)+e.getConsolidatedMultiplicity(r)===0)for(let[e,t]of i)t!==0&&n.add([r,[null,e]],t)}if(e.size>0)for(let t of e.getPresenceKeys()){let r=this.#e.getConsolidatedMultiplicity(t),i=e.getConsolidatedMultiplicity(t);if(i===0)continue;let a=r+i;if(r===0==(a===0))continue;let o=r===0;for(let[e,r]of this.#t.getIterator(t))r!==0&&n.add([t,[null,e]],o?-r:+r)}}};function wa(e,t=`inner`){return n=>{if(n.graph!==e.graph)throw Error(`Cannot join streams from different graphs`);let r=new Ni(n.graph,new Di),i=new Ca(n.graph.getNextOperatorId(),n.connectReader(),e.connectReader(),r.writer,t);return n.graph.addOperator(i),r}}var Ta=class extends ji{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.map(this.#e)}};function Y(e){return Li(Ta,e)}var Ea=class extends ki{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}run(){for(let e of this.inputMessages())this.#e(e),this.output.sendData(e)}};function Da(e){return Li(Ea,e)}function Oa(e,t){return e===t||e!==e&&t!==t}function ka(e){return e===0?0:e}var Aa=class extends ki{#e;#t=new ya({trackPresence:!1});#n;constructor(e,t,n,r,i){super(e,t,n),this.#e=new ya({...i,trackPresence:!1}),this.#n=r}run(){let e=new Set;for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let[t,i]=n;this.#e.addValue(t,[i,r]),e.add(t)}let t=[];for(let n of e){let e=this.#e.get(n),r=this.#t.get(n),i=this.#n(e);if(i.length<=1&&r.length<=1){let e=r[0],a=i[0],o=a===void 0?void 0:ka(a[0]);if(e!==void 0&&a!==void 0&&Oa(e[0],o)){let r=a[1]-e[1];r!==0&&(t.push([[n,e[0]],r]),this.#t.addValue(n,[e[0],r]));continue}e!==void 0&&(t.push([[n,e[0]],-e[1]]),this.#t.addValue(n,[e[0],-e[1]])),a!==void 0&&a[1]!==0&&(t.push([[n,o],a[1]]),this.#t.addValue(n,[o,a[1]]));continue}let a=new Map,o=new Map;for(let[e,t]of i){let n=a.get(e)??0;a.set(e,n+t)}for(let[e,t]of r){let n=o.get(e)??0;o.set(e,n+t)}for(let[e,r]of o)a.has(e)||(t.push([[n,e],-r]),this.#t.addValue(n,[e,-r]));for(let[e,r]of a)o.has(e)||r!==0&&(t.push([[n,e],r]),this.#t.addValue(n,[e,r]));for(let[e,r]of a){let i=o.get(e);if(i!==void 0){let a=r-i;a!==0&&(t.push([[n,e],a]),this.#t.addValue(n,[e,a]))}}}t.length>0&&this.output.sendData(new Ci(t))}};function ja(e,t){return Li(Aa,e,t)}var Ma=class extends ji{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}};function Na(e){return Li(Ma,e)}var Pa=class extends ki{#e;constructor(e,t,n,r,i){super(e,t,n),this.#e=new fa(i.offset??0,i.limit??1/0,la(r)),i.setSizeCallback?.(e=>e?this.#e.countLeadingInWindow(([,t])=>e(t)):this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}moveTopK({offset:e,limit:t}){let n=[];this.#e.moveWindow({offset:e,limit:t},n)&&this.output.sendData(n)}run(){let e=[];for(let[[t,n],r]of da(this.inputMessages()))this.processElement(t,n,r,e);e.length>0&&this.output.sendData(e)}processElement(e,t,n,r){this.#e.processElement(e,t,n,r)}};function Fa(e,t){return Li(Pa,e,t||{})}function Ia(e,t,n){let r={limit:t?.limit??1/0,offset:t?.offset??0,setSizeCallback:t?.setSizeCallback,setWindowFn:t?.setWindowFn,groupKeyFn:t?.groupKeyFn},i=t?.comparator??((e,t)=>e===t?0:e<t?-1:1);return t=>t.pipe(n((t,n)=>i(e(t),e(n)),r),zi())}function La(e,t){return Ia(e,t,ha)}function Ra(e,t){return Ia(e,t,Fa)}function za(){let e=typeof globalThis<`u`?globalThis.crypto:void 0;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();if(e&&typeof e.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[];for(let e=0;e<16;e++)n.push(t[e].toString(16).padStart(2,`0`));return n.slice(0,4).join(``)+`-`+n.slice(4,6).join(``)+`-`+n.slice(6,8).join(``)+`-`+n.slice(8,10).join(``)+`-`+n.slice(10,16).join(``)}throw Error(q(171))}var Ba=Symbol.for(`@tanstack/db.collectionOptions`);function Va(e){return typeof e==`object`&&!!e&&e[Ba]===!0}var Ha=Symbol.for(`@tanstack/db.collectionOptions.claim`);function Ua(e){return Va(e)}var Wa=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},Ga=class extends Wa{constructor(e,t,n){let r=`${e===`insert`?`Insert`:`Update`} validation failed: ${t.map(e=>`
|
|
2
|
+
- ${e.message} - path: ${e.path}`).join(``)}`;super(n||r),this.name=`SchemaValidationError`,this.type=e,this.issues=t}},Ka=class extends Wa{constructor(e){super(e),this.name=`CollectionConfigurationError`}},qa=class extends Ka{constructor(e){super(q(3,{reason:e})),this.name=`InvalidSyncPersistenceCapabilityError`}},Ja=class extends Ka{constructor(){super(q(4))}},Ya=class extends Ka{constructor(){super(q(5))}},Xa=class extends Ka{constructor(){super(q(6))}},Za=class extends Ka{constructor(){super(q(7))}},Qa=class extends Wa{constructor(e){super(e),this.name=`CollectionStateError`}},$a=class extends Qa{constructor(e,t){super(q(8,{operation:e,collectionId:t}))}},eo=class extends Qa{constructor(e,t){super(q(254,{collectionId:e,dependents:t}))}},to=class extends Qa{constructor(e){super(q(255,{collectionId:e}))}},no=class extends Qa{constructor(e){super(q(256,{collectionId:e}))}},ro=class extends Qa{constructor(e,t,n){super(q(9,{from:e,to:t,collectionId:n}))}},io=class extends Qa{constructor(){super(q(10))}},ao=class extends Qa{constructor(){super(q(11))}},oo=class extends Qa{constructor(){super(q(12))}},so=class extends Wa{constructor(e){super(e),this.name=`CollectionOperationError`}},co=class extends so{constructor(e){super(q(14,{item:e}))}},lo=class extends so{constructor(e,t){super(q(15,{key:e,type:e===null?`null`:typeof e}))}},uo=class extends so{constructor(e){super(q(16,{key:e}))}},fo=class extends so{constructor(e,t,n){super(q(17,{key:e,collectionId:t,...n}))}},po=class extends so{constructor(){super(q(18))}},mo=class extends so{constructor(){super(q(19))}},ho=class extends so{constructor(e){super(q(20,{key:e}))}},go=class extends so{constructor(e,t){super(q(21,{originalKey:e,newKey:t}))}},_o=class extends so{constructor(){super(q(22))}},vo=class extends so{constructor(e){super(q(23,{key:e}))}},yo=class extends Wa{constructor(e){super(e),this.name=`MissingHandlerError`}},bo=class extends yo{constructor(){super(q(24))}},xo=class extends yo{constructor(){super(q(25))}},So=class extends yo{constructor(){super(q(26))}},Co=class extends Wa{constructor(e){super(e),this.name=`TransactionError`}},wo=class extends Co{constructor(){super(q(86)),this.name=`PacedTransactionManualCommitError`}},To=class extends Co{constructor(){super(q(27)),this.name=`QueueCapacityExceededError`}},Eo=class extends Co{constructor(){super(q(28)),this.name=`QueueDisposedError`}},Do=class extends Co{constructor(){super(q(29)),this.name=`ThrottleCallDroppedError`}},Oo=class extends Co{constructor(){super(q(30)),this.name=`DebounceCallDroppedError`}},ko=class extends Co{constructor(){super(q(31))}},Ao=class extends Co{constructor(){super(q(33))}},jo=class extends Co{constructor(){super(q(34))}},Mo=class extends Co{constructor(e){super(q(233,{id:e}))}},No=class extends Co{constructor(){super(q(35))}},Po=class extends Co{constructor(){super(q(36))}},Fo=class extends Co{constructor(){super(q(37))}},Io=class extends Co{constructor(e){super(q(38,{key:e}))}},Lo=class extends Co{constructor(){super(q(39))}},Ro=class extends Co{constructor(){super(q(40))}},zo=class extends Co{constructor(e){super(q(41,{detail:e}))}},Bo=class extends Wa{constructor(e){super(e),this.name=`QueryBuilderError`}},Vo=class extends Bo{constructor(e){super(q(42,{context:e}))}},Ho=class extends Bo{constructor(e){super(q(43,{context:e}))}},Uo=class extends Bo{constructor(e){super(q(44,{alias:e}))}},Wo=class extends Bo{constructor(e){super(q(248,{field:e}))}},Go=class extends Bo{constructor(e,t){super(q(45,{context:e,type:t}))}},Ko=class extends Bo{constructor(){super(q(46))}},qo=class extends Bo{constructor(){super(q(47))}},Jo=class extends Bo{constructor(e){super(q(48,{valueType:e}))}},Yo=class extends Wa{constructor(e){super(e),this.name=`QueryCompilationError`}},Xo=class extends Yo{constructor(e){super(q(49,{segment:e})),this.name=`UnsafeAliasPathError`}},Zo=class extends Yo{constructor(){super(q(50))}},Qo=class extends Yo{constructor(){super(q(51))}},$o=class extends Yo{constructor(){super(q(247))}},es=class extends Yo{constructor(e){super(q(52,{valueDescription:e}))}},ts=class extends Yo{constructor(){super(q(53))}},ns=class extends Yo{constructor(){super(q(54))}},rs=class extends Yo{constructor(){super(q(55))}},is=class extends Yo{constructor(e,t,n){super(q(56,{alias:e,collectionId:t,availableKeys:n}))}},as=class extends Yo{constructor(e){super(q(58,{type:e}))}},os=class extends Yo{constructor(e){super(q(59,{type:e}))}},ss=class extends Yo{constructor(){super(q(60))}},cs=class extends Yo{constructor(e){super(q(61,{functionName:e}))}},ls=class extends Yo{constructor(e){super(q(62,{collectionId:e}))}},us=class extends Wa{constructor(e){super(e),this.name=`JoinError`}},ds=class extends us{constructor(e){super(q(63,{joinType:e}))}},fs=class extends us{constructor(e){super(q(64,{sourceAlias:e}))}},ps=class extends us{constructor(){super(q(65))}},ms=class extends us{constructor(e){super(q(66,{sourceAlias:e}))}},hs=class extends us{constructor(e){super(q(67,{sourceAlias:e}))}},gs=class extends us{constructor(){super(q(68))}},_s=class extends us{constructor(e){super(q(69,{type:e}))}},vs=class extends Wa{constructor(e){super(e),this.name=`GroupByError`}},ys=class extends vs{constructor(e){super(q(70,{alias:e}))}},bs=class extends Wa{constructor(e,t){super(q(78,{collectionId:e,error:t})),this.name=`SyncCleanupError`}},xs=class extends Error{constructor(){super(q(79)),this.name=`AbortError`}},Ss=class extends Error{constructor(){super(q(80)),this.name=`AbortError`}},Cs=class extends Error{constructor(){super(q(81)),this.name=`AbortError`}},ws=class extends Wa{constructor(e){super(e),this.name=`QueryOptimizerError`}},Ts=class extends ws{constructor(){super(q(82))}},Es=class extends Yo{constructor(e){super(q(83,{missingAliases:e}))}},Ds=class extends Yo{constructor(){super(q(84))}},Os=class extends Yo{constructor(){super(q(244))}},ks=class extends Wa{constructor(){super(q(85)),this.name=`SetWindowReentrancyError`}},As=class extends Error{constructor(e,t){super(q(87,{path:e,reason:t})),this.path=e,this.reason=t,this.name=`UnhashableQueryIRError`}},js=class extends Wa{constructor(e,t){super(q(245,{bindingName:e,collectionId:t})),this.bindingName=e,this.collectionId=t,this.name=`SourceCollectionIdReuseError`}},Ms=class extends Wa{constructor(){super(q(251)),this.name=`InvalidPoolOptionError`}},Ns=Symbol(`liveQueryInternal`),Ps=new WeakMap;function Fs(e){return e.utils?.[Ns]?.getBuilder?.()}function Is(e,t){Ps.set(e,t)}function Ls(e){return Ps.get(e)}function Rs(e){if(e.autoIndex===`eager`&&!e.defaultIndexType)throw new Ka(q(206))}var zs=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`];function Bs(e,t){return Ks(e,t)}function Vs(e,t){return Ks(e,t,4)}function Hs(e){return e===null||Object.getPrototypeOf(e)===null}function Us(e){let t=Object.keys(e);for(let n of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,n)&&t.push(n);return t}var Ws=2,Gs=8;function Ks(e,t,n=0,r){let i=n&1;if(!(n&4)&&e===t||Object.is(e,t))return!0;if(e==null||t==null||typeof e!=typeof t||n&Ws&&typeof e==`object`&&Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(r?.has(e))return r.get(e)===t;if(e instanceof Date)return t instanceof Date&&Object.is(e.getTime(),t.getTime());if(t instanceof Date)return!1;if(e instanceof RegExp)return t instanceof RegExp&&e.source===t.source&&e.flags===t.flags&&(!i||e.lastIndex===t.lastIndex);if(t instanceof RegExp)return!1;if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;(r??=new Map).set(e,t);let a=i&&Array.from(t.entries()),o=Array.from(e.entries()).every(([e,i],o)=>a?Object.is(e,a[o][0])&&Ks(i,a[o][1],n,r):t.has(e)&&Ks(i,t.get(e),n,r));return r.delete(e),o}if(t instanceof Map)return!1;if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;(r??=new Map).set(e,t);let a=Array.from(e),o=Array.from(t);if(i){let t=Ks(a,o,n,r);return r.delete(e),t}if(a.every(e=>typeof e!=`object`))return r.delete(e),a.every(e=>t.has(e));if(a.every((e,t)=>Ks(e,o[t],n,r)))return r.delete(e),!0;let s=a.map(e=>o.flatMap((t,i)=>Ks(e,t,n,r)?[i]:[])),c=new Map,l=(e,t)=>{let n=s[e],r=n.find(e=>!c.has(e));return r===void 0?n.some(n=>{if(t.has(n))return!1;t.add(n);let r=c.get(n);return r!==void 0&&!l(r,t)?!1:(c.set(n,e),!0)}):(c.set(r,e),!0)},u=a.every((e,t)=>l(t,new Set));return r.delete(e),u}if(t instanceof Set)return!1;let a=ArrayBuffer.isView(e)&&!(e instanceof DataView);if(a!==(ArrayBuffer.isView(t)&&!(t instanceof DataView)))return!1;if(a){let r=e,a=t;return(!i||Object.getPrototypeOf(e)===Object.getPrototypeOf(t))&&r.length===a.length&&r.every((e,t)=>Ks(e,a[t],n))}if(Js(e)&&Js(t)){let n=e[Symbol.toStringTag];if(n!==t[Symbol.toStringTag])return!1;if(n===`Temporal.Duration`){let n=e,r=t;return zs.every(e=>n[e]===r[e])}return typeof e.equals==`function`?e.equals(t):e.toString()===t.toString()}if(Js(t)||Array.isArray(e)!==Array.isArray(t)||Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&!i){(r??=new Map).set(e,t);let i=!0;for(let a=0;a<e.length;a++)if(!Ks(e[a],t[a],n,r)){i=!1;break}return r.delete(e),i}if(typeof e==`object`){let a=Object.getPrototypeOf(e),o=Object.getPrototypeOf(t),s=Hs(a),c=Hs(o);if(a!==o&&(n&4&&!i||!s&&!c)||n&Gs&&!(s&&c))return!1;let l=Us(e),u=Us(t);if(l.length!==u.length)return!1;if(l.length===0&&!Array.isArray(e)&&!(s&&c))return e instanceof URL&&e.href===t.href;let d=!1,f=!0;for(let i of l){let a=e[i];if(!d&&typeof a==`object`&&a&&((r??=new Map).set(e,t),d=!0),!Object.prototype.propertyIsEnumerable.call(t,i)||!Ks(a,t[i],n,r)){f=!1;break}}return d&&r.delete(e),f}return!1}var qs=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Js(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&qs.has(t)}var Ys={direction:`asc`,nulls:`first`,stringSort:`locale`};function Xs(e,t){if(typeof e!=`string`&&typeof e!=`number`)throw e===void 0?new co(t):new lo(e,t)}function Zs(){let e=new WeakMap,t,n,r,i=0,a=(e,t)=>{let n=e.get(t);return n===void 0&&(n=++i,e.set(t,n)),n};return i=>{r??=nc();let o;if(typeof i==`symbol`){let e=Symbol.keyFor(i);e===void 0?(t??=Qs(),o=a(t,i)):(n??=new Map,o=a(n,e))}else o=a(e,i);return[`runtimeReference`,r,o]}}function Qs(){let e=new WeakMap,t=Symbol();try{if(e.set(t,0),e.get(t)===0)return e}catch{}return new Map}var $s;function ec(e){return $s??=Zs(),$s(e)}function tc(e){return e?.stringSort===`custom`?{...e,compare:ec(e.compare)}:e}function nc(){let e=new Uint32Array(4),t=Reflect.get(globalThis,`crypto`);return typeof t?.getRandomValues==`function`?(t.getRandomValues(e),Array.from(e,e=>e.toString(36)).join(`-`)):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}function rc(e){return typeof e==`number`&&Number.isNaN(e)||e instanceof Date&&Number.isNaN(e.getTime())}var ic=(e,t,n)=>{let{nulls:r}=n;if(e==null&&t==null)return 0;if(e==null)return r===`first`?-1:1;if(t==null)return r===`first`?1:-1;let i=rc(e),a=rc(t);if(i&&a)return 0;if(i)return 1;if(a)return-1;if(typeof e==`string`&&typeof t==`string`){if(n.stringSort===`custom`)return n.compare(e,t);if(n.stringSort===`locale`)return e.localeCompare(t,n.locale,n.localeOptions)}if(Array.isArray(e)&&Array.isArray(t)){for(let r=0;r<Math.min(e.length,t.length);r++){let i=ic(e[r],t[r],n);if(i!==0)return i}return e.length-t.length}if(e instanceof Date&&t instanceof Date)return e.getTime()-t.getTime();if(Js(e)&&Js(t))return gc(e,t);let o=typeof e==`symbol`,s=typeof t==`symbol`;if(o&&s)return e===t?0:ec(e)[2]-ec(t)[2];if(o)return 1;if(s)return-1;let c=typeof e==`object`,l=typeof t==`object`;if(c||l){if(c&&l)return ec(e)[2]-ec(t)[2];if(c)return 1;if(l)return-1}return e<t?-1:+(e>t)},ac=(e,t,n)=>e==null||t==null?ic(e,t,n):ic(t,e,n);function oc(e){if(lc(e))return`Binary`;if(Js(e)){let t=e[Symbol.toStringTag],n=e;return t===`Temporal.Duration`&&(n.years||n.months||n.weeks)?`Temporal.Duration.calendar`:t}return Array.isArray(e)?`Array`:`Object`}function sc(e,t=`values`){let n=e.direction===`asc`?ic:ac;if(t!==`index`)return(t,r)=>n(t,r,e);let r=e.direction===`asc`?1:-1;return(t,i)=>{if(t!=null&&i!=null){t instanceof Date&&(t=t.getTime()),i instanceof Date&&(i=i.getTime());let e=typeof t,n=typeof i;if(e!==n)return(e<n?-1:1)*r;if(e===`object`){let e=oc(t),n=oc(i);if(e!==n)return(e<n?-1:1)*r;if(e===`Binary`||e===`Temporal.Duration.calendar`||e===`Temporal.PlainMonthDay`){let e=hc(t),n=hc(i);return(e<n?-1:+(e>n))*r}}}return n(t,i,e)}}var cc=sc({direction:`asc`,nulls:`first`,stringSort:`locale`});function lc(e){return e instanceof Uint8Array||typeof Buffer<`u`&&e instanceof Buffer}function uc(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}var dc=`\0tanstack-db:`;function fc(e,t){return`${dc}${e}:${t}`}var pc=new WeakMap;function mc(e){let t=pc.get(e);if(t)return t;let n;if(e.byteLength<=8192)n=String.fromCharCode.apply(null,e);else{let t=[];for(let n=0;n<e.byteLength;n+=8192)t.push(String.fromCharCode.apply(null,e.subarray(n,n+8192)));n=t.join(``)}let r=fc(`binary`,n);return pc.set(e,r),r}function hc(e){if(typeof e==`string`)return e.startsWith(dc)?fc(`string`,e):e;if(typeof e!=`object`||!e)return e;if(e instanceof Date)return e.getTime();if(Js(e)){let t=e[Symbol.toStringTag];if(t===`Temporal.Duration`){let n=e;return fc(t,zs.map(e=>n[e]).join(`,`))}return fc(t,e.toString())}return lc(e)?mc(e):e}function gc(e,t){let n=e[Symbol.toStringTag],r=t[Symbol.toStringTag];if(n!==r)throw TypeError(q(167,{aTag:n,bTag:r}));let i=e.constructor.compare;if(typeof i!=`function`)throw TypeError(q(168,{aTag:n}));return i(e,t)}function _c(e,t){return Js(e)&&Js(t)?gc(e,t):e<t?-1:+(e>t)}function vc(e,t){return e===t?!0:lc(e)&&lc(t)?uc(e,t):!1}var yc=Symbol(`tanstack_db_parent_context`),bc=Symbol(`tanstack_db_parent_projection_not_found`);function xc(e,t){let n=hc(e);return typeof n==`object`&&n||typeof n==`function`||typeof n==`symbol`?t(n):n}function Sc(e,t){if(typeof e==`object`&&e||typeof e==`function`||typeof e==`symbol`)return t(e);if(typeof e==`number`){if(Object.is(e,-0))return[`number`,`-0`];if(Number.isNaN(e))return[`number`,`NaN`]}return e}function Cc(){let e=Zs(),t=t=>xc(t,e);return{equality:t,exact:t=>Sc(t,e),serializeEquality:e=>Er(t(e))}}function wc(e,t,n={}){return{[yc]:!0,value:e,projectedBindings:n,identity:t}}function Tc(e){return Dc(e)?e.projectedBindings:void 0}function Ec(e,t){let n=Tc(e);return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:bc}function Dc(e){return typeof e==`object`&&!!e&&yc in e}function Oc(e){if(Dc(e))return e.value;if(typeof e==`object`&&e)return e}function kc(e){return Dc(e)?e.identity:e}function Ac(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function jc(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var Mc=Symbol(`tanstack_db_routed_scalar_value`),Nc=Symbol(`tanstack_db_callback_input`),Pc=Symbol(`tanstack_db_callback_selected`),Fc=Symbol(`tanstack_db_route_metadata`),Ic=Symbol(`includesPublicKey`),Lc=Symbol(`includesRouting`),Rc=new Set([Fc,Ic,Nc,Pc]),zc=new Set([...Rc,Lc]);function Bc(e,t,n){return Object.assign(e,{[Fc]:{correlationKey:t,parentContext:n}})}function Vc(e){if(typeof e==`object`&&e&&Fc in e)return e[Fc]}function Hc(e,t){return Vc(e)??(typeof e==`object`&&e?Vc(e[t]):void 0)}function Uc(e){let t={...e};return delete t[Fc],t}function Wc(e,t,n,r){return t===void 0&&n===void 0&&r===void 0?e:Object.assign(Ac(e)?{...e}:{[Mc]:e},{[Fc]:{correlationKey:t,parentContext:n},[Ic]:r})}function Gc(e){if(typeof e!=`object`||!e||!(Mc in e))return;let t=e;return{value:t[Mc],...t[Fc],publicKey:t[Ic]}}function Kc(e,t,n){let r=Gc(t),i=r??Vc(t),a={...Oc(i?.parentContext),[e]:r?r.value:i?Uc(t):t};return i&&Bc(a,i.correlationKey,i.parentContext),r&&Object.assign(a,{[Ic]:r.publicKey}),n!==void 0&&n!==t&&Object.assign(a,{[Nc]:{[e]:n}}),a}function qc(e){let t=e[Nc];if(Array.isArray(t)){let n={...t[0]};return`$selected`in e&&(n.$selected=e.$selected),n}return t&&typeof t==`object`?{...e,...t}:e}function Jc(e){return Xc(e,e=>e,Rc)}function Yc(e){return Xc(e,e=>e,zc)}function Xc(e,t,n){let r=t(e);if(!Object.is(r,e))return r;if(!Zc(e))return e;let i=new Map,a=[],o=e=>{e.dirty||(e.dirty=!0,a.push(e))},s=e=>{let r=i.get(e);if(r)return r;let a={value:e,properties:Object.getOwnPropertyDescriptors(e),parents:[]};i.set(e,a);for(let e of Reflect.ownKeys(a.properties)){if(n.has(e)){delete a.properties[e],o(a);continue}let r=a.properties[e];if(!r.enumerable||!(`value`in r))continue;let i=r.value;r.value=t(i),Object.is(r.value,i)?Zc(i)&&(r.child=s(i),r.child.parents.push(a)):o(a)}return a},c=s(e);for(let e of a)for(let t of e.parents)o(t);let l=e=>{if(!e.dirty)return e.value;if(e.copy)return e.copy;let t=Array.isArray(e.value)?[]:Object.create(Object.getPrototypeOf(e.value));e.copy=t;for(let t of Reflect.ownKeys(e.properties)){let n=e.properties[t];n.child&&(n.value=l(n.child))}return Object.defineProperties(t,e.properties)};return l(c)}function Zc(e){return Array.isArray(e)||Ac(e)}function Qc(e){return e==null}function $c(e){return lc(e)?e:hc(e)}function el(e,t){return rc(e)||rc(t)?rc(e)&&rc(t):vc(e,t)}function tl(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function nl(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function rl(e){return e===!0}function il(e,t=!1){return ol(e,t)}function al(e){return ol(e,!0)}function ol(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?cl(e):sl(e);case`func`:return ll(e,t);default:throw new os(e.type)}}function sl(e){let t=tr(e),[n,...r]=e.path,i=t??n,a=t===void 0?r:nr(e);if(!i)throw new ss;let o=e.bindingId?JSON.stringify([e.bindingId,a]):void 0,s=o?e=>Ec(Hc(e,i)?.parentContext,o):void 0;if(i===`$selected`){if(a.length===0)return e=>e.$selected;if(a.length===1){let e=a[0];return t=>t.$selected?.[e]}return e=>{let t=e.$selected;if(t===void 0)return;let n=t;for(let e of a){if(n==null)return n;n=n[e]}return n}}let c=i;if(a.length===0)return e=>{let t=s?.(e);return s&&t!==bc?t:e[c]};if(a.length===1){let e=a[0];return t=>{let n=s?.(t);return s&&n!==bc?n:t[c]?.[e]}}return e=>{let t=s?.(e);if(s&&t!==bc)return t;let n=e[c];if(n===void 0)return;let r=n;for(let e of a){if(r==null)return r;r=r[e]}return r}}function cl(e){let t=nr(e);return e=>{let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}}function ll(e,t){let n=e.args.map(e=>ol(e,t));switch(e.name){case`array`:return e=>n.map(t=>t(e));case`eq`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n),a=typeof r;if(a===typeof i&&(a===`string`||a===`boolean`))return r===i;let o=$c(r),s=$c(i);return Qc(o)||Qc(s)?null:el(o,s)}}case`gt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return Qc(r)||Qc(i)?null:rc(r)||rc(i)?rc(r)&&!rc(i):_c(r,i)>0}}case`gte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return Qc(r)||Qc(i)?null:rc(r)||rc(i)?rc(r):_c(r,i)>=0}}case`lt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return Qc(r)||Qc(i)?null:rc(r)||rc(i)?rc(i)&&!rc(r):_c(r,i)<0}}case`lte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return Qc(r)||Qc(i)?null:rc(r)||rc(i)?rc(i):_c(r,i)<=0}}case`and`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!1)return!1;Qc(n)&&(t=!0)}return!t||null};case`or`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!0)return!0;Qc(n)&&(t=!0)}return t?null:!1};case`not`:{let e=n[0];return t=>{let n=e(t);return Qc(n)?null:!n}}case`in`:{let t=n[0],r=n[1],i=e.args[1];if(i.type===`val`&&Array.isArray(i.value)){let e=i.value.filter(e=>!Qc(e)),n=e.filter(lc),r=new Set(e.filter(e=>!lc(e)).map(hc));return e=>{let i=t(e);return Qc(i)?null:lc(i)?n.some(e=>vc(e,i)):r.has(hc(i))}}return e=>{let n=$c(t(e)),i=r(e);return Qc(n)?null:Array.isArray(i)?i.some(e=>el($c(e),n)):!1}}case`like`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return Qc(r)||Qc(i)?null:dl(r,i,!1)}}case`ilike`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return Qc(r)||Qc(i)?null:dl(r,i,!0)}}case`upper`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toUpperCase():n}}case`lower`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toLowerCase():n}}case`length`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`||Array.isArray(n)?n.length:0}}case`concat`:return e=>n.map(t=>{let n=t(e);try{return String(n??``)}catch{try{return JSON.stringify(n)||``}catch{return`[object]`}}}).join(``);case`coalesce`:return e=>{for(let t of n){let n=t(e);if(n!=null)return n}return null};case`caseWhen`:{let e=n.length%2==1,t=Math.floor(n.length/2);if(n.length<2)throw Error(q(127));return r=>{for(let e=0;e<t;e++){let t=n[e*2];if(ul(t(r))){let t=n[e*2+1];return t(r)}}return e?n[n.length-1](r):null}}case`add`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)+(i??0)}}case`subtract`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)-(i??0)}}case`multiply`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)*(i??0)}}case`divide`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n)??0;return i===0?null:(r??0)/i}}case`date`:{let e=n[0];return t=>{let n=tl(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=tl(e(t));return n?n.toISOString():null}}case`strftime`:{let e=n[0],t=n[1];return n=>{let r=e(n);if(typeof r!=`string`)return null;let i=tl(t(n));return i?nl(r,i):null}}case`isUndefined`:{let e=n[0];return t=>e(t)===void 0}case`isNull`:{let e=n[0];return t=>e(t)===null}default:throw new cs(e.name)}}function ul(e){return e==null||e===!1?!1:e===!0?!0:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:!!e}function dl(e,t,n){if(typeof e!=`string`||typeof t!=`string`)return!1;let r=n?e.toLowerCase():e,i=n?t.toLowerCase():t,a=0,o=0,s=-1,c=0;for(;a<r.length;){let e=o<i.length?i[o]:void 0;if(e===`%`)s=o,c=a,o++;else if(e===`_`||e===r[a])a++,o++;else if(s!==-1)c++,a=c,o=s+1;else return!1}for(;i[o]===`%`;)o++;return o===i.length}var fl=class{constructor(e,t){this.gu=t,this.bl=e}lookup(e,t){let n=e===`gt`?`lt`:e===`gte`?`lte`:e===`lt`?`gt`:e===`lte`?`gte`:e;return this.bl.lookup(n,t)}rangeQuery(e={}){return this.bl.rangeQueryReversed(e)}take(e,t,n){return this.gu===void 0?this.bl.takeReversed(e,t,n):this.read(e,n,t??null)}takeFromStart(e,t){return this.gu===void 0?this.bl.takeReversedFromEnd(e,t):this.read(e,t)}read(e,t,n){let r=new Set([...this.bl.equalityLookup(null),...this.bl.equalityLookup(void 0)]),i=e=>t?.(e)??!0,a=e=>!r.has(e)&&i(e),o=e=>e<=0?[]:n==null?this.bl.takeReversedFromEnd(e,a):this.bl.takeReversed(e,n,a),s=e=>e<=0?[]:[...r].sort(Tr).filter(i).slice(0,e);if(n===null)return this.gu?o(e):[];if(this.gu&&n===void 0){let t=s(e);return[...t,...o(e-t.length)]}let c=o(e);return this.gu?c:[...c,...s(e-c.length)]}supports(e){return this.bl.supports(e)}get supportsRangeOptimization(){return this.bl.supportsRangeOptimization}get supportsOrderOptimization(){return this.bl.supportsOrderOptimization===!0}canOptimizeRangeFor(e){return this.bl.canOptimizeRangeFor?.(e)??!0}get keyCount(){return this.bl.keyCount}};function pl(e,t,n,r,i){let a=e,o=a.$hasPendingWrites??r();return{...e,$hasPendingWrites:o,$origin:a.$origin??i(),$key:a.$key??t,$collectionId:a.$collectionId??n}}var ml=[`$hasPendingWrites`,`$origin`,`$key`,`$collectionId`];function hl(e){return ml.includes(e)}function gl(e){return e.some(e=>hl(e))}function _l(e){return e.supports(`gt`)&&e.supportsRangeOptimization}function vl(e){return _l(e)&&!!e.supportsOrderOptimization}function yl(e,t,n,r){if(gl(t))return;let i=n??{...Ys,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(i)){let e=n.matchesDirection(i.direction)?n:new fl(n,i.nulls===`first`);if(!r||r(e))return e}}function bl(e){if(e.length===0)return new Set;if(e.length===1)return new Set(e[0]);let t=new Set(e[0]);for(let n=1;n<e.length;n++){let r=new Set;for(let i of t)e[n].has(i)&&r.add(i);t=r}return t}function xl(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function Sl(e){return e!=null}function Cl(e){return{...Ys,...e.compareOptions}.stringSort!==`lexical`}function wl(e,t){switch(typeof e){case`number`:case`bigint`:case`boolean`:return!1;case`string`:return Cl(t);case`symbol`:return!0;case`object`:return e!==null&&!(e instanceof Date);default:return!1}}function Tl(e,t,n){return!wl(e,n)&&t.supportsRangeOptimization&&(t.canOptimizeRangeFor?.(e)??!0)}function El(e,t){return Dl(e,t)}function Dl(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return kl(e,t);case`and`:return Al(e,t);case`or`:return jl(e,t);case`in`:return Ml(e,t)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function Ol(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};let n=new Map;for(let[t,r]of e.args.entries())if(r.type===`func`&&[`gt`,`gte`,`lt`,`lte`].includes(r.name)){let e=r;if(e.args.length===2){let r=e.args[0],i=e.args[1],a=null,o=null,s=e.name;if(r.type===`ref`&&i.type===`val`)a=r,o=i;else if(r.type===`val`&&i.type===`ref`)switch(a=i,o=r,s){case`gt`:s=`lt`;break;case`gte`:s=`lte`;break;case`lt`:s=`gt`;break;case`lte`:s=`gte`}if(a&&o){let e=a.path,r=JSON.stringify(e),i=o.value;n.has(r)||n.set(r,[]),n.get(r).push({operation:s,value:i,argIndex:t})}}}for(let[e,r]of n)if(r.length>=2){let n=yl(t,JSON.parse(e));if(n&&r.some(e=>!Tl(e.value,n,t)))continue;if(n&&n.supports(`gt`)&&n.supports(`lt`)){let e=sc({...Ys,...t.compareOptions,direction:`asc`}),i,a,o=!1,s=!1,c=!0,l=!0,u=!1;for(let{operation:t,value:n}of r)if(!Sl(n))u=!0;else switch(t){case`gt`:case`gte`:{let r=o?e(n,i):1;r>0?(i=n,o=!0,c=t===`gte`):r===0&&t===`gt`&&(c=!1);break}case`lt`:case`lte`:{let r=s?e(n,a):-1;r<0?(a=n,s=!0,l=t===`lte`):r===0&&t===`lt`&&(l=!1);break}}let d={};return o&&(d.from=i,d.fromInclusive=c),s&&(d.to=a,d.toInclusive=l),{canOptimize:!0,matchingKeys:n.rangeQuery(d),isExact:o&&!u,coveredArgIndices:new Set(r.map(e=>e.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}function kl(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=e.args[0],r=e.args[1],i=null,a=null,o=e.name;if(n.type===`ref`&&r.type===`val`)i=n,a=r;else if(n.type===`val`&&r.type===`ref`)switch(i=r,a=n,o){case`gt`:o=`lt`;break;case`gte`:o=`lte`;break;case`lt`:o=`gt`;break;case`lte`:o=`gte`}if(i&&a){let e=i.path,n=yl(t,e);if(n){let e=a.value,r=o;return!n.supports(r)||(o===`gt`||o===`gte`||o===`lt`||o===`lte`)&&!Tl(e,n,t)?{canOptimize:!1,matchingKeys:new Set,isExact:!1}:{canOptimize:!0,matchingKeys:n.lookup(r,e),isExact:o===`lt`||o===`lte`?!1:Sl(e)}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function Al(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=Ol(e,t),r=n.canOptimize?n.coveredArgIndices:new Set,i=[];n.canOptimize&&i.push(n);let a=!n.canOptimize||n.isExact;for(let[n,o]of e.args.entries()){if(r.has(n))continue;let e=Dl(o,t);e.canOptimize?(i.push(e),e.isExact||(a=!1)):a=!1}return i.length>0?{canOptimize:!0,matchingKeys:bl(i.map(e=>e.matchingKeys)),isExact:a}:{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function jl(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=[];for(let r of e.args){let e=Dl(r,t);if(!e.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};n.push(e)}return{canOptimize:!0,matchingKeys:xl(n.map(e=>e.matchingKeys)),isExact:n.every(e=>e.isExact)}}function Ml(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=e.args[0],r=e.args[1];if(n.type===`ref`&&r.type===`val`&&Array.isArray(r.value)){let e=n.path,i=r.value,a=yl(t,e),o=i.every(e=>Sl(e));if(a){if(a.supports(`in`))return{canOptimize:!0,matchingKeys:a.lookup(`in`,i),isExact:o};if(a.supports(`eq`)){let e=new Set;for(let t of i){let n=a.lookup(`eq`,t);for(let t of n)e.add(t)}return{canOptimize:!0,matchingKeys:e,isExact:o}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}var Nl=new WeakMap;function Pl(e,t){Nl.set(e,t)}function Fl(e){return typeof e==`object`&&e?Nl.get(e):void 0}var Il=0;function Ll(){let e=new Map;function t(n){let r=JSON.stringify(n);if(e.has(r))return e.get(r);let i=new Proxy({},{get(e,r,i){if(r===`__refProxy`)return!0;if(r===`__path`)return n;if(r!==`__sourceAlias`&&r!==`__bindingId`&&r!==`__type`)return r===Hn?!0:typeof r==`symbol`?Reflect.get(e,r,i):t([...n,String(r)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`||Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return e.set(r,i),i}return t([])}function Rl(e,t){let n=new Map;function r(e){let n,i;return new Proxy({},{get(a,o,s){if(o===`__refProxy`)return!0;if(o===`__path`)return e;if(o===`__sourceAlias`)return e[0];if(o===`__bindingId`)return t?.get(e[0]??``);if(o===`__type`)return;if(o===Hn)return e;if(typeof o==`symbol`)return Reflect.get(a,o,s);if(o===i?.key)return i.ref;if(Object.prototype.hasOwnProperty.call(a,o))return Reflect.get(a,o,s);n??=new Map;let c=n.get(o);return c===void 0&&(c=r([...e,o]),n.set(o,c)),c},has(e,t){return t===i?.key||t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`||Reflect.has(e,t)},ownKeys(n){let r=++Il,a=`__SPREAD_SENTINEL__${e.join(`.`)}__${r}`;return i={key:a,ref:new J(e,e[0],t?.get(e[0]??``))},[...Reflect.ownKeys(n),a]},getOwnPropertyDescriptor(e,t){return t===i?.key?{enumerable:!0,configurable:!0,value:i.ref}:t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}})}return new Proxy({},{get(t,i,a){if(i===`__refProxy`)return!0;if(i===`__path`)return[];if(i===`__sourceAlias`||i===`__bindingId`||i===`__type`)return;if(i===Hn)return!0;if(typeof i==`symbol`)return Reflect.get(t,i,a);let o=String(i);if(e.includes(o)||e.includes(`*`)){let e=n.get(o);return e===void 0&&(e=r([o]),n.set(o,e)),e}},has(t,n){return n===`__refProxy`||n===`__path`||n===`__sourceAlias`||n===`__bindingId`||n===`__type`||typeof n==`string`&&e.includes(n)?!0:Reflect.has(t,n)},ownKeys(t){return[...e,`__refProxy`,`__path`,`__sourceAlias`,`__bindingId`,`__type`]},getOwnPropertyDescriptor(t,n){if(n===`__refProxy`||n===`__path`||n===`__sourceAlias`||n===`__bindingId`||n===`__type`)return{enumerable:!1,configurable:!0};if(typeof n==`string`&&e.includes(n))return{enumerable:!0,configurable:!0}}})}function zl(e,t){let n=Rl(e,t),r=new Map;function i(e){let t=JSON.stringify(e);if(r.has(t))return r.get(t);let n=new Proxy({},{get(t,n,r){if(n===`__refProxy`)return!0;if(n===`__path`)return[`$selected`,...e];if(n===`__sourceAlias`)return`$selected`;if(n!==`__bindingId`&&n!==`__type`)return n===Hn?!0:typeof n==`symbol`?Reflect.get(t,n,r):i([...e,String(n)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`||Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return r.set(t,n),n}let a=i([]);return new Proxy(n,{get(e,t,n){return t===`$selected`?a:Reflect.get(e,t,n)},has(e,t){return t===`$selected`||Reflect.has(e,t)},ownKeys(e){return[...Reflect.ownKeys(e),`$selected`]},getOwnPropertyDescriptor(e,t){return t===`$selected`?{enumerable:!0,configurable:!0,value:a}:Reflect.getOwnPropertyDescriptor(e,t)}})}function X(e){if(e===null||typeof e!=`object`&&typeof e!=`function`)return new rr(e);let t=Un(e);if(t!==void 0)return Array.isArray(t)?new J(t,t[0],e.__bindingId):new J(e.__path,e.__sourceAlias,e.__bindingId);let n=Fl(e);if(n)throw Error(q(126,{name:n}));return lr(e)?e:new rr(e)}function Bl(e,t){return new ir(`eq`,[X(e),X(t)])}function Vl(e,t){return new ir(`gt`,[X(e),X(t)])}function Hl(e,t){return new ir(`gte`,[X(e),X(t)])}function Ul(e,t){return new ir(`lt`,[X(e),X(t)])}function Wl(e,t,...n){return new ir(`and`,[e,t,...n].map(e=>X(e)))}function Gl(e,t,...n){return new ir(`or`,[e,t,...n].map(e=>X(e)))}function Kl(e){return new ir(`not`,[X(e)])}function ql(e){return new ir(`isUndefined`,[X(e)])}function Jl(e){return new ir(`isNull`,[X(e)])}function Yl(e,t){return new ir(`in`,[X(e),X(t)])}var Xl=[`eq`,`gt`,`gte`,`lt`,`lte`,`in`],Zl=class{constructor(e,t){this.query=e,this.runtime=t,this.__brand=`ToArrayWrapper`,Pl(this,`toArray()`)}},Ql=class{constructor(e,t){this.query=e,this.runtime=t,this.__brand=`ConcatToArrayWrapper`,Pl(this,`concat(toArray())`)}},$l=class{constructor(e){this.args=e,this.__brand=`CaseWhenWrapper`,Pl(this,`caseWhen()`)}},eu=class{constructor(e,t){this.query=e,this.runtime=t,this.__brand=`MaterializeWrapper`,Pl(this,`materialize()`)}},tu=class{constructor(e,t){this.query=e,this.runtime=t,this.__brand=`IncludeWrapper`,Pl(this,`include()`)}};function nu(){return zn()&&!1}function ru(e){return e.config.autoIndex===`eager`}function iu(e,t,n,r,i){if(gl(t))return;let a=ru(n);if(!a&&!nu())return;let o=r??{...Ys,...n.compareOptions};if(!yl(n,t,o,i)){if(!a)n.id,n.size;else try{n.createIndex(e=>{let n=e;for(let e of t)n=n[e];return n},{name:`auto:${t.join(`.`)}`,options:{compareOptions:o}})}catch(e){console.warn(Vn(215,{id:n.id,value:t.join(`.`)}),e)}}}function au(e,t){if(!ru(t)&&!nu())return;let n=ou(e);for(let{fieldName:e,fieldPath:r}of n)iu(e,r,t)}function ou(e){let t=[];function n(e){if(e.type!==`func`)return;let r=e;if(r.name===`and`){for(let e of r.args)n(e);return}if(!Xl.includes(r.name)||r.args.length<1||r.args[0].type!==`ref`)return;let i=r.args[0].path;if(i.length===0)return;let a=i.join(`_`);t.push({fieldName:a,fieldPath:i})}return n(e),t}function su(e){let t=hc(e),n=typeof t;return n===`string`||n===`number`||n===`boolean`?`${n}:${String(t)}`:void 0}function cu(e,t){try{let n=e;for(let e of t)n=n?.[e];return n}catch{return}}function lu(e,t){if(e.type!==`func`||e.name!==`eq`)return;let n=e.args;if(n.length!==2)return;let r=n[0],i=n[1],a=r.type===`ref`?r:i,o=r.type===`val`?r:i;if(a.type!==`ref`||o.type!==`val`)return;let s=t(a);if(!s?.length||hl(s[0]))return;let c=su(o.value);return c===void 0?void 0:{path:s,literalKey:c}}function uu(e){switch(e.type){case`ref`:{let t=tr(e)??e.path[0];return new Set(t?[t]:[])}case`func`:{let t=new Set;for(let n of e.args)for(let e of uu(n))t.add(e);return t}default:return new Set}}function du(e,t){let n=e.type;if(n===`val`)return new rr(e.value);if(n===`ref`){let n=e.path,r=tr(e);if(Array.isArray(n)){if(r===t)return new J(nr(e));if(r!==void 0)return new J(n,r);if(n[0]===t&&n.length>1)return new J(n.slice(1));if(n.length===1&&n[0]!==void 0)return new J([n[0]])}return new J(Array.isArray(n)?n:[String(n)])}{let n=[];for(let r of e.args){let e=du(r,t);n.push(e)}return new ir(e.name,n)}}function fu(e,t){return e.map(e=>{let n=du(e.expression,t);return{...e,expression:n}})}function pu(e,t,n,r,i,a,o,s,c,l,u){let d=n.map(e=>({compiledExpression:il(i?i.replaceAggregatesByRefs(e.expression,r,`$selected`):e.expression),compare:sc(mu(e,a))})),f=e=>n.length>1?d.map(t=>t.compiledExpression(e)):n.length===1?d[0].compiledExpression(e):null,p=d.length<=1?d[0]?.compare??cc:(e,t)=>{let n=e,r=t;for(let e=0;e<d.length;e++){let t=d[e].compare(n[e],r[e]);if(t!==0)return t}return n.length-r.length},m,h;if(c!==void 0&&n.length>0&&!u&&e.from.type!==`unionFrom`&&e.from.type!==`unionAll`){let t,r,i=e.from.alias,s,u=n[0],d=u.expression,f=d.type===`ref`?yr(e,d,a):void 0;if(d.type===`ref`&&f){r=f.collection,s=f.sourceId;let n=f.path[0],o=mu(u,a);n&&iu(n,f.path,r,o,_l),t=yl(r,f.path,o,vl),f.path,i=d.path.length>1?String(d.path[0]):e.from.alias,s??=fr(e).find(e=>e.alias===i&&e.collection===r)?.sourceId}if(s&&f){let r=hu(n,a.compareOptions),u=n.every(({expression:t})=>t.type===`ref`&&yr(e,t,a)?.sourceId===s),d=il(new J(f.path),!0),p=sc(r[0].compareOptions),g=(e,t)=>p(e&&d(e),t&&d(t)),_=e.where?.some(e=>[...uu(pr(e))].some(e=>e!==i))??!1,v=_&&e.join?.length===1&&e.join[0].type===`left`&&e.join[0].from.type===`collectionRef`?e.join[0].from.sourceId:void 0,y={sourceId:s,alias:i,offset:l??0,limit:c,comparator:g,valueExtractorForRawRow:d,index:t,orderBy:r,joinedFilterSourceIds:v?[v]:void 0,sourceHoldsAllRows:f.collection.config.syncMode!==`on-demand`,requiresFullSource:r.some(({compareOptions:e})=>e.stringSort===`custom`)||!u||e.from.type!==`collectionRef`||e.from.sourceId!==s||(e.join?.some(({type:e})=>e!==`left`)??!1)||(e.where?.some(hr)??!1)||_&&v===void 0||(e.fnWhere?.length??0)>0||e.groupBy!==void 0||e.having!==void 0||e.fnHaving!==void 0||e.distinct===!0};h=y;let b=o[s];o[s]=b?{...y,joinedFilterSourceIds:[...new Set([...b.joinedFilterSourceIds??[],...y.joinedFilterSourceIds??[]])],get offset(){return Math.min(b.offset,y.offset)},get limit(){return Math.max(b.offset+b.limit,y.offset+y.limit)-this.offset},requiresFullSource:!Bs(b.orderBy,y.orderBy)||b.requiresFullSource||y.requiresFullSource,dataNeeded:e=>Math.max(b.dataNeeded?.(e)??0,y.dataNeeded?.(e)??0)}:y;let x=v!==void 0&&!y.sourceHoldsAllRows;(t||x)&&(m=e=>{y.dataNeeded=t=>{let n=e(t&&(e=>g(e[i],t)<=0));return Math.max(0,y.limit-n)}})}}let g={limit:c,offset:l,comparator:p,setSizeCallback:m,setWindowFn:e=>{s(t=>{e(t),h&&(h.offset=t.offset??h.offset,h.limit=t.limit??h.limit)})}};return t.pipe(u?La(f,{...g,groupKeyFn:u}):Ra(f,g))}function mu(e,t){return gu(e,t.compareOptions)}function hu(e,t){return e.map(e=>({expression:e.expression,compareOptions:gu(e,t)}))}function gu(e,t){return e.compareOptions.stringSort===void 0?{...t,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function _u(e){let t=e.type===`func`&&e.name===`and`?e.args:[e];for(let e of t){let t=lu(e,nr);if(t)return e=>su(cu(e,t.path))===t.literalKey}}function vu(e,t={},n){let r=r=>{let i=[],a=r&&n&&t.where?_u(t.where):void 0,o=a?n(a):e.entries();for(let[e,t]of o)(r?.(t)??!0)&&i.push({type:`insert`,key:e,value:t});return i};if(t.limit!==void 0&&!t.orderBy)throw Error(q(94));if(t.orderBy){let n=t.where?yu(t.where):void 0,r=xu(e,t.orderBy,t.limit,n,t.optimizedOnly);if(r===void 0)return;let i=[];for(let t of r){let n=e.get(t);n!==void 0&&i.push({type:`insert`,key:t,value:n})}return i}if(!t.where)return r();try{let n=t.where,i=El(n,e);if(i.canOptimize){let t=i.isExact?void 0:yu(n),r=[];for(let n of i.matchingKeys){let i=e.get(n);i!==void 0&&(t?.(i)??!0)&&r.push({type:`insert`,key:n,value:i})}return r}return t.optimizedOnly?void 0:r(yu(n))}catch(n){console.warn(Vn(213,{id:e.id}),n);let i=yu(t.where);return t.optimizedOnly?void 0:r(i)}}function yu(e){let t=al(e);return e=>{try{return rl(t(e))}catch{return!1}}}function bu(e,t){let n=yu(t.whereExpression);return t=>{let r=[];for(let e of t)if(e.type===`insert`)n(e.value)&&r.push(e);else if(e.type===`update`){let t=n(e.value),i=e.previousValue?n(e.previousValue):!1;t&&i?r.push(e):t&&!i?r.push({...e,type:`insert`}):!t&&i&&r.push({...e,type:`delete`,value:e.previousValue})}else n(e.value)&&r.push(e);return r.length>0||t.length===0?(e(r),!0):!1}}function xu(e,t,n,r,i){if(t.length===1){let i=t[0],a=i.expression;if(a.type===`ref`){let t=a.path,o=mu(i,e);iu(t[0],t,e,o,_l);let s=yl(e,t,o,vl);if(s)return s.takeFromStart(n??s.keyCount,t=>{let n=e.get(t);return n===void 0?!1:r?.(n)??!0})}}if(i)return;let a=[];for(let[t,n]of e.entries())(r?.(n)??!0)&&a.push({key:t,value:n});let o=t.map(t=>({expression:t.expression,compare:sc(mu(t,e))}));a.sort((e,t)=>{for(let n of o){let r=Su(e.value,n.expression),i=Su(t.value,n.expression),a=n.compare(r,i);if(a!==0)return a}return 0});let s=a.map(e=>e.key);return n===void 0?s:s.slice(0,n)}function Su(e,t){if(t.type===`ref`){let n=t,r=e;for(let e of n.path)r=r?.[e];return r}return t.type===`val`?t.value:al(t)(e)}var Cu=class{constructor(e){this.bT=new Set,this.map=new Map,this.am=[],this.comparator=e}indexOf(e,t,n=this.am){let r=0,i=n.length;if(!this.comparator){for(;r<i;){let t=Math.floor((r+i)/2),a=n[t],o=Tr(e,a);if(o<0)i=t;else if(o>0)r=t+1;else return t}return r}for(;r<i;){let a=Math.floor((r+i)/2),o=n[a],s=this.map.get(o),c=this.comparator(t,s);if(c<0)i=a;else if(c>0)r=a+1;else{let t=Tr(e,o);if(t<0)i=a;else if(t>0)r=a+1;else return a}}return r}restoreOrder(){if(this.bT.size===0)return;let e=this.am,t=e.filter(e=>!this.bT.has(e)),n=[...this.bT].filter(e=>this.map.has(e)).sort((e,t)=>(this.comparator?.(this.map.get(e),this.map.get(t))??0)||Tr(e,t));e.length=0;let r=0;for(let i of n){let n=this.indexOf(i,this.map.get(i),t);for(;r<n;)e.push(t[r++]);e.push(i)}for(;r<t.length;)e.push(t[r++]);this.bT.clear()}cz(e){let t=t=>t===e||t!==t&&e!==e,n=this.indexOf(e,this.map.get(e));t(this.am[n])||(n=this.am.findIndex(t)),this.am.splice(n,1)}set(e,t,n=!1){return!this.comparator&&this.map.has(e)?(this.map.set(e,t),this):n?(this.map.set(e,t),this.bT.add(e),this):(this.restoreOrder(),this.map.has(e)&&this.cz(e),this.am.splice(this.indexOf(e,t),0,e),this.map.set(e,t),this)}get(e){return this.map.get(e)}delete(e,t=!1){if(t){let t=this.map.delete(e);return t&&this.bT.add(e),t}return this.restoreOrder(),this.map.has(e)&&this.cz(e),this.map.delete(e)}has(e){return this.map.has(e)}clear(){this.map.clear(),this.am=[],this.bT.clear()}get size(){return this.map.size}*[Symbol.iterator](){for(let e of this.keys())yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.restoreOrder(),this.am[Symbol.iterator]()}*values(){for(let e of this.keys())yield this.map.get(e)}};function wu(e,t){let n=e.preserveHydrationSeedKeys;return e.truncate===!0&&(!n||e.sourceTruncate===!0&&!n.has(t))}function Tu(e){return e.metadata!==void 0&&e.type!==`delete`?{type:`set`,value:e.metadata}:e.type===`update`?void 0:{type:`delete`}}var Eu=class{constructor(e){this.pendingSyncedTransactions=[],this.a7={states:new Map,truncated:!1,sourceKeys:new Set},this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.hydrationSeedKeys=new Set,this.hydratedKeys=new Set,this.hasAppliedAdapterTruncate=!1,this.adapterTruncateKeptKeys=new Set,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.bf=()=>!1,this.getStagedSyncTransactions=()=>[],this.heldOptimisticRows=new Map,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.dE=new Map,this.size=0,this.preSyncVisibleState=new Map,this.preSyncVirtualState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.bU=!1,this.syncRunGeneration=0,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{if(this.bU)return;this.bU=!0;let e=!1,t;try{let n;do n=this.dG(),n.failure&&!e&&(e=!0,t=n.failure.error);while(n.processed)}finally{this.bU=!1}if(e)throw t},this.config=e,this.transactions=new Cu((e,t)=>e.compareCreatedAt(t)),this.syncedData=new Cu(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this.a3=e.events}ak(e,t=this){let n=!this.isLocalOnly&&(t.optimisticUpserts.has(e)||t.optimisticDeletes.has(e));return{$hasPendingWrites:n,$origin:this.isLocalOnly||n?`local`:t.rowOrigins.get(e)??`remote`,$key:e,$collectionId:this.collection.id}}et(e){let t=new Map;for(let n of e){let e=this.rowOrigins.get(n);e!==void 0&&t.set(n,e)}return t}aW(e,t){let n=e,r=n.$hasPendingWrites??t.$hasPendingWrites,i=n.$origin??t.$origin,a=n.$key??t.$key,o=n.$collectionId??t.$collectionId,s=this.dE.get(a);if(s&&s.row===e&&s.hasPendingWrites===r&&s.origin===i&&s.collectionId===o)return s.enriched;let c={...e,$hasPendingWrites:r,$origin:i,$key:a,$collectionId:o};return this.dE.set(a,{row:e,hasPendingWrites:r,origin:i,collectionId:o,enriched:c}),c}dh(){this.dE.clear(),this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.aW(e,this.ak(t))}*entriesPassing(e){let t=this.optimisticUpserts.size===0&&this.optimisticDeletes.size===0?this.syncedData:this.entries();for(let[n,r]of t)e(r)&&(yield[n,this.enrichWithVirtualProps(r,n)])}enrichChangeMessage(e){let{__virtualProps:t}=e,n=e.previousValue?this.aW(e.previousValue,t?.previousValue??this.ak(e.key)):void 0,r=this.aW(e.value,t?.value??this.ak(e.key));return e.type===`delete`&&this.dE.delete(e.key),{key:e.key,type:e.type,value:r,previousValue:n,metadata:e.metadata}}getWithVirtualProps(e){let t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e,t=this.optimisticUpserts,n=this.optimisticDeletes){if(!n.has(e))return t.get(e)??this.syncedData.get(e)}has(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;return t.has(e)?!1:n.has(e)||r.has(e)}*keys(){let{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(let n of e.keys())t.has(n)||(yield n);for(let r of n.keys())!e.has(r)&&!t.has(r)&&(yield r)}*values(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}[Symbol.iterator](){return this.entries()}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}setDeferredSyncKeys(e,t=()=>[]){this.bf=e,this.getStagedSyncTransactions=t}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;let t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),r=this.rowOrigins,i=new Set;for(let e of this.pendingSyncedTransactions)if(e.committed)for(let t of e.operations)i.add(t.key);let a=e=>i.has(e)||this.bf(e);for(let e of this.transactions.values())if(e.state===`completed`)for(let t of e.mutations){if(t.collection!==this.collection||!a(t.key)||(this.pendingLocalOrigins.add(t.key),!t.optimistic))continue;let n=this.heldOptimisticRows.get(t.key);n&&n.owner.compareCreatedAt(e)>0||this.heldOptimisticRows.set(t.key,{owner:e,row:t.type===`delete`?void 0:t.modified})}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear(),this.c7(a),this.size=this.e1();let o=[];this.ey(t,n,r,o);let s=e?o:o.filter(e=>!this.recentlySyncedKeys.has(e.key));s.length>0&&this.indexes.updateIndexes(s),this.changes.emitEvents(s,e)}trackTransaction(e){let t=this.transactions.get(e.id);if(t===e)return!1;if(t&&t.state!==`completed`&&t.state!==`failed`)throw new Mo(e.id);return this.transactions.set(e.id,e),e.collections.add(this.collection),!0}c7(e){if(e){for(let t of this.heldOptimisticRows.keys())e(t)||this.heldOptimisticRows.delete(t);for(let t of this.pendingLocalOrigins)e(t)||this.pendingLocalOrigins.delete(t)}for(let[e,{row:t}]of this.heldOptimisticRows)t===void 0?this.optimisticDeletes.add(e):this.optimisticUpserts.set(e,t);this.gl()}gl(){for(let[e,t]of this.transactions)if(t.state===`completed`||t.state===`failed`)this.transactions.delete(e,!0);else if(!this.lifecycle.hasStartedCleanup())for(let e of t.mutations)e.collection===this.collection&&(this.pendingLocalChanges.add(e.key),e.optimistic&&(e.type===`delete`?(this.optimisticUpserts.delete(e.key),this.optimisticDeletes.add(e.key)):(this.optimisticUpserts.set(e.key,e.modified),this.optimisticDeletes.delete(e.key))))}e1(){let e=this.syncedData.size;for(let t of this.optimisticDeletes)this.syncedData.has(t)&&!this.optimisticUpserts.has(t)&&e--;for(let t of this.optimisticUpserts.keys())this.syncedData.has(t)||e++;return e}ey(e,t,n,r){let i=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(let a of i){let i=this.get(a),o=this.get(a,e,t),s=this.ak(a,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),c=this.ak(a);o!==void 0&&i===void 0?r.push({type:`delete`,key:a,value:o,__virtualProps:{value:s}}):o===void 0&&i!==void 0?r.push({type:`insert`,key:a,value:i,__virtualProps:{value:c}}):o===void 0||i===void 0||Vs(o,i)&&s.$origin===c.$origin&&s.$hasPendingWrites===c.$hasPendingWrites||r.push({type:`update`,key:a,value:i,previousValue:o,__virtualProps:{value:c,previousValue:s}})}}createSyncedKeyLookup(){if(this.pendingSyncedTransactions.length===0)return e=>this.syncedData.has(e);let e=new Map,t=!1;for(let n of this.pendingSyncedTransactions)if(n.committed){n.truncate&&(e.clear(),t=!0);for(let t of n.operations)e.set(t.key,t.type!==`delete`)}return n=>e.get(n)??(!t&&this.syncedData.has(n))}enableHydrationAuthorityTracking(){this.appliedAdapterKeys??=new Map}bj(e,t){let n=e.states.get(t);return n===void 0?e.truncated?{exists:!1,value:void 0}:{exists:this.syncedData.has(t),value:this.syncedData.get(t)}:n}getAcceptedSyncedRow(e){return this.bj(this.a7,e).value}acceptSyncTransaction(e){let t=this.pendingSyncedTransactions,n=t.indexOf(e);n!==-1&&t.splice(n,1);let r=t.findIndex(e=>!e.committed),i=r===-1?t.length:r;t.splice(i,0,e),i!==n&&this.refreshPendingSyncedProjection(),this.commitPendingTransactions()}discardOpenSyncTransactions(){let e=this.pendingSyncedTransactions.filter(e=>e.committed);e.length!==this.pendingSyncedTransactions.length&&(this.pendingSyncedTransactions=e,this.refreshPendingSyncedProjection())}hasOpenSyncTransaction(){return this.pendingSyncedTransactions.at(-1)?.committed===!1}hasHeldSyncTransaction(){return this.pendingSyncedTransactions.some(e=>e.committed)}*acceptedSyncedEntries(){let{states:e,truncated:t}=this.a7;if(!t)for(let t of this.syncedData.entries())e.has(t[0])||(yield t);for(let[t,n]of e)n.exists&&(yield[t,n.value])}dt(e,t,n){let r=this.bj(e,t);return!r.exists||this.hydrationSeedKeys.has(t)&&!e.sourceKeys.has(t)?`insert`:r.value!==void 0&&Vs(r.value,n)?`update`:`duplicate`}b_(e){return e.type===`update`&&e.originalSyncType!==`insert`&&(this.config.sync.rowUpdateMode||`partial`)===`partial`}classifyPendingSyncedInsert(e,t){return this.dt(this.a7,e,t)}c1(e,t){let n=t.key;if(t.type===`delete`)e.states.set(n,{exists:!1,value:void 0});else if(this.b_(t)){let r=this.bj(e,n);e.states.set(n,{exists:!0,value:{...r.value,...t.value}})}else e.states.set(n,{exists:!0,value:t.value})}stagePendingSyncOperation(e,t){this.c1(this.a7,e),t||this.a7.sourceKeys.add(e.key)}dJ(e){let t=e.explicitRowMetadataWrites,n=e.rowMetadataWrites;for(let t of e.operations)n.delete(t.key);for(let[e,r]of t)n.set(e,r.write);e.operations.forEach((e,r)=>{let i=e.key;if(r<(t.get(i)?.position??0))return;let a=Tu(e);a&&n.set(i,a)})}bA(){let e={states:new Map,truncated:!1,sourceKeys:new Set},t=new Set;for(let n of this.pendingSyncedTransactions){if(n.invalidationError!==void 0)continue;let r=n.committed?void 0:{states:new Map(e.states),truncated:e.truncated,sourceKeys:new Set(e.sourceKeys)};n.truncate&&(e.states=new Map,e.truncated=!0);let i;for(let r of n.operations){let a=r.key;if(!n.committed&&r.originalSyncType===`insert`&&r.type!==`delete`&&!(this.hydrationSeedKeys.has(a)&&e.sourceKeys.has(a)&&!t.has(a))){let t=this.dt(e,a,r.value);if(t===`duplicate`){i=a;break}r.type=t}this.c1(e,r),n.preserveHydrationSeedKeys?.has(a)||(e.sourceKeys.add(a),n.committed&&t.add(a))}i===void 0?n.committed||this.dJ(n):(Object.assign(e,r),n.invalidationError=n.duplicateKeyError?.(i)??new xs)}this.a7=e}refreshPendingSyncedProjection(){this.bA()}hasPersistingTransaction(){for(let e of this.transactions.values())if(e.state===`persisting`)return!0;return!1}dG(){let e=this.syncRunGeneration,t=this.hasPersistingTransaction(),n=[],r=[],i=!1,a=!1,o=!1;for(let e of this.pendingSyncedTransactions)e.committed?(n.push(e),o||=e.layoutChanged,e.truncate&&(i=!0,a=e.truncateMarkReady!==!1)):r.push(e);if(n.length===0)return{processed:!1};if(!t||i){let t=o?[...this.keys()]:void 0;this.pendingSyncedTransactions=r;let s=n.reduce((e,t)=>e+t.operations.length,0)>=512;for(let e of n)e.applicationStarted=!0;this.isCommittingSyncTransactions=!0;let c=new Set,l=new Map;for(let e of n){for(let t of e.operations){let e=t.key;c.add(e),l.has(e)||l.set(e,t)}for(let[t]of e.rowMetadataWrites)c.add(t)}let u=this.et(c),d=new Map(this.optimisticUpserts),f=new Set(this.optimisticDeletes),p=this.preSyncVisibleState;if(p.size===0){p=new Map;for(let e of c){let t=this.get(e);t!==void 0&&p.set(e,t)}}let m=[],h;if(i)for(let[e,t]of this.entries())m.push({type:`delete`,key:e,value:this.aW(t,this.ak(e))});for(let e of n){if(e.truncate){this.syncedData.clear();let t=e.sourceTruncate?e.preserveHydrationSeedKeys:void 0;if(!e.preserveHydrationSeedKeys||t){for(let e of[this.syncedMetadata,this.hydrationSeedKeys,this.hydratedKeys,this.appliedAdapterKeys??new Set])for(let n of e.keys())t?.has(n)||e.delete(n);this.appliedAdapterKeys&&(this.hasAppliedAdapterTruncate=!0,this.adapterTruncateKeptKeys=new Set(t))}this.dE.clear(),this.rowOrigins.clear(),this.pendingLocalOrigins.clear();for(let e of c)p.delete(e);this.a3.emit(`truncate`,{type:`truncate`,collection:this.collection})}let t=new Set;for(let n of e.operations){let r=n.key,i=this.isLocalOnly||this.pendingLocalChanges.has(r)||this.pendingLocalOrigins.has(r)||t.has(r)?`local`:`remote`;i===`local`&&t.add(r),this.dE.delete(r),n.type===`delete`?(this.syncedData.delete(r,s),this.syncedMetadata.delete(r),this.rowOrigins.delete(r)):(this.syncedData.set(r,this.b_(n)?{...this.syncedData.get(r),...n.value}:n.value,s),this.rowOrigins.set(r,i)),this.pendingLocalChanges.delete(r),this.pendingLocalOrigins.delete(r),this.bf(r)||this.heldOptimisticRows.delete(r),e.preserveHydrationSeedKeys?.has(r)||(this.hydrationSeedKeys.delete(r),this.hydratedKeys.delete(r),n.type===`delete`?this.appliedAdapterKeys?.set(r,!0):this.appliedAdapterKeys?.get(r)&&this.appliedAdapterKeys.set(r,!1))}for(let[t,n]of e.rowMetadataWrites)!e.preserveHydrationSeedKeys?.has(t)&&!this.appliedAdapterKeys?.has(t)&&this.appliedAdapterKeys?.set(t,!1),n.type===`delete`?this.syncedMetadata.delete(t):this.syncedMetadata.set(t,n.value);for(let[t,n]of e.collectionMetadataWrites)n.type===`delete`?this.syncedCollectionMetadata.delete(t):this.syncedCollectionMetadata.set(t,n.value)}if(this.syncedData.restoreOrder(),this.refreshPendingSyncedProjection(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,this.c7(),i){for(let[e,t]of this.optimisticUpserts)m.push({type:`insert`,key:e,value:t});h=new Set(this.optimisticUpserts.keys())}for(let e of c){if(h?.has(e))continue;let t=l.get(e),n=t?.type===`update`&&p.get(e)===t.value?t.previousValue:void 0,r=!i&&!d.has(e)&&!f.has(e)&&n!==void 0?n:p.get(e),a=this.get(e);if(r===void 0){if(a===void 0)continue;m.push({type:`insert`,key:e,value:a});continue}let o=this.preSyncVirtualState.get(e)??this.ak(e,{rowOrigins:u,optimisticUpserts:d,optimisticDeletes:f}),s=t=>pl(t,e,this.collection.id,()=>o.$hasPendingWrites,()=>o.$origin);if(a===void 0){m.push({type:`delete`,key:e,value:s(r)});continue}let c=this.ak(e);o.$hasPendingWrites===c.$hasPendingWrites&&o.$origin===c.$origin&&Vs(r,a)||m.push({type:`update`,key:e,value:a,previousValue:s(r)})}this.size=this.e1(),m.length>0&&this.indexes.updateIndexes(m);let g,_=e=>{try{e()}catch(e){g??={error:e}}},v=t!==void 0&&(t.length!==this.size||[...this.keys()].some((e,n)=>e!==t[n])),y=!1,b=()=>{y=!0,_(()=>this.changes.emitEvents(m,!0,v))};a&&this.lifecycle.status!==`ready`&&_(()=>this.lifecycle.markReady(b)),y||b(),i&&this.lifecycle.status===`ready`&&_(()=>this.lifecycle.completeReload()),this.syncRunGeneration===e&&(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),Promise.resolve().then(()=>{this.syncRunGeneration===e&&this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit=!0);for(let e of n)e.applied.resolve();return{processed:!0,failure:g}}return{processed:!1}}cancelPendingSyncedTransaction(e,t=new xs){if(e.committed||this.pendingSyncedTransactions.at(-1)!==e)throw new zo(`only the open last sync transaction can be canceled`);this.pendingSyncedTransactions.pop();let n=new Set;for(let t of e.operations)n.add(t.key);e.applied.reject(t),this.bA();let r=new Set;for(let e of this.pendingSyncedTransactions)if(e.invalidationError===void 0)for(let t of e.operations)r.add(t.key);for(let e of n)r.has(e)||(this.recentlySyncedKeys.delete(e),this.preSyncVisibleState.delete(e),this.preSyncVirtualState.delete(e));this.pendingSyncedTransactions.length===0?(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.changes.emitEvents([],!0)):this.recomputeOptimisticState(!1)}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;let e=new Set;for(let t of this.pendingSyncedTransactions)if(t.committed){for(let n of t.operations)e.add(n.key);for(let n of t.rowMetadataWrites.keys())e.add(n)}for(let t of e)this.recentlySyncedKeys.add(t);for(let t of e)if(!this.preSyncVisibleState.has(t)){let e=this.get(t);this.preSyncVisibleState.set(t,e),e!==void 0&&this.preSyncVirtualState.set(t,this.ak(t))}}onTransactionStateChange(){let e=this.hasPersistingTransaction();this.changes.shouldBatchEvents=this.pendingSyncedTransactions.some(t=>t.committed&&(!e||t.truncate)),this.changes.shouldBatchEvents&&this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncRunGeneration++;for(let e of this.pendingSyncedTransactions)e.applied.reject(new xs);this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.heldOptimisticRows.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.appliedAdapterKeys?.clear(),this.hasAppliedAdapterTruncate=!1,this.adapterTruncateKeptKeys.clear(),this.dh(),this.isLocalOnly=!1,this.localOnlyDirectWrite=void 0,this.size=0,this.pendingSyncedTransactions=[],this.refreshPendingSyncedProjection(),this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.hasReceivedFirstCommit=!1}},Du=new class{constructor(){this.fW=new Map}fg(e){let t=this.fW.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map},this.fW.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:r}){if(e===void 0){r();return}let i=this.fg(e);if(i.jobs.has(t)||i.queue.push(t),i.jobs.set(t,r),n){let e=new Set(n);e.delete(t),i.dependencies.set(t,e)}else i.dependencies.has(t)||i.dependencies.set(t,new Set)}flush(e){let t=this.fW.get(e);if(!t)return;let{queue:n,jobs:r,dependencies:i}=t;for(;n.length>0;){let t=!1,a=n.length;for(let e=0;e<a;e++){let e=n.shift(),a=r.get(e);if(!a){i.delete(e);continue}let o=i.get(e),s=!o;if(o){s=!0;for(let t of o)if(t!==e&&r.has(t)){s=!1;break}}s?(r.delete(e),i.delete(e),a(),t=!0):n.push(e)}if(!t)throw Error(q(161,{contextId:e}))}this.fW.delete(e)}clear(e){this.fW.delete(e)}},Ou,ku;function Au(){return ku}function ju(){return Ou}function Mu(e){if(Ou===void 0)throw e;ku??={error:e}}function Nu(e){if(Ou!==void 0)return e();let t=Symbol(`collection-publication`);Ou=t,ku=void 0;let n,r;try{n=e(),Du.flush(t),r=Au()}catch(e){try{Du.clear(t)}catch{}let n=Au();throw n?n.error:e}finally{Ou=void 0,ku=void 0}if(r)throw r.error;return n}function Pu(e){let t;for(let n of e)try{n()}catch(e){t??={error:e}}if(t)throw t.error}function Fu(e){queueMicrotask(()=>{throw e})}var Iu=class{constructor(){this.listeners=new Map,this.e4=new WeakMap}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Map);let n=this.listeners.get(e),r=t,i=n.get(r);return i||(i={},n.set(r,i)),()=>{let t=this.listeners.get(e);t?.get(r)===i&&t.delete(r)}}once(e,t){let n=()=>{},r=e=>{n(),t(e)};return this.e4.set(r,t),n=this.on(e,r),n}off(e,t){let n=this.listeners.get(e);if(n)for(let e of n.keys())(e===t||this.e4.get(e)===t)&&n.delete(e)}waitFor(e,t){return new Promise((n,r)=>{let i,a=this.on(e,e=>{i&&=(clearTimeout(i),void 0),n(e),a()});t&&(i=setTimeout(()=>{i=void 0,a(),r(Error(q(98,{event:e})))},t))})}emitInner(e,t){this.emitInnerWhile(e,t,()=>!0)}emitInnerWhile(e,t,n){let r=this.listeners.get(e);if(r)for(let[i,a]of[...r]){if(!n())break;if(this.listeners.get(e)?.get(i)===a)try{i(t)}catch(e){queueMicrotask(()=>{throw e})}}}clearListeners(){this.listeners.clear()}};function Lu(e){return Gl(Jl(e),ql(e))}function Ru(e,t){let n=Lu(e.expression);if(t==null)return e.compareOptions.nulls===`first`?Kl(n):new rr(!1);let r=(e.compareOptions.direction===`asc`?Vl:Ul)(e.expression,new rr(t));return e.compareOptions.nulls===`last`?Gl(r,n):r}function zu(e,t){if(t.length!==0){if(e.length===0||t.length!==1)throw Error(q(169));return Ru(e[0],t[0])}}function Bu(e,t){let{expression:n}=e[0]??{};if(!n||t.length===0)return;let r=t[0];if(r==null)return Lu(n);if(r instanceof Date)return Number.isFinite(r.getTime())?Wl(Hl(n,new rr(r)),Ul(n,new rr(new Date(r.getTime()+1)))):void 0;if(typeof r!=`object`)return Bl(n,new rr(r))}function Vu(e,t){if(e.length===0||t.length!==1)return!1;let n=t[0];return n==null?!1:n instanceof Date?Number.isFinite(n.getTime()):typeof n==`string`?e[0].compareOptions.stringSort===`lexical`:typeof n==`number`&&Number.isFinite(n)||typeof n==`bigint`||typeof n==`boolean`}var Hu=e=>{try{return e instanceof Error?e:Error(String(e))}catch{return Error(q(170))}};function Uu(){let e,t,n=!0;return{promise:new Promise((r,i)=>{e=e=>{n=!1,r(e)},t=e=>{n=!1,i(e)}}),resolve:e,reject:t,isPending:()=>n}}function Wu(e){return typeof e==`object`&&!!e&&typeof e.subscribeChanges==`function`&&typeof e.startSyncImmediate==`function`&&typeof e.id==`string`}function Gu(e){return e?.publicCollection??e}function Ku(e){return e.config?.singleResult===!0}function qu(e){return e===`error`||e===`crashed`}function Ju(e,t){return{isLoading:e===`loading`,isReady:e===`ready`,isIdle:e===`idle`,isLoadingError:e===`error`,isCrashed:e===`crashed`,isCleanedUp:e===`cleaned-up`,isSyncError:e===`ready`&&t?.hasErrors===!0,health:t}}function Yu(){let e=Uu();return e.promise.catch(()=>{}),e}function Xu(e){e.abortController?.abort(),e.removeRequestAbortListener?.()}function Zu(e,t,n){e?.addEventListener(`abort`,n,{once:!0});let r=()=>e?.removeEventListener(`abort`,n);t.then(r,r)}var Qu=class extends Iu{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.ej=!1,this.snapshotSent=!1,this.C=[],this.d8=new WeakMap,this.aC=new Set,this.ac=new Map,this.ad=new Map,this.fk=`ready`,this.aV=0,this.aq=new Set,this.dx=new WeakMap,this.aR=!1,this.unsubscribed=!1,this.c_=n.deferAcquisition===!0,n.onUnsubscribe&&this.on(`unsubscribed`,n.onUnsubscribe),n.onLoadSubsetError&&this.on(`loadSubset:error`,n.onLoadSubsetError),n.whereExpression&&au(n.whereExpression,this.collection),this.callback=e=>{for(let t of e)t.type===`delete`?(this.ac.delete(t.key),this.aC.delete(t.key)):(this.ac.set(t.key,t.value),this.aC.add(t.key));t(e)},this.dN=n.whereExpression?bu(this.callback,n):e=>(this.callback(e),!0),this.cb=[this.collection.on(`truncate`,()=>this.fC()),this.collection._onCleanupStart(()=>this.eE()),this.collection.on(`status:change`,({status:e})=>{if(e!==`loading`&&e!==`ready`)return;let t=this.collection._sync.getSyncRunGeneration(),n=this.o;this.C.some(e=>e.acquisitionState===`detached`)&&this.setStatus(`loadingSubset`),queueMicrotask(()=>{this.o===n&&this.eM(t)})})]}get owner(){return this.options.owner}get status(){return this.fk}get lastError(){return this.fu}isDeferringAcquisition(){return this.c_}resumeDeferredAcquisition(){if(!this.c_||this.unsubscribed)return;let e=this.options.onResumeAcquisition?.();this.unsubscribed||(this.c_=!1,e?.(),this.collection.status!==`idle`&&this.eM(this.collection._sync.getSyncRunGeneration()))}retireSyncRun(){let e=this.g3()&&this.C.length>0;this.eE(!0,e),e&&this.fC(!0)}g3(){return this.collection.config.syncMode===`on-demand`&&!this.c_}eE(e=!1,t=!1){this.bP(),this.aR=t,e||(this.ad=new Map(this.ac)),this.aq.clear();for(let t of[...this.C])if(e&&t.acquisitionState!==`starting`||t.initialResult?.reject(new Cs),Xu(t.acquisition),t.acquisitionState===`starting`){let e=this.C.indexOf(t);e!==-1&&this.C.splice(e,1)}else t.acquisitionState=`detached`,t.acquisition={options:t.requestOptions,syncRunGeneration:t.acquisition.syncRunGeneration};this.b9()}eM(e){if(this.unsubscribed||this.c_||!this.Z(e))return;if(qu(this.collection.status)||this.collection.config.syncMode===`on-demand`&&this.collection._sync.syncLoadSubsetFn===null){this.b9();return}let t=this.C.filter(e=>e.acquisitionState===`detached`&&!e.requestOptions.signal?.aborted);if(t.length===0){this.b9();return}if(this.collection.config.syncMode!==`on-demand`&&this.collection.status!==`ready`)return;let n=this.o,r=n?.syncRunGeneration===e,i=r?n:this.c4(()=>{let e=this.collection.currentStateAsChanges({optimizedOnly:!1});return new Map((e??[]).filter(e=>e.type!==`delete`).map(e=>[e.key,e.value]))});r&&(n.pendingSetups++,n.failed&&(n.completion.isPending()||(n.completion=Yu()),n.currentAttempt={pendingCount:0,setupComplete:!1}));let a=i.currentAttempt;this.o=i,this.setStatus(`loadingSubset`),this.o===i&&this.cX(i,a,t)}fC(e=!1){let t=this.g3()?[...this.C]:[];if(t.length===0&&this.ad.size===0){this.dU();return}let n=this.o;n?(n.completion.isPending()||(n.completion=Yu()),n.pendingSetups++,n.failures.clear(),n.unloaded.clear(),n.failed=!1,n.currentAttempt={pendingCount:0,setupComplete:!1}):(n=this.c4(()=>new Map(this.ac)),this.o=n);let r=n.currentAttempt;if(this.setStatus(`loadingSubset`),this.o===n){this.options.truncateReplayPublication&&(this.aR=!0,this.options.truncateReplayPublication.start(e));for(let e of t)e.acquisition.abortController?.abort();this.dU(),queueMicrotask(()=>{this.o===n&&(this.Z(n.syncRunGeneration)?this.cX(n,r,n.currentAttempt===r?t:[]):this.c8(n))})}}eu(e,t,n){let r=()=>this.o===e&&e.currentAttempt===t&&this.Z(e.syncRunGeneration)&&this.a4(n),i=n.initialResult,a=n.parkedParticipant;n.parkedParticipant=void 0,a&&e.pending.delete(a)&&a.attempt.pendingCount--,i&&e.completion.promise.then(i.resolve,e=>{e instanceof Cs||i.reject(e)});let o=n.acquisition,s=n.acquisitionState===`active`;if(n.acquisitionState=`detached`,s&&this.releaseAcquisition(o),!r()||n.requestOptions.signal?.aborted)return;let c=this.cF(n.requestOptions);c.attempt=t,n.acquisition=c,n.acquisitionState=`starting`;let l=this.collection._sync.loadSubset(c.options);r()?(n.acquisitionState=`active`,this.co(l,n,c.options,!0,()=>r()&&!c.options.signal?.aborted),this.cB(e,t,n,l,c.options.signal)):(n.acquisition===c&&(n.acquisitionState=`detached`),this.releaseAcquisition(c))}ea(e,t){try{if(this.o!==e)return;if(!this.Z(e.syncRunGeneration)){this.c8(e);return}e.pending.delete(t)&&t.attempt.pendingCount--,this.bJ(e)}catch(e){Fu(e)}}cB(e,t,n,r,i){if(this.o!==e||e.currentAttempt!==t&&t.setupComplete&&t.pendingCount===0||!(r instanceof Promise))return;let a={demand:n,attempt:t};t.pendingCount++,e.pending.add(a);let o=()=>this.ea(e,a);return Zu(i,r,()=>{e.currentAttempt===t&&e.unloaded.add(n),queueMicrotask(o)}),r.then(o,a=>{if(!i?.aborted&&this.o===e&&e.currentAttempt===t&&this.Z(e.syncRunGeneration)&&this.C.includes(n)){let t=this.cl(r,a);e.failures.set(n,t),e.failed=!0}o()}),a}dX(e){let t=this.o;if(t){t.failures.delete(e);for(let n of t.pending)n.demand===e&&(t.pending.delete(n),n.attempt.pendingCount--)}}bJ(e){if(this.o!==e||e.pendingSetups>0||e.pending.size>0)return;let t=[];for(let[n,r]of e.failures)this.C.includes(n)&&!this.C.some(t=>t.replaces?.includes(n)&&!e.failures.has(t)&&!e.unloaded.has(t))&&t.push(r);try{if(t.length>0)this.eP(e,t);else{if(this.gN(e,()=>this.bJ(e)))return;this.fb(e)}}finally{this.b9()}}eP(e,t){if(this.o!==e)return;let n=e.completion.isPending();if(e.completion.reject(t[0]),n&&this.options.truncateReplayPublication?.fail?.(t),!e.privateRows)return;let r=e.publicationState;this.loadedInitialState=r.loadedInitialState,this.snapshotSent=r.snapshotSent}fb(e){if(this.o===e){this.o=void 0,this.aR=!1;try{this.gy(e.privateRows)}finally{e.completion.resolve(),this.options.truncateReplayPublication?.succeed()}}}gy(e){for(let t of this.ad.keys())e?.delete(t);this.ad.clear();try{if(e){let t=this.fx(this.ac,e);t.length>0&&this.dN(t)}}finally{this.cg()}}cg(){this.aC=new Set(this.ac.keys())}eG(e){let t=this.o?.privateRows;if(!t)return!1;for(let n of e)n.type===`delete`?t.delete(n.key):t.set(n.key,n.value);return!0}fx(e,t){let n=[];for(let[r,i]of e){let e=t.get(r);e===void 0?n.push({type:`delete`,key:r,value:i}):Vs(e,i)||n.push({type:`update`,key:r,value:e,previousValue:i})}for(let[r,i]of t)e.has(r)||n.push({type:`insert`,key:r,value:i});return n}get fS(){return this.o!==void 0}b9(){this.aq.size===0&&!this.hasTruncateReplayWork&&this.setStatus(`ready`)}Z(e){return e===this.collection._sync.getSyncRunGeneration()}c8(e){this.o===e&&(this.bP(),this.ad.clear())}failReplacement(e){if(this.o)return;let t=this.c4(()=>new Map);t.pendingSetups=0,t.failed=!0,t.completion.reject(e),this.o=t,this.aR=!0}gN(e,t){let n=this.options.truncateReplayPublication?.siblingReplays();return n?.then(()=>{this.o===e&&t()}),n!==void 0}get hasTruncateReplayWork(){let e=this.o;return e!==void 0&&(e.pendingSetups>0||e.pending.size>0)}bP(){let e=this.o;e?.completion.isPending()&&e.completion.reject(new Cs),this.o=void 0,this.aR=!1}dU(){this.snapshotSent=!1,this.loadedInitialState=!1}c4(e){return{syncRunGeneration:this.collection._sync.getSyncRunGeneration(),publicationState:{loadedInitialState:this.loadedInitialState,snapshotSent:this.snapshotSent},privateRows:this.options.truncateReplayPublication?void 0:e(),pending:new Set,pendingSetups:1,currentAttempt:{pendingCount:0,setupComplete:!1},failures:new Map,unloaded:new Set,failed:!1,completion:Yu()}}cX(e,t,n){for(let r of n)if(this.C.includes(r)&&r.acquisition.attempt!==t&&(this.eu(e,t,r),this.o!==e||e.currentAttempt!==t))break;t.setupComplete=!0,e.pendingSetups--,this.bJ(e)}get hasPendingTruncateReplacement(){return this.aR}get hasHeldSyncTransaction(){return this.collection._hasHeldSyncTransaction()}get pendingTruncateReplacement(){let e=this.o?.completion;return e?.isPending()?e.promise:void 0}get hasFailedTruncateReplacement(){let e=this.o?.completion;return this.aR&&e!==void 0&&!e.isPending()}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this.unsubscribed||this.fk===e)return;let t=this.fk;this.fk=e;let n=++this.aV;if(this.emitInnerWhile(`status:change`,{type:`status:change`,subscription:this,previousStatus:t,status:e},()=>this.aV===n),this.aV!==n)return;let r=`status:${e}`;this.emitInnerWhile(r,{type:r,subscription:this,previousStatus:t,status:e},()=>this.aV===n)}co(e,t,n,r,i=()=>!0){if(!(e instanceof Promise))return;let a=this.collection._sync.getSyncRunGeneration(),o={demand:t,promise:e};r&&(this.aq.add(o),this.setStatus(`loadingSubset`));let s=()=>{r&&(this.aq.delete(o),this.Z(a)&&this.b9())};r&&Zu(n.signal,e,()=>queueMicrotask(s)),e.then(s,t=>{this.Z(a)&&i()&&this.bR(n,this.cl(e,t)),s()})}cl(e,t){let n=this.dx.get(e);if(n)return n;let r=Hu(t);return this.dx.set(e,r),r}cO(e){for(let t of this.aq)t.demand===e&&this.aq.delete(t);this.b9()}cF(e,t=!1){if(t||this.collection.config.syncMode!==`on-demand`)return{options:e,syncRunGeneration:this.collection._sync.getSyncRunGeneration()};let n=new AbortController,r=e.signal,i;if(r?.aborted)n.abort(r.reason);else if(r){let e=()=>n.abort(r.reason);r.addEventListener(`abort`,e,{once:!0}),i=()=>r.removeEventListener(`abort`,e)}return{options:{...e,signal:n.signal},syncRunGeneration:this.collection._sync.getSyncRunGeneration(),abortController:n,removeRequestAbortListener:i}}releaseAcquisition(e){if(!e.releaseAttempted){e.releaseAttempted=!0;try{e.abortController?.abort(),this.Z(e.syncRunGeneration)&&this.collection._sync.unloadSubset(e.options)}catch(e){Fu(e)}finally{e.removeRequestAbortListener?.()}}}dD(e){let t;!this.o&&this.options.truncateReplayPublication?.siblingReplays()&&(t=this.c4(()=>new Map),this.o=t,this.aR=!0);let n=this.o,r=n?.currentAttempt;try{let t=this.collection.status===`cleaned-up`||this.c_&&this.collection.config.syncMode===`on-demand`||this.collection.config.syncMode===`on-demand`&&(qu(this.collection.status)||this.collection.status!==`idle`&&this.collection._sync.syncLoadSubsetFn===null),i=this.cF(e,t),a={requestOptions:e,acquisition:i,acquisitionState:t?`detached`:`starting`};if(this.C.push(a),t){let t=Uu();a.initialResult=t;let i=()=>t.reject(new Cs);e.signal?.addEventListener(`abort`,i,{once:!0});let o=()=>{e.signal?.removeEventListener(`abort`,i),a.initialResult=void 0};return t.promise.then(o,o),n&&r&&(a.parkedParticipant=this.cB(n,r,a,t.promise,e.signal)),{demand:a,result:t.promise,started:!1}}let o=i.syncRunGeneration,s=this.collection._sync.loadSubset(i.options);if(this.Z(o))a.acquisitionState=`active`,this.C.includes(a)?n&&r&&this.cB(n,r,a,s,i.options.signal):this.releaseAcquisition(i);else{let e=this.C.indexOf(a);e!==-1&&this.C.splice(e,1),Xu(i)}return{demand:a,result:s,started:!0}}finally{t&&r&&this.cX(t,r,[])}}a4(e){return!this.unsubscribed&&this.C.includes(e)}bR(e,t,n=!1){let r=Hu(t);return e.signal?.aborted&&!n||(this.fu=r,this.emitInner(`loadSubset:error`,{type:`loadSubset:error`,subscription:this,options:e,error:r})),r}emitEvents(e){if(this.unsubscribed)return!1;let t=this.d0(e);return e.length>0&&t.length===0||this.eG(t)?!1:this.dN(t)}eH(e){this.eG(e)||this.callback(e)}requestSnapshot(e){if(this.unsubscribed||e?.signal?.aborted||this.loadedInitialState)return!1;let t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if(`where`in e){let n=e.where;if(t.where){let e=t.where;t.where=Wl(e,n)}else t.where=n}e.boundedPrefix&&(t.orderBy=e.orderBy,t.limit=e.limit)}else this.loadedInitialState=!0;let n={...e?.refetch?{refetch:!0}:{},where:t.where,signal:e?.signal,subscription:this,orderBy:e?.orderBy,limit:e?.limit===void 0?void 0:e.limit+this.collection._optimisticOverlaySize()};e?.where&&this.d8.set(n,e.where);let{demand:r,result:i,started:a}=this.dD(n);if(!this.a4(r)||(e?.onLoadSubsetResult?.(i,r.acquisition.options,e=>this.e6(r,e)),!this.a4(r))||(a&&this.co(i,r,r.acquisition.options,e?.trackLoadSubsetPromise??!0),!this.a4(r)))return!1;let o;if(e?.onUnoptimized){if(o=this.collection.currentStateAsChanges({...t,optimizedOnly:!0}),o===void 0){if(e.onUnoptimized(),!this.a4(r))return!1;o=this.collection.currentStateAsChanges({...t,optimizedOnly:!1})}}else o=this.collection.currentStateAsChanges(t);if(!this.a4(r)||o===void 0)return!1;let s=this.o?.privateRows??this.ac,c=o.filter(e=>!this.fS&&this.ad.has(e.key)||!this.aC.has(e.key)&&!s.has(e.key));for(let e of c)this.aC.add(e.key);return this.snapshotSent=!0,this.eH(this.fS?c:this.cy(c)),!0}releaseSnapshot(...e){let t=[];for(let n of e){let e=this.C.find(e=>!t.includes(e)&&this.d7(e,n));e&&t.push(e)}t.length>0&&this.g$(t)}replaceSnapshots(e,t){let n=this.C.find(t=>this.d7(t,e));n&&(n.replaces=this.C.filter(e=>t.some(t=>this.d7(e,t))))}d7(e,t){return e.requestOptions.where===t||this.d8.get(e.requestOptions)===t}e6(e,t){try{t&&this.bR(e.acquisition.options,t.error,!0)}finally{this.C.includes(e)&&this.g$([e])}}g$(e){let t=this.o,n=[];for(let t of e){let e=t.acquisition;this.C.splice(this.C.indexOf(t),1),t.initialResult?.reject(new Cs),n.push(()=>this.dX(t)),t.acquisitionState===`active`&&n.push(()=>this.releaseAcquisition(e))}Pu([...n,()=>this.fm(),()=>{t&&this.bJ(t)},...e.map(e=>()=>this.cO(e))])}fm(){let e=this.o;this.C.length===0&&e&&(e.privateRows&&!e.failed?this.fb(e):this.gN(e,()=>this.fm())||(this.bP(),this.ad=new Map(this.ac),this.cg(),this.options.truncateReplayPublication?.succeed()))}readOrderedSnapshot(e){let t=[this.options.whereExpression,e.where,e.cursor?.whereFrom].filter(e=>e!==void 0),n=this.collection.currentStateAsChanges({orderBy:e.orderBy,limit:e.limit,where:t.length>0?t.reduce((e,t)=>Wl(e,t)):void 0});return Array.isArray(n)?n.filter(({key:e})=>!this.collection._hasOptimisticOverlay(e)):[]}requestLimitedSnapshot({refetch:e,orderBy:t,limit:n,minValues:r,offset:i,trackLoadSubsetPromise:a=!0,onLoadSubsetResult:o}){if(this.unsubscribed)return;if(!n)throw Error(q(96));if(!this.orderByIndex)throw Error(q(97));let s=r?zu(t,r):void 0,c=r!==void 0&&r.length>0,l=r?.[0],u=this.orderByIndex,d=this.options.whereExpression,f=d?yu(d):void 0,p=e=>{if(e!==void 0&&this.aC.has(e))return!1;let t=this.collection.get(e);return t===void 0?!1:f?.(t)??!0},m=l,h=[],g=[];if(c){let{expression:e}=t[0],r=this.collection.currentStateAsChanges({where:Bl(e,new rr(l))});if(r){let e=r.map(e=>e.key).filter(p);g.push(...e);let t=u.take(n-g.length,l,p);g.push(...t)}else g=u.take(n,l,p)}else g=u.takeFromStart(n,p);let _=()=>Math.max(n-h.length,0),v=()=>g.length===0,y=t[0].expression,b=y.type===`ref`?il(new J(nr(y)),!0):null;for(;_()>0&&!v();){for(let e of g){let t=this.collection.get(e);h.push({type:`insert`,key:e,value:t}),m=b?b(t):t}g=u.take(_(),m,p)}for(let e of h)this.aC.add(e.key);if(this.eH(h),this.unsubscribed)return;let x;if(s&&r){let e=Bu(t,r);e&&(x={whereFrom:s,whereCurrent:e})}let S=this.collection._optimisticOverlaySize(),C=i===void 0?c?void 0:n+this.aC.size+S:n+S,w={...e?{refetch:!0}:{},where:d,limit:C,orderBy:t,cursor:x,offset:i??0,subscription:this},{demand:T,result:E,started:D}=this.dD(w);this.a4(T)&&(o?.(E,T.acquisition.options,e=>this.e6(T,e)),this.a4(T)&&(D&&this.co(E,T,T.acquisition.options,a),this.a4(T)))}d0(e){if(e=this.cy(e),this.loadedInitialState||this.ej)return e;let t=this.fS,n=new Set,r=[];for(let i of e){let e=i;if(!(this.aC.has(i.key)||n.has(i.key))){if(i.type===`update`)e={...i,type:`insert`,previousValue:void 0},n.add(i.key);else if(i.type===`delete`){if(!t)continue}else n.add(i.key)}else if(i.type===`insert`)continue;else i.type===`delete`&&(this.aC.delete(i.key),n.delete(i.key));r.push(e)}return r}cy(e){if(this.ad.size===0)return e;let t=[];for(let n of e){let e=this.ad.get(n.key);e===void 0?t.push(n):(this.ad.delete(n.key),n.type===`delete`?t.push({...n,value:e,previousValue:void 0}):(this.o?.privateRows||!Vs(e,n.value))&&t.push({...n,type:`update`,previousValue:e}))}if(this.collection.config.syncMode!==`on-demand`&&!this.fS)for(let[e,n]of this.ad)this.collection.has(e)||(this.ad.delete(e),t.push({type:`delete`,key:e,value:n}));return t}markAllStateAsSeen(){this.ej=!0}unsubscribe(){if(this.unsubscribed)return;this.unsubscribed=!0,this.aV++;let e=this.cb;this.cb=[],Pu([...e,()=>{this.bP(),this.ad.clear();let e=this.C.filter(e=>e.acquisitionState===`active`).map(e=>e.acquisition);for(let e of this.C)e.initialResult?.reject(new Cs),this.cO(e),e.acquisitionState===`starting`&&Xu(e.acquisition);this.C=[];for(let t of e)this.releaseAcquisition(t)},()=>this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this}),()=>this.clearListeners()])}},$u=class{constructor(){this.activeSubscribersCount=0,this.acquiringSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1,this.cM=new Set,this.f2=!1,this.ex=new Set,this.stateRevision=0,this.layoutRevision=0}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){Nu(()=>{try{Pu([...this.changeSubscriptions].map(e=>()=>e.emitEvents([])))}catch(e){Mu(e)}})}cK(e){return this.state.enrichChangeMessage(e)}eW(e,t){if(!e)return t;if(e.type===`insert`)return t.type===`delete`?void 0:{...t,type:`insert`,previousValue:void 0};let n=e.type===`update`?e.previousValue??e.value:e.value;return t.type===`delete`?{...t,value:n,previousValue:void 0}:{...t,type:`update`,previousValue:n}}emitEvents(e,t=!1,n=!1){if(e.length>0&&this.stateRevision++,n&&this.layoutRevision++,this.shouldBatchEvents&&!t){this.batchedEvents.push(...e.map(e=>this.cK(e)));return}let r=e;if(t){if(this.batchedEvents.length>0){let t=new Map;for(let n of[...this.batchedEvents,...e])t.set(n.key,this.eW(t.get(n.key),n));r=[...t.values()].flatMap(e=>e?[e]:[])}this.batchedEvents=[],this.shouldBatchEvents=!1}this.aN?this.aN.publications.push({changes:r,layoutChanged:n}):this.e5(r,n)}deferPublication(){let e=this.aN??={depth:0,discard:!1,layoutRevision:this.layoutRevision,publications:[]};e.depth++;let t=!1,n=n=>{if(t||this.aN!==e||(t=!0,e.discard||=n,--e.depth>0))return;let r=e.publications;e.publications=[],this.aN=void 0,e.discard?(this.layoutRevision!==e.layoutRevision&&this.stateRevision++,this.layoutRevision=e.layoutRevision):this.e5(r.flatMap(({changes:e})=>e),r.some(({layoutChanged:e})=>e))};return{publish:()=>n(!1),discard:()=>n(!0)}}e5(e,t){if(e.length===0&&!t)return;let n=e.map(e=>this.cK(e)),r=[...this.cM],i=[...this.changeSubscriptions];Nu(()=>{let t=i.map(e=>()=>e.emitEvents(n));e.length===0&&t.unshift(...r);try{Pu(t)}catch(e){Mu(e)}})}subscribeLayoutChanges(e){return this.cM.add(e),()=>this.cM.delete(e)}subscribeChanges(e,t={}){if(t.where&&t.whereExpression)throw Error(q(95));let{where:n,...r}=t,i=r.whereExpression;n&&(i=X(n(Ll())));let a=r.deferAcquisition===!0;this.ei(a);let o,s={closed:!1};try{o=new Qu(this.collection,e,{...r,whereExpression:i,deferAcquisition:a,onResumeAcquisition:()=>this.gA(),onUnsubscribe:()=>{s.closed=!0,this.eB(o?.isDeferringAcquisition()??!1),o&&this.changeSubscriptions.delete(o)}}),t.onStatusChange&&o.on(`status:change`,t.onStatusChange),t.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&o.markAllStateAsSeen(),s.closed||this.changeSubscriptions.add(o)}catch(e){if(o)try{o.unsubscribe()}catch{}else this.eB(a);throw e}return o}hasSubscriberOrPreload(){return this.f2||this.acquiringSubscribersCount>0}onFirstSubscriberOrPreload(e){return this.ex.add(e),()=>this.ex.delete(e)}markSubscriberOrPreload(){if(this.f2)return;this.f2=!0;let e=[];for(let t of[...this.ex])try{t()}catch(t){e.push(t)}if(e.length)throw e[0]}gA(){return this.lifecycle.assertCanStartSync(),this.gT(),()=>this.e2(1)}gT(){let e=this.sync.getSyncRunGeneration();this.markSubscriberOrPreload(),e===this.sync.getSyncRunGeneration()&&(this.gr(),this.sync.resumeStart())}e2(e){let t=this.acquiringSubscribersCount;this.acquiringSubscribersCount+=e,this.events.emitSubscribersChange(this.acquiringSubscribersCount,t),e===1&&this.acquiringSubscribersCount>0&&this.markSubscriberOrPreload()}gr(){(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync()}ei(e){e||this.lifecycle.assertCanStartSync(),this.activeSubscribersCount++,this.lifecycle.cancelGCTimer();let t=!1;try{e?!this.lifecycle.isCleaningUp()&&Fs(this.collection.config)&&this.gr():this.gT(),e||(t=!0,this.e2(1))}catch(e){if(this.activeSubscribersCount--,t)try{this.e2(-1)}catch{}throw this.activeSubscribersCount===0&&this.lifecycle.startGCTimer(),e}}eB(e){if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new ao;e||this.e2(-1)}cleanup(){this.f2=[...this.changeSubscriptions].some(e=>!e.isDeferringAcquisition()),this.stateRevision++,this.batchedEvents=[],this.shouldBatchEvents=!1,this.aN&&(this.aN.publications.length=0),this.aN=void 0}},ed=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),td=e=>{clearTimeout(e)},nd=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>ed(e),rd=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):td,id=()=>globalThis.performance?.now()??Date.now(),ad=class e{constructor(){this.tasks=new Map,this.timeoutId=null,this.dm=!1}static getInstance(){return e.fY??=new e}schedule(e,t,n){let r=id()+t;this.tasks.set(e,{executeAt:r,callback:n}),this.dm||(this.dm=!0,Promise.resolve().then(()=>{this.dm=!1,this.fa()}))}cancel(e){this.tasks.delete(e),this.tasks.size===0&&this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}fa(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let e=1/0;for(let t of this.tasks.values())t.executeAt<e&&(e=t.executeAt);let t=Math.max(0,e-id());this.timeoutId=setTimeout(()=>{this.timeoutId=null;let e=id();for(let[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(e){console.error(q(214),e)}}this.fa()},t),typeof this.timeoutId==`object`&&this.timeoutId.unref()}};ad.fY=null;var od=ad,sd=class{constructor(e,t,n=()=>{}){this.status=`idle`,this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.aI=null,this.failureReason=null,this.a6=!1,this.dk=null,this.cc=null,this.cE=new cd,this.bw=!1,this.bI=!1,this.g2=!1,this.aP=0,this.aV=0,this.dr=!1,this.b5=null,this.bO=new Set,this.config=e,this.id=t,this.fX=n}setDeps(e){this.indexes=e.indexes,this.events=e.events,this.changes=e.changes,this.sync=e.sync,this.state=e.state}validateStatusTransition(e,t){if(e!==t&&!{idle:[`loading`,`error`,`crashed`,`cleaned-up`],loading:[`ready`,`error`,`crashed`,`cleaned-up`],ready:[`cleaned-up`,`crashed`],error:[`cleaned-up`,`idle`,`crashed`],crashed:[`cleaned-up`],"cleaned-up":[`loading`,`error`,`crashed`]}[e].includes(t)&&!(this.g2&&e===`error`&&t===`ready`))throw new ro(e,t,this.id)}setStatus(e,t=!1,n){if(e===`ready`&&!t)throw new Qa(q(208));this.validateStatusTransition(this.status,e),e===`loading`&&(this.b5=null);let r=++this.aV,i=this.status;this.status=e,n?.();let a=()=>this.aV===r;this.events.emitStatusChange(e,i,a),a()&&this.events.emitHealthChange()}validateCollectionUsable(e){switch(this.status){case`error`:case`crashed`:throw new $a(e,this.id);case`cleaned-up`:this.sync.startSync()}}markReady(e){if(this.status===`crashed`||this.bI)return;if(this.b6){this.completeReload(e);return}let t=this.d_(e);if(t){if(this.gn)this.gn(t);else throw t.error}}deferReadyFailures(){let e;return this.gn=t=>{e??=t},()=>(this.gn=void 0,e)}d_(e){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`||this.status===`error`){let t=this.aV+1;if(this.setStatus(`ready`,!0,e),this.status!==`ready`||this.aV!==t)return;let n=[];this.hasBeenReady||(this.hasBeenReady=!0,this.hasReceivedFirstCommit=!0,n.push(...this.onFirstReadyCallbacks),this.onFirstReadyCallbacks=[]),n.push(()=>this.changes.emitEmptyReadyEvent());try{Pu(n)}catch(e){return{error:e}}}}fail(e){if(this.status===`crashed`||this.bI)return;this.bI=!0;let t=this.b6;this.b6=void 0,this.status===`ready`?(this.failureReason=null,this.dk=ld([dd(e)]),this.events.emitHealthChange()):t&&this.status===`error`?(this.cc=ld([dd(e)]),this.events.emitHealthChange()):(this.validateStatusTransition(this.status,`error`),this.cc=ld([dd(e)]),this.setStatus(`error`)),t?.reject(e)}get stoppedThisRun(){return this.bI}get inFirstLoad(){return this.status===`loading`||this.reloading&&this.status===`error`}get reloading(){return this.b6!==void 0}beginReload(){if(this.b6)return this.b6.promise;let e=Uu();return e.promise.catch(()=>void 0),this.b6=e,this.a6=!1,this.bw=!1,this.bI=!1,this.events.emitHealthChange(),e.promise}completeReload(e){let t=this.b6;if(t){if(this.b6=void 0,this.a6||(this.failureReason=null),this.dk=null,this.bw||(this.cE=new cd),this.status===`ready`)this.events.emitHealthChange();else{this.cc=null,this.g2=!0;try{this.markReady(e)}catch(e){throw this.status===`ready`?t.resolve():t.reject(e),e}finally{this.g2=!1}}t.resolve()}}retireSubscriptionDemand(){for(let e of[...this.changes.changeSubscriptions])e.retireSyncRun()}abandonReload(e){this.g8(e)&&this.status!==`cleaned-up`&&this.events.emitHealthChange()}g8(e){let t=this.b6;return t?(this.b6=void 0,t.reject(e),!0):!1}crash(e){this.status!==`crashed`&&(this.validateStatusTransition(this.status,`crashed`),this.g8(e),this.cc=ld([dd(e)]),this.setStatus(`crashed`))}get problems(){let e=qu(this.status)?this.cc:this.dk??this.cE.problem;return{failureReason:e?null:this.failureReason,error:e}}get statusProblem(){return qu(this.status)?this.cc:null}reportError(e){if(this.status===`crashed`)return;this.d4(`reportError`),this.g5(`reportError`);let t=this.reloading&&!this.a6?[]:this.failureReason?.errors??[];t.some(t=>t.cause===e)||(this.failureReason=ld([...t,dd(e)]),this.a6=this.reloading,this.events.emitHealthChange())}reportHealthy(e){if(this.status===`crashed`)return;this.d4(`reportHealthy`),this.g5(`reportHealthy`);let t=this.failureReason?.errors??[],n=e===void 0?[]:t.filter(t=>t.cause!==e);n.length!==t.length&&(this.failureReason=n.length>0?ld(n):null,this.events.emitHealthChange())}reportRequestError(e,t){this.reloading&&!this.bw&&(this.cE=new cd,this.bw=!0),this.cE.fail(e,t)&&this.events.emitHealthChange()}clearRequestError(e){this.cE.settle(e)&&this.events.emitHealthChange()}d4(e){if(this.bI)throw new Qa(q(259,{operation:e,id:this.id}))}g5(e){if(this.status!==`ready`)throw new Qa(q(257,{operation:e,id:this.id,status:this.status}))}getSyncError(){return this.cc?.cause}hasStartedCleanup(){return this.dr||this.status===`cleaned-up`}assertCanStartSync(){if(this.dr)throw new Qa(q(209,{id:this.id}))}isCleaningUp(){return this.dr}onCleanupStart(e){if(this.bO.add(e),this.dr)try{e()}catch(t){throw this.bO.delete(e),t}return()=>this.bO.delete(e)}startGCTimerIfUnsubscribed(){this.aP=id()+50,this.startGCTimer(!0)}dA(){return!this.dr&&this.changes.activeSubscribersCount===0&&!this.sync.hasPendingPreload&&!this.state.hasPersistingTransaction()}startGCTimer(e=!1){if(e||(this.aP=0),this.status===`idle`||this.status===`cleaned-up`||(this.cancelGCTimer(),!this.dA()))return;let t=this.config.gcTime??3e5;t<=0||!Number.isFinite(t)||od.getInstance().schedule(this,Math.max(t,this.aP-id()),()=>{this.dA()&&this.eg()})}cancelGCTimer(){od.getInstance().cancel(this),this.aI!==null&&(rd(this.aI),this.aI=null)}eg(){this.aI!==null&&rd(this.aI),this.aI=nd(e=>{if(this.dA()){if(!(e.timeRemaining()>0||e.didTimeout)){this.eg();return}this.fe().catch(()=>void 0)}this.aI=null},{timeout:1e3})}fe(){if(this.b5)return this.b5;let e=Uu();this.b5=e.promise,this.dr=!0;let t=[],n,r=!0,i=e=>{try{e()}catch(e){t.push(e)}};for(let e of[...this.bO])i(e);let a=n=>{this.dr=!1,this.cc=null,i(()=>this.setStatus(`cleaned-up`)),this.changes.activeSubscribersCount===0&&i(()=>this.events.cleanup());let r=n?[n.error,...t]:t,a=r.length===0?void 0:{error:r.length===1?r[0]:AggregateError(r,q(173,{syncFailure:n!==void 0}),{cause:r[0]})};Promise.resolve().then(()=>Promise.resolve()).then(()=>{this.b5===e.promise&&(this.b5=null),a?e.reject(a.error):e.resolve()})};i(()=>this.fX());try{r=this.sync.cleanup(a)}catch(e){n={error:e}}i(()=>this.state.cleanup()),i(()=>this.changes.cleanup()),i(()=>this.indexes.cleanup()),this.hasBeenReady=!1;let o=this.problems,s=this.reloading;this.bI=!1,this.failureReason=null,this.dk=null,this.cE=new cd,this.abandonReload(new Ss);let c=this.problems;return s||o.error===c.error&&o.failureReason===c.failureReason||this.events.emitHealthChange(),this.onFirstReadyCallbacks=[],r&&a(n),e.promise}onFirstReady(e){return this.hasBeenReady?(e(),()=>{}):(this.onFirstReadyCallbacks.push(e),()=>{let t=this.onFirstReadyCallbacks.indexOf(e);t!==-1&&this.onFirstReadyCallbacks.splice(t,1)})}cleanup(){return this.cancelGCTimer(),this.fe()}},cd=class{constructor(){this.failed=new Map,this.open=new Map,this.problem=null}fail(e,t){let n=!1;for(let e of t){let t=this.open.get(e);t?t.requests++:(this.open.set(e,{failure:dd(e),requests:1}),n=!0)}return n=this.release(e)||n,this.failed.set(e,t),n&&this.hd()}settle(e){return this.release(e)&&this.hd()}release(e){let t=!1;for(let n of this.failed.get(e)??[]){let e=this.open.get(n);--e.requests===0&&(t=this.open.delete(n))}return this.failed.delete(e),t}hd(){let e=Array.from(this.open.values(),({failure:e})=>e);return this.problem=e.length>0?ld(e):null,!0}};function ld(e){let t=e[e.length-1];return ud({...t,errors:e},t.cause)}function ud(e,t){return Object.defineProperty(e,"cause",{value:t,enumerable:!1})}function dd(e){let t=`Error`,n=`Collection is in an error state`,r;try{e instanceof Error?(t=e.name,n=e.message):e!==void 0&&(n=String(e)),r=e?.code}catch{}return ud({name:t,message:n,...typeof r==`string`?{code:r}:{},at:Date.now()},e)}var fd=Symbol(`tanstack-db.sync-receipt.accepted`);function pd(e,t){return e[fd]=t,e}function md(e){return e===!0?!0:e[fd]??e}var hd=Symbol();function gd(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.is(e[n],t[n]))}var _d=class{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.aw=new Set,this.a5=new Set,this.bb=!1,this.bM=!1,this.ab=[],this.bZ=0,this.syncRunGeneration=0,this.bg=!1,this.cL=0,this.config=e,this.id=t,this.syncMode=e.syncMode??`eager`}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this.a3=e.events}f6(e,t,n){let r=n.value,i=this.f4??=new WeakMap;try{let a=i.get(r);if(a&&t===`update`&&!(`previousValue`in n)&&!gd(a,r))throw new Io(e);i.set(r,{...r})}catch(e){if(e instanceof Io)throw e;i.delete(r)}}du(e){let t=this.config.utils?.[Ns];return new fo(e,this.id,{hasCustomGetKey:t?.hasCustomGetKey??!1,hasJoins:t?.hasJoins??!1,hasDistinct:t?.hasDistinct??!1})}markLayoutChange(){this.aA().layoutChanged=!0}startSync(){if(this.lifecycle.assertCanStartSync(),this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`)return;if(this.bb){this.bM=!0;return}let e=++this.bZ;if(this.lifecycle.setStatus(`loading`),e!==this.bZ)return;let t=this.g9(e);if(t)throw t.error}reload(){let e=this.lifecycle.status;if(e===`crashed`)return Promise.reject(new to(this.id));try{this.lifecycle.assertCanStartSync()}catch(e){return Promise.reject(e)}if(this.lifecycle.reloading)return this.lifecycle.beginReload();if(e===`idle`||e===`cleaned-up`)return this.preload();if(this.bg||this.cL>0)return Promise.reject(new no(this.id));let t=++this.bZ,n=this.lifecycle.beginReload();if(this.retireSyncRun().catch(e=>this.lifecycle.crash(e)),this.lifecycle.retireSubscriptionDemand(),t!==this.bZ)return n;try{let e=this.g9(t);e&&Fu(e.error)}catch(e){this.lifecycle.abandonReload(e)}return n}g9(e){let t=()=>e===this.bZ,n=!1,r=this.lifecycle.deferReadyFailures(),i;this.bg=!0;try{let e=vd(this.config.sync.sync({collection:this.collection,begin:e=>{if(!t())return;let n=Uu();n.promise.catch(()=>void 0);let r=e?.snapshot===!0;this.state.pendingSyncedTransactions.push({committed:!1,applicationStarted:!1,layoutChanged:!1,operations:[],rowMetadataWrites:new Map,explicitRowMetadataWrites:new Map,collectionMetadataWrites:new Map,applied:n,duplicateKeyError:e=>this.du(e),truncate:r,truncateMarkReady:!1}),r&&this.state.refreshPendingSyncedProjection()},write:e=>{if(!t())return;let n=this.ar();if(!n)return;let r=`key`in e?e.key:this.config.getKey(e.value);Xs(r,e);let i=e.type;if(e.type===`insert`){let t=this.state.classifyPendingSyncedInsert(r,e.value);if(t===`duplicate`)throw this.du(r);i=t}`value`in e;let a={...e,type:i,key:r,originalSyncType:e.type===`insert`||e[hd]?`insert`:void 0};n.operations.push(a),this.state.stagePendingSyncOperation(a,n.preserveHydrationSeedKeys?.has(r));let o=Tu(a);o&&n.rowMetadataWrites.set(r,o)},commit:e=>{if(!t())return!0;let n=this.state.pendingSyncedTransactions.at(-1);if(!n)throw new Lo;if(n.committed)throw new Ro;return e?.aborted||n.invalidationError!==void 0?(this.state.cancelPendingSyncedTransaction(n,e?.aborted?void 0:n.invalidationError),n.applied.promise):(n.committed=!0,this.state.acceptSyncTransaction(n),!n.applied.isPending()||pd(n.applied.promise,!0))},markReady:()=>{t()&&this.lifecycle.markReady()},fail:e=>{t()&&this.lifecycle.fail(e)},reportError:e=>{t()&&this.lifecycle.reportError(e)},reportHealthy:e=>{t()&&this.lifecycle.reportHealthy(e)},truncate:e=>{if(!t())return;let n=this.ar();n&&(n.operations=[],n.rowMetadataWrites.clear(),n.explicitRowMetadataWrites.clear(),n.truncate=!0,n.truncateMarkReady=e?.markReady??!0,this.state.refreshPendingSyncedProjection())},invalidateLoadedSubsets:()=>{t()&&!n&&(n=!0,queueMicrotask(()=>{n=!1,t()&&this.a3.emit(`loadedSubsets:invalidated`,{type:`loadedSubsets:invalidated`,collection:this.collection})}))},metadata:this.eT(t)}));if(this.bg=!1,i=r(),!t())return e?.cleanup&&this.dW(e.cleanup),this.ck(),i;if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new Ka(q(210,{id:this.id}));this.lifecycle.startGCTimerIfUnsubscribed()}catch(e){throw this.bg=!1,this.ck(),r(),t()&&!this.lifecycle.stoppedThisRun&&this.lifecycle.crash(e),e}return i}deferStart(){return this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`?!1:(this.bb=!0,!0)}resumeStart(){if(!this.bb)return;this.bb=!1;let e=this.bM||this.ab.length>0;this.bM=!1;let t=this.ab;this.ab=[];let n=this.syncRunGeneration;try{e&&this.startSync()}catch(e){for(let{deferred:n}of t)n.reject(e);throw e}for(let{options:e,deferred:r}of t){let t=this.syncLoadSubsetFn;try{if(n!==this.syncRunGeneration||e.signal?.aborted)throw new Cs;let i=!t||this.g_(t,e);i instanceof Promise?i.then(e=>r.resolve(e),e=>r.reject(e)):r.resolve(void 0)}catch(e){r.reject(e)}}}aA(){let e=this.state.pendingSyncedTransactions.at(-1);if(!e)throw new Po;if(e.committed)throw new Fo;return e}ar(){let e=this.aA();return e.invalidationError===void 0?e:void 0}a8(e,t){let n=this.aA();n.explicitRowMetadataWrites.set(e,{position:n.operations.length,write:t}),n.rowMetadataWrites.set(e,t)}eT(e){return{persistence:null,row:{get:t=>{if(!e())return;let n=this.state.pendingSyncedTransactions;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.invalidationError!==void 0)continue;let i=r.rowMetadataWrites.get(t);if(i)return i.type===`delete`?void 0:i.value;if(wu(r,t))return}return this.state.syncedMetadata.get(t)},set:(t,n)=>{e()&&this.a8(t,{type:`set`,value:n})},delete:t=>{e()&&this.a8(t,{type:`delete`})}},collection:{get:t=>{if(!e())return;let n=this.state.pendingSyncedTransactions;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.invalidationError!==void 0)continue;let i=r.collectionMetadataWrites.get(t);if(i)return i.type===`delete`?void 0:i.value}return this.state.syncedCollectionMetadata.get(t)},set:(t,n)=>{e()&&this.aA().collectionMetadataWrites.set(t,{type:`set`,value:n})},delete:t=>{e()&&this.aA().collectionMetadataWrites.set(t,{type:`delete`})},list:t=>{if(!e())return[];let n=new Map(this.state.syncedCollectionMetadata);for(let e of this.state.pendingSyncedTransactions)if(e.invalidationError===void 0)for(let[t,r]of e.collectionMetadataWrites)r.type===`delete`?n.delete(t):n.set(t,r.value);return Array.from(n.entries()).filter(([e])=>!t||e.startsWith(t)).map(([e,t])=>({key:e,value:t}))}}}}get hasPendingPreload(){return this.cW!==void 0}preload(){try{this.lifecycle.assertCanStartSync(),this.bb&&this.resumeStart()}catch(e){return Promise.reject(e)}if(this.lifecycle.status===`ready`&&(this.lifecycle.cancelGCTimer(),this.lifecycle.startGCTimerIfUnsubscribed()),this.preloadPromise)return this.preloadPromise;let e=new Promise((e,t)=>{if(this.lifecycle.status===`ready`){e();return}if(qu(this.lifecycle.status)){t(this.d1());return}let n=!1,r={active:!1,ready:!1},i=()=>{},a=()=>{},o=()=>{n=!0,i(),a(),this.cW===c&&(this.cW=void 0),this.lifecycle.startGCTimerIfUnsubscribed()},s=()=>{r.active?r.ready=!0:n||(o(),e())},c=e=>{n||(o(),t(e))};this.cW=c,this.lifecycle.cancelGCTimer(),a=this.lifecycle.onFirstReady(s);let l=()=>{r.active||c(this.d1())},u=this.collection.on(`status:error`,l),d=this.collection.on(`status:crashed`,l);if(i=()=>{u(),d()},this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`){r.active=!0;let e;try{this.startSync()}catch(t){e={error:t}}finally{r.active=!1}qu(this.collection.status)?c(this.d1()):r.ready?(e&&Fu(e.error),s()):e&&c(e.error)}});return this.preloadPromise=e,e.then(void 0,()=>{this.preloadPromise===e&&(this.preloadPromise=null)}),e}d1(){let e=this.lifecycle.getSyncError();return e===void 0?new io:e}get isLoadingSubset(){return this.aw.size>0}beginLoadSubsetOperation(){let e=this.aa,t={pending:new Set,waiting:!1,completed:!1,hasError:!1};return this.aa=t,this.a5.add(t),{wait:()=>this.el(t),cancel:()=>{t.completed=!0,this.a5.delete(t),this.aa===t&&(this.aa=e?.completed?void 0:e)}}}el(e){return e.waiting=!0,e.pending.size===0?(this.gm(e),!e.hasError||Promise.reject(e.error)):(e.deferred=Uu(),e.deferred.promise)}c9(e,t,n){e.completed||(e.pending.delete(t),!n.ok&&!e.hasError&&(e.hasError=!0,e.error=n.error),!(!e.waiting||e.pending.size>0)&&queueMicrotask(()=>{e.completed||e.pending.size>0||(this.gm(e),e.hasError?e.deferred.reject(e.error):e.deferred.resolve())}))}gm(e){e.completed=!0,this.a5.delete(e),this.aa===e&&(this.aa=void 0)}gk(e){this.a3.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:e,previousIsLoadingSubset:!e,loadingSubsetTransition:e?`start`:`end`})}trackLoadSubsetOperationPromise(e){let t=this.aa;t&&!t.pending.has(e)&&(t.pending.add(e),e.then(()=>this.c9(t,e,{ok:!0}),n=>this.c9(t,e,{ok:!1,error:n})))}trackLoadPromise(e){let t=this.syncRunGeneration,n=!this.isLoadingSubset;this.aw.add(e),this.trackLoadSubsetOperationPromise(e),n&&this.gk(!0);let r=()=>{if(t!==this.syncRunGeneration)return;let n=this.aw.size===1&&this.aw.has(e);this.aw.delete(e),n&&this.gk(!1)};e.then(r,r)}getSyncRunGeneration(){return this.syncRunGeneration}loadSubset(e){if(e.signal?.aborted)return Promise.reject(new Cs);if(this.syncMode===`eager`)return!0;if(this.bb){this.bM=!0;let t=Uu();return this.ab.push({options:e,deferred:t}),this.trackLoadPromise(t.promise),t.promise}if(this.syncLoadSubsetFn){let t=this.g_(this.syncLoadSubsetFn,e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}g_(e,t){this.cL++;try{return e(t)}catch(e){return Promise.reject(e)}finally{this.cL--}}unloadSubset(e){this.syncMode!==`eager`&&(this.bb?this.ab=this.ab.filter(t=>t.options!==e||(t.deferred.reject(new Cs),!1)):this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e))}eC(e){let t=new bs(this.id,e);return t.cause=e,e instanceof Error&&(t.stack=e.stack),t}e3(e){if(!e)return!0;try{let t=e();return!jc(t)||Promise.resolve(t).then(()=>void 0,e=>{throw this.eC(e)})}catch(e){throw this.eC(e)}}dW(e){let t=this.bE;if(t)try{let n=this.e3(e);n!==!0&&(t.tasks.push(n),n.catch(()=>void 0))}catch(e){t.failure??={error:e}}}ck(){let e=this.bE;if(!e)return;this.bE=void 0;let t=t=>{let n=e.failure??t;e.onSettled?.(n),n?e.completion?.reject(n.error):e.completion?.resolve()};e.tasks.length===0?t():Promise.allSettled(e.tasks).then(e=>{let n=e.find(e=>e.status===`rejected`);t(n?{error:n.reason}:void 0)})}retireSyncRun(){this.syncRunGeneration++,this.state.discardOpenSyncTransactions();let e=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.dp();try{let t=this.e3(e);return t===!0?Promise.resolve():t}catch(e){return Promise.reject(e)}}dp(){let e=this.aw.size>0;this.aw.clear(),e&&this.gk(!1),this.aa=void 0;for(let e of this.a5)e.completed||(e.completed=!0,e.pending.clear(),e.hasError=!0,e.error=new Cs,e.deferred?.reject(e.error));this.a5.clear();let t=this.ab;this.ab=[];for(let e of t)e.deferred.reject(new Cs)}cleanup(e){++this.bZ,this.syncRunGeneration++,this.cW?.(new Ss);let t=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null;let n=!0,r;try{n=this.e3(t)}catch(e){r={error:e}}if(this.preloadPromise=null,this.bb=!1,this.bM=!1,this.dp(),this.bg){let t=e?void 0:Uu(),i={tasks:[],failure:r,onSettled:e,completion:t};return n!==!0&&(i.tasks.push(n),n.catch(()=>void 0)),this.bE=i,!e&&t.promise}if(r)throw r.error;return n===!0?!0:e?(n.then(()=>e(),t=>e({error:t})),!1):n}};function vd(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var yd=new WeakMap,bd=1;function xd(e){if(!Js(e))return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype}function Sd(e,t){return e===t?0:e<t?-1:1}function Cd(e){let t=yd.get(e)??e.name;return{kind:`constructor`,...t?{name:t}:{}}}function wd(e){if(e==null)return e;switch(typeof e){case`string`:case`boolean`:return e;case`number`:return Number.isFinite(e)?e:null;case`bigint`:return{__type:`bigint`,value:e.toString()};case`function`:case`symbol`:return;case`undefined`:return}if(Array.isArray(e))return e.map(e=>wd(e)??null);if(xd(e))return{__type:e[Symbol.toStringTag],value:String(e)};if(e instanceof Date)return{__type:`date`,value:e.toISOString()};if(e instanceof Set)return{__type:`set`,values:Array.from(e).map(e=>wd(e)??null).sort((e,t)=>Sd(Td(e),Td(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:wd(e)??null,value:wd(t)??null})).sort((e,t)=>Sd(Td(e.key),Td(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>Sd(e,t));for(let[e,r]of n){let n=wd(r);n!==void 0&&(t[e]=n)}return Object.hasOwn(t,`__type`)?{__type:`object`,value:t}:t}function Td(e){return e===null?`null`:Array.isArray(e)?`[${e.map(Td).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>Sd(e,t)).map(t=>`${JSON.stringify(t)}:${Td(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function Ed(e,t,n,r,i){let a=Cd(r),o=wd(t)??null,s=wd(i);return{signatureVersion:bd,signature:Td({signatureVersion:bd,expression:o,options:s??null}),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function Dd(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>Dd(e));let t={};for(let[n,r]of Object.entries(e))t[n]=Dd(r);return t}function Od(e){return xd(e)?e:e instanceof Date?new Date(e.getTime()):Array.isArray(e)?e.map(Od):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Od(t)])):e}function kd(e){return Od(e)}var Ad=class{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle,this.defaultIndexType=e.defaultIndexType,this.events=e.events}createIndex(e,t={}){this.lifecycle.validateCollectionUsable(`createIndex`);let n=++this.indexCounter,r=X(e(Ll())),i=t.indexType??this.defaultIndexType;if(!i)throw new Ka(q(207));let a=new i(n,r,t.name,t.options);a.build(this.state.entries()),this.indexes.set(n,a);let o=Ed(n,r,t.name,i,t.options);return this.indexMetadata.set(n,o),this.events.emitIndexAdded(o),a}removeIndex(e){this.lifecycle.validateCollectionUsable(`removeIndex`);let t=typeof e==`number`?e:e.id,n=this.indexes.get(t);if(!n||typeof e!=`number`&&n!==e)return!1;this.indexes.delete(t);let r=this.indexMetadata.get(t);return this.indexMetadata.delete(t),r&&this.events.emitIndexRemoved(r),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:kd(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:Dd(e.options)}}))}updateIndexes(e){try{for(let t of this.indexes.values())for(let n of e)switch(n.type){case`insert`:t.add(n.key,n.value);break;case`update`:n.previousValue?t.update(n.key,n.previousValue,n.value):t.add(n.key,n.value);break;case`delete`:t.remove(n.key,n.value)}}catch(e){throw this.lifecycle.crash(e),e}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}},jd=new WeakMap;function Md(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}function Nd(e){return typeof e==`object`&&e?jd.get(e)??e:e}var Pd=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`,`set`]),Fd=new Set([`entries`,`keys`,`values`,`forEach`]);function Id(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!Js(e)}function Ld(e,t,n,r){return function(...i){let a=e.apply(t.copy_,i);return n(t),a===t.copy_?r:a}}function Rd(e,t,n,r,i){if(Fd.has(e)||t===Symbol.iterator)return(...a)=>{let o=n.copy_,s=o instanceof Map;if(s&&e===`keys`)return o.keys();let c=e=>Id(e)?i(e,{tracker:n,prop:``,retainIdentity:!0}).proxy:e;if(e===`forEach`){let e=a[0];if(typeof e!=`function`)throw TypeError(q(109));return o.forEach((t,n)=>{let i=c(t);e.call(a[1],i,s?n:i,r)})}let l=o.entries(),u=e===`entries`||s&&t===Symbol.iterator;return{next(){let e=l.next();if(e.done)return e;let[t,n]=e.value,r=c(n);return{done:!1,value:u?[s?t:r,r]:r}},[Symbol.iterator](){return this}}}}function zd(e,t=new WeakMap,n=!1){if(e=Nd(e),typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);if(e instanceof Date){let n=new Date(e.getTime());return t.set(e,n),n}if(e instanceof RegExp){let n=new RegExp(e.source,e.flags);return n.lastIndex=e.lastIndex,t.set(e,n),n}if(e instanceof URL){let n=new URL(e.href);return t.set(e,n),n}if(Array.isArray(e)){let r=Array(e.length);return t.set(e,r),e.forEach((e,i)=>{r[i]=zd(e,t,n)}),r}let r=Object.prototype.toString.call(e),i=r===`[object ArrayBuffer]`?ArrayBuffer:r===`[object SharedArrayBuffer]`&&typeof SharedArrayBuffer<`u`?SharedArrayBuffer:void 0;if(i){let n;try{n=Object.getOwnPropertyDescriptor(i.prototype,`byteLength`).get.call(e)}catch{}if(n!==void 0){let r=new i(n);return new Uint8Array(r).set(new Uint8Array(e)),t.set(e,r),r}}if(ArrayBuffer.isView(e)){let r=zd(e.buffer,t,n),i=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get.call(e);if(i===void 0){let n=new DataView(r,e.byteOffset,e.byteLength);return t.set(e,n),n}let a=Object.getPrototypeOf(e).constructor,o=e.length,s=Function.prototype.toString.call(a)===Function.prototype.toString.call(globalThis[i])?new a(r,e.byteOffset,o):new a(o);return t.set(e,s),s.set(e),s}if(e instanceof Map){let r=new Map;return t.set(e,r),e.forEach((e,i)=>{r.set(i,zd(e,t,n))}),r}if(e instanceof Set){let r=new Set;return t.set(e,r),e.forEach(e=>{r.add(zd(e,t,n))}),r}if(Js(e))return e;if(n){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e}let a={};t.set(e,a);for(let r of Reflect.ownKeys(e))(typeof r==`symbol`||Object.prototype.propertyIsEnumerable.call(e,r))&&Md(a,r,zd(e[r],t,n));return a}function Bd(e,t,n){return Ks(e,t,5,n)}function Vd(e,t){let n=new Map;function r(e,t){if(n.has(e))return n.get(e);{let r=Vd(e,t);return n.set(e,r),r}}let i=t?.tracker.valueCopies??new WeakMap,a={valueCopies:i,copy_:t?i.get(e)??e:zd(e,i),originalObject:t?zd(e):e,modified:!1,assigned_:Object.create(null),parent:t,target:e};function o(e){e.modified||=!0,e.parent&&(!e.parent.retainIdentity&&e.parent.tracker.copy_[e.parent.prop]===e.copy_&&(e.parent.tracker.assigned_[e.parent.prop]=!0),o(e.parent.tracker))}function s(e){if(e.copy_ instanceof Map||e.copy_ instanceof Set)return Bd(Array.from(e.copy_),Array.from(e.originalObject));for(let t in e.assigned_)if(!e.assigned_[t]||Object.hasOwn(e.copy_,t)!==Object.hasOwn(e.originalObject,t)||!Bd(e.copy_[t],e.originalObject[t]))return!1;return!0}function c(e){if(s(e)){e.modified=!1,e.assigned_=Object.create(null);let t=e.parent;t&&(Bd(t.tracker.copy_[t.prop],t.tracker.originalObject[t.prop])&&delete t.tracker.assigned_[t.prop],c(t.tracker))}}function l(e,t){let n=a.originalObject;return Object.hasOwn(n,e)&&Bd(t,n[e])}function u(e,t){t?(delete a.assigned_[e.toString()],a.modified=!0,c(a)):(a.assigned_[e.toString()]=!0,o(a))}let d=new Proxy(a.copy_,{get(e,t,n){let s=a.copy_[t],c=Object.getOwnPropertyDescriptor(e,t);if(c?.get)return s;if(c?.configurable===!1&&!c.writable)return Id(s)&&(a.assigned_[String(t)]=!0,o(a)),s;if(typeof s==`function`){if(Object.hasOwn(e,t)||t===`constructor`)return s;let c=t.toString();if(c===`subarray`&&ArrayBuffer.isView(e))return(...t)=>r(s.apply(e,t),{tracker:a,prop:``,retainIdentity:!0}).proxy;if(Pd.has(c)&&(Array.isArray(e)||ArrayBuffer.isView(e)))return Ld(s,a,o,n);if(Array.isArray(e))return s.bind(n);if(e instanceof Map||e instanceof Set){let l=e=>{let t=Nd(e);return typeof t==`object`&&t?i.get(t)??t:t};if(c===`has`||c===`delete`||c===`add`||c===`set`)return(...t)=>{e instanceof Set?t[0]=l(t[0]):c===`set`&&(t[1]=l(t[1]));let r=s.apply(e,t);return c!==`has`&&o(a),r===e?n:r};if(e instanceof Map&&c===`get`)return t=>{let n=e.get(t);return Id(n)?r(n,{tracker:a,prop:``,retainIdentity:!0}).proxy:n};if(c===`clear`)return Ld(s,a,o,n);let u=Rd(c,t,a,n,r);if(u)return u}return s.bind(e)}return Id(s)?r(s,{tracker:a,prop:String(t)}).proxy:s},set(e,t,n){if(Reflect.getOwnPropertyDescriptor(e,t)?.get)return Reflect.set(e,t,n);let r=a.copy_[t];if(!Object.hasOwn(a.copy_,t)||!Bd(r,n)){let e=l(t,n);a.copy_[t]=e?zd(a.originalObject[t]):n,u(t,e)}return!0},defineProperty(e,t,n){let r=Reflect.defineProperty(e,t,n);return r&&(`value`in n||n.get||n.set)&&u(t,l(t,Reflect.get(e,t))),r},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(e,t)},preventExtensions(e){return Reflect.preventExtensions(e)},isExtensible(e){return Reflect.isExtensible(e)},deleteProperty(e,t){let n=typeof t==`symbol`?t.toString():t;if(Object.hasOwn(e,t)){let r=Object.prototype.propertyIsEnumerable.call(a.originalObject,t),i=Reflect.deleteProperty(e,t);return i&&(r?(a.assigned_[n]=!1,o(a)):(delete a.assigned_[n],a.modified=!0,c(a))),i}return!0}});return jd.set(d,a.copy_),{proxy:d,getChanges:()=>{if(!a.modified)return{};if(typeof a.copy_!=`object`||Array.isArray(a.copy_)||Object.keys(a.assigned_).length===0)return a.copy_;let e={},t=Object.keys(a.assigned_).some(e=>typeof a.copy_[e]==`object`||typeof a.originalObject[e]==`object`),n=new Map([[a.copy_,a.originalObject]]);for(let r in a.copy_){let i=a.copy_[r],o=a.originalObject[r];(a.assigned_[r]===!0||t&&!Bd(i instanceof Set?Array.from(i):i,o instanceof Set?Array.from(o):o,n))&&Md(e,r,a.copy_[r])}for(let t of Object.keys(a.assigned_))a.assigned_[t]===!1&&Md(e,t,void 0);return e}}}function Hd(e){let t=e.map(e=>Vd(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function Ud(e,t){let{proxy:n,getChanges:r}=Vd(e);return t(n),zd(r(),void 0,!0)}function Wd(e,t){let{proxies:n,getChanges:r}=Hd(e);return t(n),zd(r(),void 0,!0)}function Gd(e){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1;for(let t in e){let{value:n,get:r}=Object.getOwnPropertyDescriptor(e,t);if(r||typeof n==`object`&&n)return!1}return Object.getOwnPropertySymbols(e).length===0}function Kd(e,t,n){if(!e.every(Gd))return;let r=e.map(e=>({...e}));return t(n?r:r[0]),r.map((t,n)=>{let r=e[n],i={},a=!1;for(let e in t){let n=t[e],o=r[e];Object.hasOwn(r,e)&&Bd(n,o)||(Md(i,e,n),typeof n==`object`&&n&&(a=!0))}for(let e in r)Object.hasOwn(t,e)||Md(i,e,void 0);return a?zd(i,void 0,!0):i})}var qd=new WeakMap;function Jd(e){let t=qd.get(e);if(t)return qd.delete(e),Promise.allSettled(t).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason})}var Yd=new class{constructor(){this.transactions=[],this.bm=[],this.sequenceNumber=0}createTransaction(e){let t=new of(e,this,this.sequenceNumber++);return this.transactions.push(t),t}getActiveTransaction(){return this.bm.at(-1)}getActiveTransactionForCollection(){let e=this.getActiveTransaction();if(e)return e;if(this!==Yd)return Yd.eJ(this)}eJ(e){let t=this.getActiveTransaction();if(!t)return;let n=Qd(t);if(n===e)return t;if(n!==this)throw Error(q(162));return this.removeTransaction(t),e.transactions.push(t),e.bm.push(t),t.sequenceNumber=e.sequenceNumber++,Xd.set(t,e),t}registerTransaction(e){Du.clear(e.id),this.bm.push(e)}unregisterTransaction(e,t=!1){try{Du.flush(e.id)}finally{t||this.clearTransactionContext(e)}}clearTransactionContext(e){let t=this.bm.lastIndexOf(e);t!==-1&&this.bm.splice(t,1)}removeTransaction(e){let t=this.transactions.indexOf(e);t!==-1&&this.transactions.splice(t,1)}rollbackConflictingTransactions(e,t){let n=[];for(let r of[...this.transactions])if(r!==e&&r.state===`pending`&&r.mutations.some(e=>t.has(e.globalKey)))try{r.rollback({isSecondaryRollback:!0})}catch(e){n.push(e)}if(n.length>0)throw n[0]}clear(){let e=new Set([...this.transactions.map(e=>e.id),...this.bm.map(e=>e.id)]);for(let t of e)Du.clear(t);this.transactions=[],this.bm=[]}},Xd=new WeakMap,Zd=new WeakMap;function Qd(e){let t=Xd.get(e);if(!t)throw Error(q(163));return t}function $d(e){let t=Zd.get(e);if(!t)throw Error(q(164));return t}function ef(e,t){switch(t.type){case`update`:{if(e.type===`delete`)break;let n=e.type===`insert`;return{...n?e:t,original:n?{}:e.original,modified:t.modified,changes:{...e.changes,...t.changes},metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt}}case`delete`:return e.type===`insert`?null:t;case`insert`:{if(e.type===`insert`)return t;if(e.type!==`delete`)break;let n=e.collection._state.syncedData.get(e.key);if(n===void 0)return t;if(Vs(n,t.modified))return null;let r=t.modified,i=new Set([...Object.keys(n),...Object.keys(r)]),a={};for(let e of i)Object.hasOwn(n,e)===Object.hasOwn(r,e)&&Vs(n[e],r[e])||(a[e]=r[e]);return{...t,type:`update`,original:n,changes:a,metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata}}}}let n=`${e.type}-${t.type}`;throw Error(q(165,{combination:n}))}function tf(e){return Yd.createTransaction(e)}function nf(){return Yd.getActiveTransaction()}var rf=new WeakMap;function af(e){return rf.get(e)}var of=class{constructor(e,t,n){if(this.collections=new Set,e.mutationFn===void 0)throw new ko;this.id=e.id??za(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[];let r=Uu();rf.set(this,r),r.promise.catch(()=>void 0),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=n,this.metadata=e.metadata??{},Xd.set(this,t),Zd.set(this,t)}when(e){return af(this).promise}completeWithoutCommit(){if(this.state!==`pending`)throw new No;this.setState(`completed`),af(this).resolve(this)}setState(e){this.state=e,(e===`completed`||e===`failed`)&&Qd(this).removeTransaction(this)}mutate(e){if(this.state!==`pending`)throw new Ao;let t=Qd(this),n=new Set([t,$d(this)]);for(let e of n)e.registerTransaction(this);let r,i=this.gq;this.gq=()=>{i?.(),r??=[...this.mutations]};let a=!1;try{e()}catch(e){let t=r??this.mutations,i=new Set([...t,...this.mutations].map(e=>e.collection));r&&this.mutations.splice(0,this.mutations.length,...r),n.add(Qd(this));for(let e of n)e.clearTransactionContext(this);a=!0;let o=[];for(let e of i)try{e._state.onTransactionStateChange()}catch(e){o.push(e)}throw o.length?AggregateError([e,...o],q(174),{cause:e}):e}finally{this.gq=i,n.add(Qd(this));for(let e of n)e.unregisterTransaction(this,a)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){this.gq?.();let t=new Map;for(let e of this.mutations)t.set(e.globalKey,e);for(let n of e){let e=n.globalKey,r=t.get(e),i=r?ef(r,n):n;i===null?t.delete(e):t.set(e,i)}this.mutations.length=0;for(let e of t.values())this.mutations.push(e)}rollback(e){let t=e?.isSecondaryRollback??!1;if(this.state===`completed`)throw new jo;if(this.state===`failed`)return this;e?.error&&(this.error={message:e.error.message,error:e.error});let n=this.state===`persisting`;this.setState(`failed`);try{if(!t){let e=new Set(this.mutations.map(e=>e.globalKey));Qd(this).rollbackConflictingTransactions(this,e)}}finally{af(this).reject(this.error?.error),this.touchCollection(n)}return this}touchCollection(e=!1){let t=new Set(this.collections);for(let e of this.mutations)t.add(e.collection);(this.state===`completed`||this.state===`failed`)&&this.collections.clear();let n=[];for(let r of t)try{r._state.onTransactionStateChange(),e&&r._lifecycle.startGCTimer(!0),r._state.pendingSyncedTransactions.length>0&&r._state.commitPendingTransactions()}catch(e){n.push(e)}if(n.length>0)throw n[0]}async commit(){if(this.state!==`pending`)throw new No;if(this.setState(`persisting`),this.mutations.length>0){try{await this.mutationFn({transaction:this});let e=Jd(this);e&&await e}catch(e){if(this.state!==`persisting`)return this;let t=Hu(e);try{await Jd(this)}catch{}this.error={message:t.message,error:t};try{this.rollback()}catch{}throw t}if(this.state!==`persisting`)return this}this.setState(`completed`);try{this.touchCollection(!0)}finally{af(this).resolve(this)}return this}compareCreatedAt(e){let t=this.createdAt.getTime()-e.createdAt.getTime();return t===0?this.sequenceNumber-e.sequenceNumber:t}},sf,cf=0;function lf(){return sf??=za(),`${sf}-${++cf}`}var uf=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=this.getActiveTransaction();if(!r&&!this.config.onInsert)throw new bo;let i=Array.isArray(e)?e:[e],a=new Date,o=[],s=new Set;i.forEach(e=>{let n=this.validateData(e,`insert`),r=this.config.getKey(n);if(s.has(r))throw new uo(r);s.add(r);let i=this.generateGlobalKey(r,e),c={mutationId:lf(),original:{},modified:n,changes:Object.fromEntries(Object.keys(e).map(e=>[e,n[e]])),globalKey:i,key:r,metadata:t?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:t?.optimistic??!0,type:`insert`,createdAt:a,updatedAt:a,collection:this.collection};o.push(c)});let c=o.find(({key:e})=>n.has(e));if(c||(this.collection._sync.startSync(),c=o.find(({key:e})=>n.has(e)),c))throw new uo(c.key);return r?(this.bX(r,o),r):this.cn(`insert`,e=>this.config.onInsert(e),o)},this.delete=(e,t)=>{let n=this.state;this.lifecycle.validateCollectionUsable(`delete`);let r=this.getActiveTransaction();if(!r&&!this.config.onDelete)throw new So;if(Array.isArray(e)&&e.length===0)throw new _o;let i=Array.isArray(e)?e:[e];this.collection._sync.startSync();let a=new Date,o=[];for(let e of i){if(!this.state.has(e))throw new vo(e);let r=this.generateGlobalKey(e,this.state.get(e)),i={mutationId:lf(),original:this.state.get(e),modified:this.state.get(e),changes:this.state.get(e),globalKey:r,key:e,metadata:t?.metadata,syncMetadata:n.syncedMetadata.get(e)||{},optimistic:t?.optimistic??!0,type:`delete`,createdAt:a,updatedAt:a,collection:this.collection};o.push(i)}return r?(this.bX(r,o),r):this.cn(`delete`,e=>this.config.onDelete(e),o)},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}setTransactionScope(e){this.fR=e}getActiveTransaction(){return this.fR?this.fR.getActiveTransactionForCollection():nf()}createTransaction(e){return this.fR?this.fR.createTransaction(e):tf(e)}eX(e){if(e&&`~standard`in e)return e;throw new Xa}validateData(e,t,n){if(!this.config.schema)return e;let r=this.eX(this.config.schema);if(t===`update`&&n){let i=this.state.get(n);if(i&&e&&typeof e==`object`&&typeof i==`object`){let n={...i,...e},a=r[`~standard`].validate(n);if(a instanceof Promise)throw new Za;if(`issues`in a&&a.issues)throw new Ga(t,a.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));let o=a.value,s=Object.keys(e);return Object.fromEntries(s.map(e=>[e,o[e]]))}}let i=r[`~standard`].validate(e);if(i instanceof Promise)throw new Za;if(`issues`in i&&i.issues)throw new Ga(t,i.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));return i.value}generateGlobalKey(e,t){return Xs(e,t),`KEY::${JSON.stringify([this.id,typeof e,String(e)])}`}f7(e,t){let n=this.state.localOnlyDirectWrite;if(!n?.types.has(t))return;for(let e of this.state.transactions.values())if(e.state===`pending`||e.state===`persisting`)return;let r=this.createTransaction({autoCommit:!1,mutationFn:()=>Promise.resolve()});r.applyMutations(e);try{n.write(e)}finally{r.completeWithoutCommit()}return r}bX(e,t){this.state.trackTransaction(e),e.applyMutations(t),this.state.recomputeOptimisticState(!0)}cn(e,t,n){let r=this.f7(n,e);if(r)return r;let i=this.createTransaction({mutationFn:async e=>await t({transaction:e.transaction,collection:this.collection})});try{this.bX(i,n)}catch(e){try{i.rollback({isSecondaryRollback:!0,error:Hu(e)})}catch{}throw e}return i.commit().catch(()=>void 0),i}update(e,t,n){if(e===void 0)throw new po;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=this.getActiveTransaction();if(!i&&!this.config.onUpdate)throw new xo;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new mo;let s=typeof t==`function`?t:n;if(typeof s!=`function`)throw TypeError();let c=typeof t==`function`?{}:t;this.collection._sync.startSync();let l=o.map(e=>{let t=this.state.get(e);if(!t)throw new ho(e);return t}),u=Kd(l,s,a)??(a?Wd(l,s):[Ud(l[0],s)]),d=new Date,f=o.map((e,t)=>{let n=u[t];if(!n||Object.keys(n).length===0)return null;let i=l[t],a=this.validateData(n,`update`,e),o={...i,...a},s=this.config.getKey(i),f=this.config.getKey(o);if(s!==f)throw new go(s,f);let p=this.generateGlobalKey(f,o);return{mutationId:lf(),original:i,modified:o,changes:a===n?n:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),globalKey:p,key:e,metadata:c.metadata,syncMetadata:r.syncedMetadata.get(e)||{},optimistic:c.optimistic??!0,type:`update`,createdAt:d,updatedAt:d,collection:this.collection}}).filter(Boolean);if(f.length===0){let e=this.createTransaction({mutationFn:async()=>{}});return e.commit().catch(()=>void 0),e}return i?(this.bX(i,f),i):this.cn(`update`,e=>this.config.onUpdate(e),f)}},df=class extends Iu{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t,n){if(this.emitInnerWhile(`status:change`,{type:`status:change`,collection:this.collection,previousStatus:t,status:e},n),!n())return;let r=`status:${e}`;this.emitInnerWhile(r,{type:r,collection:this.collection,previousStatus:t,status:e},n)}emitHealthChange(){this.emit(`health:change`,{type:`health:change`,collection:this.collection})}emitSubscribersChange(e,t){this.emit(`subscribers:change`,{type:`subscribers:change`,collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}emitIndexAdded(e){this.emit(`index:added`,{type:`index:added`,collection:this.collection,index:e})}emitIndexRemoved(e){this.emit(`index:removed`,{type:`index:removed`,collection:this.collection,index:e})}cleanup(){this.clearListeners()}},ff=new WeakMap;function pf(e,{alias:t,id:n,kind:r}={alias:`root`},i=e){let a=Ls(e),o=a?.healthSources()??[],{failureReason:s,error:c}=e._lifecycle.problems,l=o.map(t=>pf(t.collection,t,e));return mf(i,n,{alias:t,collectionId:e.id,kind:r??(a?`live-query`:`source`),status:e.status,failureReason:s,error:c,reloading:e._lifecycle.reloading,sources:l})}function mf(e,t,n){let{failureReason:r,error:i,sources:a}=n;return gf(e,t??n.alias,{...n,hasErrors:r!==null||i!==null||a.some(e=>e.hasErrors)})}function hf(e){return e.hasErrors?[...e.failureReason!==null||e.error!==null?[e]:[],...e.sources.flatMap(hf)]:[]}function gf(e,t,n){let r=ff.get(e);r||ff.set(e,r=new Map);let i=r.get(t);return i&&_f(i,n)?i:(r.set(t,n),n)}function _f(e,t){return e.collectionId===t.collectionId&&e.kind===t.kind&&e.status===t.status&&e.hasErrors===t.hasErrors&&e.failureReason===t.failureReason&&e.error===t.error&&e.reloading===t.reloading&&e.sources.length===t.sources.length&&e.sources.every((e,n)=>e===t.sources[n])}var vf=Symbol.for(`@tanstack/db.collectionSyncConfig.factory`),yf=Symbol.for(`@tanstack/db.collectionSyncConfig.cleanup`);function bf(e,t){return Object.defineProperty(e,vf,{value:t,enumerable:!0}),e}function xf(e,t,n){let r=e[vf];if(!r)return{sync:e,utilities:t};let i=Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t));return{sync:r(e,i,n),utilities:i}}function Sf(e){let t=e[yf];t?.()}function Cf(e){let t=e[Ha];return wf(e,t?.())}function wf(e,t){try{return new Tf(e)}catch(e){throw t?.(),e}}var Tf=class{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(e,t)=>this.cS.insert(e,t),this.delete=(e,t)=>this.cS.delete(e,t),!e)throw new Ja;if(!e.sync)throw new Ya;this.id=e.id?e.id:za();let{sync:t,utilities:n}=xf(e.sync,e.utils??{},()=>{this._lifecycle.status===`idle`&&this._sync.startSync()});this.config={...e,sync:t,autoIndex:e.autoIndex??`off`,utils:n},this.utils=n,Rs(e),ui(this),this.cC=new $u,this.a3=new df,this.dd=new Ad,this._lifecycle=new sd(this.config,this.id,()=>Sf(this.config.sync)),this.cS=new uf(this.config,this.id),this._state=new Eu(this.config),this._sync=new _d(this.config,this.id),this.eS=Ef(e),this.cC.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this.a3,state:this._state}),this.a3.setDeps({collection:this}),this.dd.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this.a3}),this._lifecycle.setDeps({changes:this.cC,events:this.a3,indexes:this.dd,state:this._state,sync:this._sync}),this.cS.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this.cC,indexes:this.dd,events:this.a3}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this.a3}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get health(){return pf(this)}_emitHealthChange(){this.a3.emitHealthChange()}get subscriberCount(){return this.cC.acquiringSubscribersCount}get _stateRevision(){return this.cC.stateRevision}get _layoutRevision(){return this.cC.layoutRevision}_subscribeLayoutChanges(e){return this.cC.subscribeLayoutChanges(e)}_markLayoutChange(){this._sync.markLayoutChange()}_deferPublication(){return this.cC.deferPublication()}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}_onCleanupStart(e){return this._lifecycle.onCleanupStart(e)}_setTransactionScope(e){this.cS.setTransactionScope(e)}_hasHydratedKey(e){return this._state.hydratedKeys.has(e)}_deferSyncStart(){return this._sync.deferStart()}_resumeSyncStart(){this._sync.resumeStart()}preload(){return this.gz(()=>this._sync.preload())}gz(e){try{this._markPreload()}catch(e){return Promise.reject(e)}return e()}_markPreload(){this.cC.markSubscriberOrPreload()}_hasSubscriberOrPreload(){return this.cC.hasSubscriberOrPreload()}_onFirstSubscriberOrPreload(e){return this.cC.onFirstSubscriberOrPreload(e)}get base(){return this._state.syncedData}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}_optimisticOverlaySize(){return this._state.optimisticDeletes.size+this._state.optimisticUpserts.size}_hasOptimisticOverlay(e){return this._state.optimisticDeletes.has(e)||this._state.optimisticUpserts.has(e)}_hasHeldSyncTransaction(){return this._state.hasHeldSyncTransaction()}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this.dd.createIndex(e,t)}removeIndex(e){return this.dd.removeIndex(e)}getIndexMetadata(){return this.dd.getIndexMetadataSnapshot()}get indexes(){return this.dd.indexes}validateData(e,t,n){return this.cS.validateData(e,t,n)}get compareOptions(){return{...this.eS}}update(e,t,n){return this.cS.update(e,t,n)}get state(){let e=new Map;for(let[t,n]of this.entries())e.set(t,n);return e}stateWhenReady(){return this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return vu(this,e,e=>this._state.entriesPassing(e))}subscribeChanges(e,t={}){return this.cC.subscribeChanges(t=>e(t),t)}on(e,t){return this.a3.on(e,t)}once(e,t){return this.a3.once(e,t)}off(e,t){this.a3.off(e,t)}waitFor(e,t){return this.a3.waitFor(e,t)}reload(){let e=Fs(this.config);return e?e.reload(this):this._sync.reload()}get subscribers(){let e=new Set;for(let t of this.cC.changeSubscriptions)e.add(t.owner??{kind:`subscription`,active:!0,end:()=>(t.unsubscribe(),Promise.resolve())});return[...e]}cleanup(e){let t=this.subscribers.filter(e=>e.kind!==`subscription`);if(!e?.dependents){let e=t.filter(e=>e.active);return e.length>0?Promise.reject(new eo(this.id,e.length)):this._lifecycle.cleanup()}let n=t.map(async e=>e.end());return Promise.allSettled([this._lifecycle.cleanup(),...n]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason})}};function Ef(e){let t=e.defaultStringCollation;return t?t.stringSort===`lexical`?{stringSort:`lexical`}:t.stringSort===`custom`?{stringSort:`custom`,compare:t.compare}:{stringSort:`locale`,...`locale`in t&&t.locale!==void 0&&{locale:t.locale},...`localeOptions`in t&&t.localeOptions!==void 0&&{localeOptions:t.localeOptions}}:{stringSort:`locale`}}function Df(e,t,n){let r=e.get(t);return r===void 0&&(r=n(),e.set(t,r)),r}function Of(e){if(typeof e==`object`&&e){if(Array.isArray(e))for(let t of e){let e=Of(t);if(e)return e}else{if(e instanceof ar)return e;if(e instanceof ir)return Of(e.args);if(e instanceof cr)return Of([e.branches,e.defaultValue]);if(!ur(e))return Of(Object.values(e))}}}function kf(e){if(e.from.type===`unionAll`)return{optimizedQuery:{...e,from:new er(e.from.queries.map(e=>kf(e).optimizedQuery))},sourceWhereClauses:new Map};let t=Af(e),n=e,r,i=0;for(;i<10&&!Bs(n,r);)r=n,n=Nf(n),i++;return{optimizedQuery:Ff(n),sourceWhereClauses:t}}function Af(e){let t=new Map;if(!e.where||e.where.length===0)return t;let n=zf(e.where),r=Vf(e),i=Uf(n.map(e=>Hf(e,r))),a=Mf(e);for(let[n,r]of i.singleSource)jf(e,n)&&!a.has(n)&&t.set(n,r);return t}function jf(e,t){for(let n of _r(e.from))if(n.alias===t)return n.type===`collectionRef`||n.type===`descriptorRef`;if(e.join){for(let n of e.join)if(n.from.alias===t)return n.from.type===`collectionRef`||n.from.type===`descriptorRef`}return!1}function Mf(e){let t=new Set;if(e.join){let n=new Set(_r(e.from).map(e=>e.alias));for(let r of e.join){let e=r.from.alias;if((r.type===`left`||r.type===`full`)&&t.add(e),r.type===`right`||r.type===`full`)for(let e of n)t.add(e);n.add(e)}}return t}function Nf(e){return Pf({...e,from:Jf(e.from),join:e.join?.map(e=>({...e,from:e.from.type===`queryRef`?new Qn(Nf(e.from.query),e.from.alias,e.from.bindingId):e.from}))})}function Pf(e){if(!e.where||e.where.length===0||e.from.type===`unionFrom`)return e;if(!e.join||e.join.length===0){if(e.where.length>1){let t=tp(zf(e.where));return{...e,where:[t]}}return e}let t=zf(e.where.filter(e=>!hr(e))),n=Vf(e);return Wf(e,Uf(t.map(e=>Hf(e,n))))}function Ff(e){return{...e,from:If(e.from),join:e.join?.map(e=>({...e,from:Lf(e.from)}))}}function If(e){if(e.type===`unionFrom`)return new $n(e.sources.map(e=>If(e)));if(e.type===`unionAll`)return new er(e.queries.map(e=>Ff(e)));if(e.type===`collectionRef`||e.type===`descriptorRef`)return e;let t=Ff(e.query);if(Rf(t)&&e.alias===Yf(t)){let n=If(t.from);if(n.type===`collectionRef`||n.type===`descriptorRef`)return n.bindingId===e.bindingId?n:new Qn(t,e.alias,e.bindingId);if(n.type===`queryRef`)return new Qn(n.query,e.alias,e.bindingId)}return new Qn(t,e.alias,e.bindingId)}function Lf(e){return If(e)}function Rf(e){return(!e.where||e.where.length===0)&&!e.select&&(!e.groupBy||e.groupBy.length===0)&&(!e.having||e.having.length===0)&&(!e.orderBy||e.orderBy.length===0)&&(!e.join||e.join.length===0)&&e.limit===void 0&&e.offset===void 0&&!e.fnSelect&&(!e.fnWhere||e.fnWhere.length===0)&&(!e.fnHaving||e.fnHaving.length===0)&&!e.distinct&&!e.singleResult}function zf(e){let t=[];for(let n of e){let e=pr(n);t.push(...Bf(e))}return t}function Bf(e){if(e.type===`func`&&e.name===`and`){let t=[];for(let n of e.args)t.push(...Bf(n));return t}return[e]}function Vf(e){return new Set([..._r(e.from).map(e=>e.bindingId),...e.join?.map(({from:e})=>e.bindingId)??[]])}function Hf(e,t){let n=new Set,r=!1,i=!1;function a(e){switch(e.type){case`ref`:if(e.bindingId!==void 0&&!t.has(e.bindingId)&&(i=!0),e.path&&e.path.length>0){let t=e.path[0];t&&(n.add(t),e.path.length===1&&(r=!0))}break;case`func`:e.args&&e.args.forEach(a);break;case`val`:break;case`agg`:e.args&&e.args.forEach(a)}}return a(e),{expression:e,touchedSources:n,hasNamespaceOnlyRef:r,hasExternalBinding:i}}function Uf(e){let t=new Map,n=[];for(let r of e)if(r.touchedSources.size===1&&!r.hasNamespaceOnlyRef&&!r.hasExternalBinding){let e=Array.from(r.touchedSources)[0];t.has(e)||t.set(e,[]),t.get(e).push(r.expression)}else n.push(r.expression);let r=new Map;for(let[e,n]of t)r.set(e,tp(n));return{singleSource:r,multiSource:n.length>0?tp(n):void 0}}function Wf(e,t){let n=new Set,r=Mf(e),i=new Map;for(let[e,n]of t.singleSource)r.has(e)||i.set(e,n);let a=Xf(e.from,i,n),o=e.join?e.join.map(e=>({...e,from:Xf(e.from,i,n)})):void 0,s=[],c=e.where?.filter(hr)??[];t.multiSource&&s.push(t.multiSource);let l=r.size>0;for(let[e,r]of t.singleSource)n.has(e)?l&&c.push(gr(r)):s.push(r);let u=e=>e.length>1?tp(e.flatMap(e=>Bf(pr(e)))):e[0],d=u(s),f=u(c),p=[...d?[d]:[],...f?[gr(pr(f))]:[]];return{...Kf(e),from:a,join:o,where:p.length>0?p:[]}}function Gf(e){return{...Kf(e),from:qf(e.from),join:e.join?e.join.map(e=>({type:e.type,on:e.on,from:qf(e.from)})):void 0,where:e.where?[...e.where]:void 0}}function Kf(e){return{...e,groupBy:e.groupBy?[...e.groupBy]:void 0,having:e.having?[...e.having]:void 0,orderBy:e.orderBy?[...e.orderBy]:void 0,fnWhere:e.fnWhere?[...e.fnWhere]:void 0,fnHaving:e.fnHaving?[...e.fnHaving]:void 0}}function qf(e){return e.type===`collectionRef`||e.type===`descriptorRef`?e:e.type===`queryRef`?new Qn(Gf(e.query),e.alias,e.bindingId):e.type===`unionAll`?new er(e.queries.map(e=>Gf(e))):new $n(e.sources.map(e=>qf(e)))}function Jf(e){return e.type===`queryRef`?new Qn(Nf(e.query),e.alias,e.bindingId):e.type===`unionFrom`?new $n(e.sources.map(e=>Jf(e))):e.type===`unionAll`?new er(e.queries.map(e=>Nf(e))):e}function Yf(e){return _r(e.from)[0]?.alias}function Xf(e,t,n){if(e.type===`unionFrom`)return new $n(e.sources.map(e=>Xf(e,t,n)));if(e.type===`unionAll`)return new er(e.queries.map(e=>Gf(e)));let r=t.get(e.alias);if(!r)return e.type===`collectionRef`||e.type===`descriptorRef`?e:new Qn(Gf(e.query),e.alias,e.bindingId);if(e.type===`collectionRef`||e.type===`descriptorRef`){let t={from:e,where:[r]};return n.add(e.alias),new Qn(t,e.alias,e.bindingId)}if(!Qf(e.query,r,e.alias)||ep(e.query,r,e.alias))return new Qn(Gf(e.query),e.alias,e.bindingId);let i=e.query.where||[],a=Zf(e.query,r,e.alias);if(a===void 0)return new Qn(Gf(e.query),e.alias,e.bindingId);let o={...Gf(e.query),where:[...i,a]};return n.add(e.alias),new Qn(o,e.alias,e.bindingId)}function Zf(e,t,n){let r=Yf(e);if(r===void 0)return;let i=t=>{if(t instanceof J){if(t.path[0]!==n)return t;let i=t.path[1],a=i?e.select?.[i]:void 0,o=e.join!==void 0||e.from.type===`unionFrom`;return new J(a instanceof J?[...a.path,...t.path.slice(2)]:o?t.path.slice(1):[r,...t.path.slice(1)])}return t instanceof ir?new ir(t.name,t.args.map(i)):t};return i(t)}function Qf(e,t,n){return!(e.distinct||e.select&&(Of(e.select)!==void 0||$f(e.select,t,n))||e.groupBy?.length||e.having?.length||e.orderBy?.length&&(e.limit!==void 0||e.offset!==void 0)||e.fnSelect||e.fnWhere?.length||e.fnHaving?.length)}function $f(e,t,n){let r=new Set;for(let[t,n]of Object.entries(e))t.startsWith(`__SPREAD_SENTINEL__`)||n instanceof J||r.add(t);let i=or(t);for(let e of i){let t=e.path;if(!Array.isArray(t)||t.length<2)continue;let i=t[0],a=t[1];if(i===n&&r.has(a))return!0}return!1}function ep(e,t,n){let r=or(t);if(r.every(e=>e.path[0]!==n))return!1;if(e.fnSelect)return!0;let i=e.select;if(!i)return!1;let a=Object.keys(i).some(e=>e.startsWith(`__SPREAD_SENTINEL__`)),o=Vf(e);for(let t of r){let r=t.path;if(r.length<2||r[0]!==n)continue;let s=i[r[1]];if(!s){if(a)return!0;continue}if(!(s instanceof J)||s.bindingId!==void 0&&!o.has(s.bindingId)||s.path.length<2)return!0;let[c,l]=s.path,u=Yf(e);if(c!==n&&c!==u||l!==r[1])return!0}return!1}function tp(e){if(e.length===0)throw new Ts;return e.length===1?e[0]:new ir(`and`,e)}function np(e){if(e.type===`func`){if(e.name===`eq`&&e.args.length===2)return[[e.args[0],e.args[1]]];if(e.name===`and`&&e.args.length>0)return e.args.flatMap(np)}throw new Ko}function rp(e=0){if(e<0)throw RangeError(q(261))}function ip(e){let t=e;if(t==null)throw Error(q(237,{received:t===null?`null`:`undefined`}));return e._getQuery()}function ap(e,t){return op(e,{clones:new WeakMap,resolveDescriptor:t})}function op(e,t){let{clones:n}=t,r=n.get(e);if(r)return r;let i={...e};return n.set(e,i),i.from=sp(e.from,t),i.join=e.join?.map(e=>({...e,from:cp(e.from,t)})),i.select=e.select===void 0||ur(e.select)?e.select:lp(e.select,t),i}function sp(e,t){return e.type===`unionFrom`?new $n(e.sources.map(e=>cp(e,t))):e.type===`unionAll`?new er(e.queries.map(e=>op(e,t))):cp(e,t)}function cp(e,t){return e.type===`collectionRef`?new Yn(e.collection,e.alias,e.bindingId):e.type===`descriptorRef`?t.resolveDescriptor?new Yn(t.resolveDescriptor(e.descriptor),e.alias,e.bindingId):new Xn(e.descriptor,e.alias,e.bindingId):new Qn(op(e.query,t),e.alias,e.bindingId)}function lp(e,t){let{clones:n}=t,r=n.get(e);if(r)return r;let i={};n.set(e,i);for(let[n,r]of Object.entries(e))i[n]=up(r,t);return i}function up(e,t){let{clones:n}=t;if(e instanceof sr){let r=n.get(e);if(r)return r;let i=new sr(op(e.query,t),e.correlationField,e.childCorrelationField,e.fieldName,e.runtime,e.parentFilters,e.parentProjection,e.materialization,e.scalarField);return n.set(e,i),i}if(e instanceof cr){let r=n.get(e);if(r)return r;let i=new cr(e.branches.map(e=>({...e,value:up(e.value,t)})),e.defaultValue===void 0?void 0:up(e.defaultValue,t));return n.set(e,i),i}return typeof e!=`object`||!e||Array.isArray(e)||Wn(e)||ur(e)?e:lp(e,t)}var dp=`unionAll clause`,fp=class e{constructor(e={},t=!1){this.query=t?e:{...e}}bW(t){return new e({...this.query,...t},!0)}dY(t,n){if(typeof t==`string`)throw new Go(n,`string`);let r;try{r=Object.keys(t)}catch{throw new Go(n,t===null?`null`:`undefined`)}if(Array.isArray(t))throw new Go(n,`array`);if(r.length===0)throw new Go(n,`empty object`);if(n!==dp&&r.length!==1)throw new Vo(n);let i=[];for(let a of r){let r=t[a],o;if(r instanceof Tf)o=new Yn(r,a);else if(Ua(r))o=new Xn(r,a);else if(r instanceof e){let e=ap(r._getQuery());if(!e.from)throw new Ho(n);o=new Qn(e,a)}else throw new Uo(a);i.push([a,o])}return i}from(e){let[,t]=this.dY(e,`from clause`)[0];return this.bW({from:t})}unionAll(t,...n){if(t instanceof e)return this.bW({from:new er([t,...n].map(e=>ap(e._getQuery())))});let r=this.dY(t,dp),i=r.length===1?r[0][1]:new $n(r.map(e=>e[1]));return this.bW({from:i})}join(e,t,n=`left`){let[r,i]=this.dY(e,`join clause`)[0],a=t(Rl([...this.bo(),r],new Map([...this.dH(),[r,i.bindingId]])));np(a);let o={from:i,type:n,on:a},s=this.query.join||[];return this.bW({join:[...s,o]})}leftJoin(e,t){return this.join(e,t,`left`)}rightJoin(e,t){return this.join(e,t,`right`)}innerJoin(e,t){return this.join(e,t,`inner`)}fullJoin(e,t){return this.join(e,t,`full`)}where(e){let t=pp(e(Rl(this.bo(),this.dH()))),n=this.query.where||[];return this.bW({where:[...n,t]})}having(e){let t=this.bo(),n=pp(e(this.query.select||this.query.fnSelect?zl(t,this.dH()):Rl(t,this.dH()))),r=this.query.having||[];return this.bW({having:[...r,n]})}select(e){let t=this.bo(),n=e(Rl(t,this.dH()));Wn(n)&&n.__path.length===1&&(n={[`__SPREAD_SENTINEL__${n.__path[0]}__0`]:X(n)});let r=gp(n,{aliases:t,bindingIds:Ep(this._getQuery())});return this.bW({select:r,fnSelect:void 0})}orderBy(e,t=`asc`){let n=this.bo(),r=e(this.query.select||this.query.fnSelect?zl(n,this.dH()):Rl(n,this.dH())),i=typeof t==`string`?{direction:t,nulls:`first`}:{direction:t.direction??`asc`,nulls:t.nulls??`first`,...t.stringSort===`custom`?{stringSort:`custom`,compare:t.compare}:{stringSort:t.stringSort,locale:t.stringSort===`locale`?t.locale:void 0,localeOptions:t.stringSort===`locale`?t.localeOptions:void 0}},a=e=>({expression:X(e),compareOptions:i}),o=Array.isArray(r)?r.map(e=>a(e)):[a(r)],s=this.query.orderBy||[];return this.bW({orderBy:[...s,...o]})}groupBy(e){let t=(typeof e==`function`?e:e.callback)(Rl(this.bo(),this.dH())),n=Array.isArray(t)?t.map(e=>X(e)):[X(t)],r=this.query.groupBy||[];return this.bW({groupBy:[...r,...n],...typeof e==`function`?{}:{grouping:e.grouping}})}limit(e){return rp(e),this.bW({limit:e})}offset(e){return this.bW({offset:e})}distinct(){return this.bW({distinct:!0})}findOne(){return this.bW({singleResult:!0})}bo(){let e=[];if(this.query.from&&(this.query.from.type===`unionFrom`?e.push(...this.query.from.sources.map(e=>e.alias)):this.query.from.type===`unionAll`?e.push(`*`):e.push(this.query.from.alias)),this.query.join)for(let t of this.query.join)e.push(t.from.alias);return e}dH(){let e=new Map,t=this.query.from;if(t?.type===`unionFrom`)for(let n of t.sources)e.set(n.alias,n.bindingId);else t&&t.type!==`unionAll`&&e.set(t.alias,t.bindingId);for(let t of this.query.join??[])e.set(t.from.alias,t.from.bindingId);return e}get fn(){let e=this;return{select(t){return e.bW({select:void 0,fnSelect:t})},where(t){return e.bW({fnWhere:[...e.query.fnWhere||[],t]})},having(t){return e.bW({fnHaving:[...e.query.fnHaving||[],t]})}}}_getQuery(){if(!this.query.from)throw new qo;return this.query}_bindCollectionSources(t){if(!t||!this.query.from)return this;let n=this._getQuery();return dr(n).some(e=>e.type===`descriptorRef`)?new e(ap(n,t),!0):this}};function pp(e){let t=Wn(e)?X(e):e;if(!ur(t))throw new Jo(t===null?`null`:typeof t);return t}function mp(e){return X(e??null)}function hp(e){return Ac(e)&&!Array.isArray(e)&&!ur(e)&&!Wn(e)}function gp(e,t,n){if(Array.isArray(e))return e.some(e=>Wn(e)||ur(e))?new ir(`array`,e.map(e=>X(e??null))):mp(e);if(e instanceof fp||e instanceof tu){if(!n)throw Error(q(114));if(e instanceof fp)throw new Wo(n);if(!(e.query instanceof fp))throw Error(q(249));return wp(e.query,n,t,`collection`,e.runtime)}if(e instanceof Zl){if(!(e.query instanceof fp))throw Error(q(115));if(!n)throw Error(q(116));return wp(e.query,n,t,`array`,e.runtime)}if(e instanceof Ql){if(!(e.query instanceof fp))throw Error(q(117));if(!n)throw Error(q(118));return wp(e.query,n,t,`concat`,e.runtime)}if(e instanceof $l)return _p(e,t,n);if(!hp(e))return mp(e);let r={},i=0;for(let[n,a]of Object.entries(e))if(typeof n==`string`&&n.startsWith(`__SPREAD_SENTINEL__`)){let e=n.slice(0,n.lastIndexOf(`__`));r[`${e}__${++i}`]=a}else{if(a instanceof fp)throw new Wo(n);if(a instanceof tu){if(!(a.query instanceof fp))throw Error(q(250));r[n]=wp(a.query,n,t,`collection`,a.runtime)}else if(a instanceof Zl){if(!(a.query instanceof fp))throw Error(q(119));r[n]=wp(a.query,n,t,`array`,a.runtime)}else if(a instanceof Ql){if(!(a.query instanceof fp))throw Error(q(120));r[n]=wp(a.query,n,t,`concat`,a.runtime)}else if(a instanceof eu){if(!(a.query instanceof fp))throw Error(q(121));let e=a.query._getQuery().singleResult?`singleton`:`array`;r[n]=wp(a.query,n,t,e,a.runtime)}else r[n]=a instanceof $l?_p(a,t,n):gp(a,t,n)}return r}function _p(e,t,n){let r=e.args;if(r.length<2)throw Error(q(122));let i=r.length%2==1,a=Math.floor(r.length/2),o=[];for(let e=0;e<a;e++)o.push({condition:X(r[e*2]),value:gp(r[e*2+1],t,n)});return new cr(o,i?gp(r[r.length-1],t,n):void 0)}function vp(e){return e instanceof J||e instanceof ir||e instanceof ar?or(e):e instanceof cr?[...e.branches.flatMap(e=>[...or(e.condition),...vp(e.value)]),...e.defaultValue===void 0?[]:vp(e.defaultValue)]:e instanceof sr?[e.correlationField,...e.parentProjection??[],...yp(e.query)]:hp(e)?Object.values(e).flatMap(vp):[]}function yp(e){let t=new Set(Tp(e)),n=Ep(e),r=[],i=e=>{r.push(...or(e))},a=e=>{i(typeof e==`object`&&`expression`in e?e.expression:e)};for(let t of e.where??[])a(t);for(let t of e.join??[])i(t.on),t.from.type===`queryRef`&&r.push(...yp(t.from.query));for(let t of e.groupBy??[])i(t);for(let t of e.having??[])a(t);for(let{expression:t}of e.orderBy??[])i(t);if(e.select&&r.push(...vp(e.select)),e.from.type===`queryRef`)r.push(...yp(e.from.query));else if(e.from.type===`unionFrom`)for(let t of e.from.sources)t.type===`queryRef`&&r.push(...yp(t.query));else if(e.from.type===`unionAll`)for(let t of e.from.queries)r.push(...yp(t));let o=new Set;return r.filter(e=>{let r=e.path.length>1||e.bindingId!==void 0?e.path[0]:void 0,i=JSON.stringify([e.bindingId,e.path]);return r==null||r===`$selected`||(e.bindingId===void 0?t.has(r):n.has(e.bindingId))||o.has(i)?!1:(o.add(i),!0)})}function bp(e,t){let n=Ep(e),r=[],i=e=>{r.push(...or(e))},a=e=>{i(typeof e==`object`&&`expression`in e?e.expression:e)};for(let t of e.where??[])a(t);for(let n of e.join??[])i(n.on),n.from.type===`queryRef`&&r.push(...bp(n.from.query,t));for(let t of e.groupBy??[])i(t);for(let t of e.having??[])a(t);for(let{expression:t}of e.orderBy??[])i(t);if(e.select&&r.push(...vp(e.select)),e.from.type===`queryRef`)r.push(...bp(e.from.query,t));else if(e.from.type===`unionFrom`)for(let n of e.from.sources)n.type===`queryRef`&&r.push(...bp(n.query,t));else if(e.from.type===`unionAll`)for(let n of e.from.queries)r.push(...bp(n,t));let o=new Set;return r.filter(e=>{let r=JSON.stringify([e.bindingId,e.path]);return e.path[0]==null||!t.includes(e.path[0])||e.bindingId!==void 0&&n.has(e.bindingId)||o.has(r)?!1:(o.add(r),!0)})}function xp(e){return[...new Set(yp(e).map(e=>e.path[0]).filter(e=>e!==void 0))]}function Sp(e,t,n){return or(typeof e==`object`&&`expression`in e?e.expression:e).some(e=>e.path[0]!=null&&t.includes(e.path[0])&&(e.bindingId===void 0||!n.has(e.bindingId)))}function Cp(e,t,n=new Set){if(n.has(e))return!1;n.add(e);let r=e=>t.has(e.bindingId)||e instanceof Qn&&Cp(e.query,t,n),i=e=>e instanceof sr?Cp(e.query,t,n):e instanceof cr?e.branches.some(e=>i(e.value))||e.defaultValue!==void 0&&i(e.defaultValue):hp(e)&&Object.values(e).some(i),a=e.from;return(a.type===`unionFrom`?a.sources.some(r):a.type===`unionAll`?a.queries.some(e=>Cp(e,t,n)):r(a))||(e.join?.some(e=>r(e.from))??!1)||e.select!==void 0&&i(e.select)}function wp(e,t,n,r,i){let a=e._getQuery();if(Cp(a,n.bindingIds))throw Error(q(236,{fieldName:t}));let o=ap(a),s=Tp(o),c=Ep(o),l=[...new Set([...n.aliases,...xp(o)])],u,d,f=-1,p=-1;if(o.where)for(let e=0;e<o.where.length;e++){let t=o.where[e],n=typeof t==`object`&&`expression`in t?t.expression:t;if(n.type===`func`&&n.name===`eq`&&n.args.length===2){let t=Op(n.args[0],n.args[1],l,s,c);if(t){u=t.parentRef,d=t.childRef,f=e;break}}if(n.type===`func`&&n.name===`and`&&n.args.length>=2){for(let t=0;t<n.args.length;t++){let r=n.args[t];if(r.type===`func`&&r.name===`eq`&&r.args.length===2){let n=Op(r.args[0],r.args[1],l,s,c);if(n){u=n.parentRef,d=n.childRef,f=e,p=t;break}}}if(u)break}}if(!u||!d||f===-1)throw Error(q(123,{fieldName:t}));let m=[...o.where];if(p>=0){let e=m[f],t=(typeof e==`object`&&`expression`in e?e.expression:e).args.filter((e,t)=>t!==p);if(t.length===1){let n=typeof e==`object`&&`expression`in e&&e.residual;m[f]=n?{expression:t[0],residual:!0}:t[0]}else{let n=new ir(`and`,t),r=typeof e==`object`&&`expression`in e&&e.residual;m[f]=r?{expression:n,residual:!0}:n}}else m.splice(f,1);let h=[],g=[];for(let e of m)Sp(e,l,c)?g.push(e):h.push(e);let _=bp({...o,where:m},l),v=_.length>0?_:void 0,y={...o,where:h.length>0?h:void 0},b=y.select,x=b===void 0||hp(b),S=y,C;if(r===`concat`&&(b===void 0||x))throw Error(q(124,{fieldName:t}));if(!x){if(r===`collection`)throw Error(q(125,{fieldName:t}));C=Gn,S={...y,select:{[C]:b}}}return new sr(S,u,d,t,i,g.length>0?g:void 0,v,r,C)}function Tp(e){let t=new Set(Dp(e.from));if(e.join)for(let n of e.join)t.add(n.from.alias);return[...t]}function Ep(e){let t=new Set,n=e.from;if(n.type===`unionFrom`)for(let e of n.sources)t.add(e.bindingId);else n.type!==`unionAll`&&t.add(n.bindingId);for(let n of e.join??[])t.add(n.from.bindingId);return t}function Dp(e){return e.type===`unionFrom`?e.sources.map(e=>e.alias):e.type===`unionAll`?e.queries.flatMap(e=>Tp(e)):[e.alias]}function Op(e,t,n,r,i){if(e.type===`ref`&&t.type===`ref`){if(e.bindingId!==void 0&&t.bindingId!==void 0){let n=i.has(e.bindingId);return n===i.has(t.bindingId)?void 0:n?{parentRef:t,childRef:e}:{parentRef:e,childRef:t}}let a=e.path[0],o=t.path[0];if(a&&o&&n.includes(a)&&r.includes(o))return{parentRef:e,childRef:t};if(a&&o&&n.includes(o)&&r.includes(a))return{parentRef:t,childRef:e}}}function kp(e){return ip(e(new fp))}function Ap(){return Object.create(null)}function jp(e,t,n,r,i,a){if(t.type===`unionFrom`)return Pp(e,r);if(t.type===`queryRef`&&Mp(t.query.from))return Rp(Np(t.query,n,r));if(!i)return[];let o=zp(r);if(!o)return[];let s=yr(e,o,i);if(!s)return[];let c=s.alias||a[n]||n,l=Lp(e,t,{alias:c,collection:s.collection,sourceId:s.sourceId});return l?[{sourceId:l.sourceId,alias:c,collection:s.collection,path:s.path}]:[]}function Mp(e){return e.type===`unionFrom`?!0:e.type===`queryRef`?Mp(e.query.from):e.type===`unionAll`&&e.queries.some(e=>Mp(e.from))}function Np(e,t,n){if(!n||typeof n!=`object`||!(`type`in n))return[];let r=n;if(r.type===`func`&&r.name===`coalesce`)return Rp(r.args.flatMap(n=>Np(e,t,n)));let i=zp(r);return!i||i.path[0]!==t?[]:Fp(e,new J(i.path.slice(1)))}function Pp(e,t){if(!t||typeof t!=`object`||!(`type`in t))return[];let n=t;return n.type===`ref`?Fp(e,n):n.type===`func`&&n.name===`coalesce`?Rp(n.args.flatMap(t=>Pp(e,t))):[]}function Fp(e,t){if(t.path.length===0)return[];if(t.path.length===1){let n=t.path[0],r=e.select?.[n];return r?Pp(e,r):[]}let[n,...r]=t.path,i=Ip(e,n,t.bindingId);return i?i.type===`collectionRef`?[{sourceId:i.sourceId,alias:i.alias,collection:i.collection,path:r}]:i.type===`descriptorRef`?Zn(i):i.query.limit!==void 0||i.query.offset!==void 0||i.query.singleResult?[]:Np(i.query,i.alias,t):[]}function Ip(e,t,n){if(e.join){for(let r of e.join)if(r.from.alias===t&&(n===void 0||r.from.bindingId===n))return r.from}return _r(e.from).find(e=>e.alias===t&&(n===void 0||e.bindingId===n))}function Lp(e,t,n){if(n.sourceId!==void 0)return fr(e).find(e=>e.sourceId===n.sourceId&&e.collection===n.collection);if(t.type===`collectionRef`&&t.collection===n.collection&&t.alias===n.alias)return t}function Rp(e){let t=new Set,n=[];for(let r of e){let e=`${r.sourceId}:${JSON.stringify(r.path)}`;t.has(e)||(t.add(e),n.push(r))}return n}function zp(e){if(e instanceof J)return e;if(e&&typeof e==`object`&&`type`in e&&e.type===`ref`&&Array.isArray(e.path)){let t=e;return new J(t.path,t.sourceAlias)}}var Bp=`__tanstack_parent_route_cross__`;function Vp(e,t,n){let r=e.pipe(Y(([e,t,n])=>[Bp,[e,t,n]])),i=t.pipe(Y(([e,t])=>[Bp,[e,t]]));return r.pipe(wa(i,`inner`),Ui(([,[e,t]])=>e!=null&&t!=null),Y(([,[e,t]])=>{let[r,i,a]=e,[o,s]=t;return n(r,i,o,s,a)}))}function Hp(e){return Gp(e)}function Up(e){return Hp(ip(e))}function Wp(e,t=`value`){return JSON.stringify(Z(e,t,new WeakSet))}function Gp(e){return JSON.stringify(qp(e))}function Kp(e){if(e.where===void 0&&!e.orderBy?.length&&e.limit===void 0&&(e.offset===void 0||e.offset===0)&&e.cursor===void 0)return;let t=new WeakSet,n={type:`loadSubsetDemand`,query:$p(e,`loadSubset`,t)};if(e.limit!==void 0&&(n.limit=Z(e.limit,`loadSubset.limit`,t)),e.offset!==void 0&&e.offset!==0&&(n.offset=Z(e.offset,`loadSubset.offset`,t)),e.cursor!==void 0){let r={whereFrom:sm(e.cursor.whereFrom,`loadSubset.cursor.whereFrom`,t,`exact-output`),whereCurrent:sm(e.cursor.whereCurrent,`loadSubset.cursor.whereCurrent`,t,`exact-output`)};e.cursor.lastKey!==void 0&&(r.lastKey=Z(e.cursor.lastKey,`loadSubset.cursor.lastKey`,t)),n.cursor=r}return JSON.stringify(n)}function qp(e){return Xp(e,`query`,new WeakSet)}function Jp(e,t){let n=new Map,r=new Map,i=e=>{e.type===`unionFrom`?e.sources.forEach(i):e.type!==`unionAll`&&(n.has(e.alias)||n.set(e.alias,n.size),r.set(e.bindingId,n.get(e.alias)))};return i(e.from),e.join?.forEach(({from:e})=>i(e)),{bindings:n,bindingIds:r,hasUnqualifiedOutput:e.from.type===`unionAll`,parent:t}}function Yp(e,t,n){let r=e,i=0;for(;r;){let e=n===void 0?r.bindings.get(t):r.bindingIds.get(n);if(e!==void 0)return[i,e];if(r.hasUnqualifiedOutput)return;r=r.parent,i++}}function Xp(e,t,n,r){return Zp(e,t,n,Jp(e,r))}function Zp(e,t,n,r){if(e.fnSelect)throw new As(`${t}.fnSelect`,`function select`);if(e.fnWhere?.length)throw new As(`${t}.fnWhere`,`function where`);if(e.fnHaving?.length)throw new As(`${t}.fnHaving`,`function having`);let i={type:`query`,from:tm(e.from,`${t}.from`,n,r)};return e.select&&(i.select=nm(e.select,`${t}.select`,n,r)),e.select||e.from.type!==`unionFrom`&&e.join===void 0&&e.groupBy===void 0||(i.implicitOutput={type:`namespaced`,aliases:Array.from(r.bindings.keys())}),e.join&&(i.join=e.join.map((e,i)=>em(e,`${t}.join[${i}]`,n,r))),e.where&&(i.where=Qp(e.where,`${t}.where`,n,r)),e.grouping&&(i.grouping=!0),e.groupBy&&(i.groupBy=e.groupBy.map((e,i)=>sm(e,`${t}.groupBy[${i}]`,n,`exact-output`,r))),e.having&&(i.having=Qp(e.having,`${t}.having`,n,r)),e.orderBy&&(i.orderBy=e.orderBy.map((e,i)=>am(e,`${t}.orderBy[${i}]`,n,`ordering-operand`,r))),e.limit!==void 0&&(i.limit=Z(e.limit,`${t}.limit`,n)),e.offset!==void 0&&e.offset!==0&&(i.offset=Z(e.offset,`${t}.offset`,n)),e.distinct&&(i.distinct=!0),e.singleResult&&(i.singleResult=!0),i}function Qp(e,t,n,r){let i=e.map((e,i)=>im(e,`${t}[${i}]`,n,r));return i.sort(hm),i.filter((e,t)=>t===0||hm(e,i[t-1])!==0)}function $p(e,t,n){let r={type:`loadSubsetQuery`};return e.where!==void 0&&(r.where=sm(e.where,`${t}.where`,n,`exact-output`)),e.orderBy?.length&&(r.orderBy=e.orderBy.map((e,r)=>am(e,`${t}.orderBy[${r}]`,n,`ordering-operand`))),r}function em(e,t,n,r){return{type:e.type,from:tm(e.from,`${t}.from`,n,r),on:sm(e.on,`${t}.on`,n,`exact-output`,r)}}function tm(e,t,n,r){return e.type===`collectionRef`||e.type===`descriptorRef`?{type:`collectionRef`,collectionId:Z(e.type===`descriptorRef`?e.descriptor.id:e.collection.id,`${t}.collection.id`,n)}:e.type===`unionFrom`?{type:`unionFrom`,sources:e.sources.map((e,i)=>tm(e,`${t}.sources[${i}]`,n,r))}:e.type===`unionAll`?{type:`unionAll`,queries:e.queries.map((e,i)=>Xp(e,`${t}.queries[${i}]`,n,r.parent))}:{type:`queryRef`,query:Xp(e.query,`${t}.query`,n,r)}}function nm(e,t,n,r){return{type:`select`,fields:Object.keys(e).sort().map(i=>[i,rm(e[i],`${t}.${i}`,n,r)])}}function rm(e,t,n,r){return Wn(e)?sm(X(e),t,n,`exact-output`,r):ym(e)?sm(e,t,n,`exact-output`,r):Ac(e)?nm(e,t,n,r):fm(e,t,n)}function im(e,t,n,r){if(vm(e)){let i={type:`where`,expression:sm(e.expression,`${t}.expression`,n,`exact-output`,r)};return e.residual===!0&&(i.residual=!0),i}return sm(e,t,n,`exact-output`,r)}function am(e,t,n,r=`exact-output`,i){return{expression:sm(e.expression,`${t}.expression`,n,r,i),compareOptions:om(e.compareOptions,`${t}.compareOptions`,n)}}function om(e,t,n){return Z(tc(e),t,n)}function sm(e,t,n,r=`exact-output`,i){if(e.type===`ref`){let r=tr(e);if(r!==void 0){let a=Yp(i,r,e.bindingId);return a===void 0?{type:`ref`,path:e.path.map((e,r)=>Z(e,`${t}.path[${r}]`,n)),sourceAlias:Z(r,`${t}.sourceAlias`,n)}:{type:`ref`,path:[[`binding`,...a],...nr(e).map((e,r)=>Z(e,`${t}.path[${r+1}]`,n))]}}let a=Yp(i,e.path[0]??``,e.bindingId);return{type:`ref`,path:a===void 0?e.path.map((e,r)=>Z(e,`${t}.path[${r}]`,n)):[[`binding`,...a],...e.path.slice(1).map((e,r)=>Z(e,`${t}.path[${r+1}]`,n))]}}if(e.type===`val`)return{type:`val`,value:r===`equality-operand`?pm(e.value,`${t}.value`,n,i):r===`ordering-operand`?mm(e.value,`${t}.value`,n):fm(e.value,`${t}.value`,n)};if(e.type===`func`){if(e.name===`in`&&e.args.length===2&&e.args[1]?.type===`val`&&Array.isArray(e.args[1].value)){let r=e.args[1].value.map((e,r)=>pm(e,`${t}.args[1].value[${r}]`,n,i));return cm(e.name,[sm(e.args[0],`${t}.args[0]`,n,`equality-operand`,i),{type:`val`,value:[`set`,lm(r)]}])}let r=e.name===`eq`?`equality-operand`:e.name===`gt`||e.name===`gte`||e.name===`lt`||e.name===`lte`?`ordering-operand`:`exact-output`,a=e.args.map((e,a)=>sm(e,`${t}.args[${a}]`,n,r,i));return cm(e.name,a)}if(e.type===`agg`)return{type:`agg`,...e.grouping?{}:{withoutOperator:!0},name:e.name,args:e.args.map((e,r)=>sm(e,`${t}.args[${r}]`,n,`exact-output`,i))};if(e.type===`conditionalSelect`){let r={type:`conditionalSelect`,branches:e.branches.map((e,r)=>({condition:sm(e.condition,`${t}.branches[${r}].condition`,n,`exact-output`,i),value:rm(e.value,`${t}.branches[${r}].value`,n,i)}))};return e.defaultValue!==void 0&&(r.defaultValue=rm(e.defaultValue,`${t}.defaultValue`,n,i)),r}let a=Jp(e.query,i),o={type:`includesSubquery`,...e.runtime?{}:{withoutOperator:!0},query:Zp(e.query,`${t}.query`,n,a),correlationField:sm(e.correlationField,`${t}.correlationField`,n,`equality-operand`,i),childCorrelationField:sm(e.childCorrelationField,`${t}.childCorrelationField`,n,`equality-operand`,a),fieldName:e.fieldName,materialization:e.materialization};return e.parentFilters&&(o.parentFilters=e.parentFilters.map((e,r)=>im(e,`${t}.parentFilters[${r}]`,n,i))),e.parentProjection&&(o.parentProjection=e.parentProjection.map((e,r)=>sm(e,`${t}.parentProjection[${r}]`,n,`exact-output`,i))),e.scalarField!==void 0&&(o.scalarField=e.scalarField),o}function cm(e,t){return(e===`and`||e===`or`)&&t.length>0?{type:`func`,name:e,args:lm(t.flatMap(t=>um(t,e)?t.args:[t]))}:e===`eq`&&t.length===2?(t.sort(hm),{type:`func`,name:e,args:t}):(e===`gt`||e===`gte`||e===`lt`||e===`lte`)&&t.length===2&&hm(t[0],t[1])>0?{type:`func`,name:dm(e),args:[t[1],t[0]]}:{type:`func`,name:e,args:t}}function lm(e){let t=e.map(e=>({key:JSON.stringify(e),value:e}));return t.sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),t.filter((e,n)=>n===0||e.key!==t[n-1].key).map(e=>e.value)}function um(e,t){return typeof e==`object`&&!!e&&!Array.isArray(e)&&e.type===`func`&&e.name===t&&Array.isArray(e.args)}function dm(e){switch(e){case`gt`:return`lt`;case`gte`:return`lte`;case`lt`:return`gt`;case`lte`:return`gte`}}function Z(e,t,n){if(e===null)return[`null`];if(typeof e==`string`)return[`string`,e];if(typeof e==`boolean`)return[`boolean`,e];if(typeof e==`number`)return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:Object.is(e,-0)?[`number`,`-0`]:[`number`,e];if(e===void 0)return[`undefined`];if(typeof e==`bigint`)return[`bigint`,e.toString()];if(typeof e==`function`)throw new As(t,`function value`);if(typeof e==`symbol`)throw new As(t,`symbol value`);if(Wn(e))return sm(X(e),t,n);if(Array.isArray(e))return _m(e,t,n,()=>[`array`,e.map((e,r)=>Z(e,`${t}[${r}]`,n))]);if(e instanceof Date){let n=e.getTime();if(Number.isNaN(n))throw new As(t,`invalid Date`);return[`Date`,e.toISOString()]}if(e instanceof ArrayBuffer)return[`binary`,`ArrayBuffer`,Array.from(new Uint8Array(e))];if(ArrayBuffer.isView(e))return[`binary`,e.constructor.name,Array.from(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))];if(e instanceof Map)return _m(e,t,n,()=>{let r=Array.from(e.entries(),([e,r],i)=>[Z(e,`${t}.key[${i}]`,n),Z(r,`${t}.value[${i}]`,n)]);return r.sort(hm),[`Map`,r]});if(e instanceof Set)return _m(e,t,n,()=>{let r=Array.from(e,(e,r)=>Z(e,`${t}[${r}]`,n));return r.sort(hm),[`Set`,r]});if(Ac(e))return gm(e,t,n);throw new As(t,`non-plain object value`)}function fm(e,t,n){return typeof e==`object`&&e||typeof e==`function`||typeof e==`symbol`?ec(e):Z(e,t,n)}function pm(e,t,n,r){if(Wn(e))return sm(X(e),t,n,`equality-operand`,r);if(typeof e==`number`&&Object.is(e,-0))return Z(0,t,n);if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)return[`binary`,`Uint8Array`,Array.from(e)];let i=hc(e);return i===e?typeof e==`object`&&e||typeof e==`function`||typeof e==`symbol`?ec(e):Z(e,t,n):Z(i,t,n)}function mm(e,t,n){if(typeof e==`number`&&Object.is(e,-0))return Z(0,t,n);if(e instanceof Date&&Number.isNaN(e.getTime()))return Z(NaN,t,n);let r=hc(e);if(r!==e&&!(e instanceof Uint8Array))return Z(r,t,n);try{return Z(e,t,n)}catch(t){if(t instanceof As&&typeof e==`object`&&e)return ec(e);throw t}}function hm(e,t){let n=JSON.stringify(e),r=JSON.stringify(t);return n<r?-1:+(n>r)}function gm(e,t,n){return _m(e,t,n,()=>[`object`,Object.keys(e).sort().map(r=>[r,Z(e[r],`${t}.${r}`,n)])])}function _m(e,t,n,r){if(n.has(e))throw new As(t,`circular value`);n.add(e);try{return r()}finally{n.delete(e)}}function vm(e){return`expression`in e}function ym(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`agg`||t===`conditionalSelect`||t===`func`||t===`ref`||t===`val`||t===`includesSubquery`}function bm(e,t){if(!Bs(xm(e),xm(t)))return!1;try{return Gp(e)===Gp(t)}catch(e){if(e instanceof As)return!1;throw e}}function xm(e){return{from:Sm(e.from),select:e.select,join:e.join?.map(e=>({from:Sm(e.from),type:e.type,on:e.on})),where:e.where,groupBy:e.groupBy,having:e.having,orderBy:e.orderBy,limit:e.limit,offset:e.offset,distinct:e.distinct,singleResult:e.singleResult,fnSelect:e.fnSelect,fnWhere:e.fnWhere,fnHaving:e.fnHaving}}function Sm(e){switch(e.type){case`collectionRef`:return{type:e.type,collection:e.collection,alias:e.alias};case`descriptorRef`:return{type:e.type,descriptor:e.descriptor,alias:e.alias};case`queryRef`:return{type:e.type,query:xm(e.query),alias:e.alias};case`unionFrom`:return{type:e.type,sources:e.sources.map(Sm)};case`unionAll`:return{type:e.type,queries:e.queries.map(xm)}}}var Cm=0;function wm(e,t,n){return Vp(e,t,(e,t,r,i,a)=>[Er([n.equality(e),n.equality(r),kc(i)]),Bc({...t},r,i),a])}function Tm(e,t,n,r){let i=Hc(e,t);return Er([r.equality(i?.correlationKey),kc(i?.parentContext??null),n])}function Em(e,t,n,r,i,a,o){let s=i[0](t),c=[e,t,void 0],l=r===`main`?`\0m`:`\0j`;if(s==null)return[l,c];let u=o.equality(s);if(i.length>1){let e=[u];for(let n=1;n<i.length;n++){let r=i[n](t);if(r==null)return[l,c];e.push(o.equality(r))}u=e}return c[2]=s,[a?Tm(t,n,u,o):Er(u),c]}function Dm(e,t,n=new Set){let r={id:`lazy-demand-${++Cm}`,path:t.path,collectionId:t.collection.id,initialKeys:new Set(n)},i=e[t.sourceId]??={};return(i.plans??=[]).push(r),r}function Om(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=new Set(_r(d).map(e=>e.bindingId));function b(e,t){let d=t.from.alias,b=Object.keys(n),x=e=>{let n=km(e);return e.bindingId===void 0?n===d?`joined`:n&&(b.includes(n)||u.from.type===`unionAll`)?`main`:`unknown`:e.bindingId===t.from.bindingId?`joined`:y.has(e.bindingId)?`main`:`ancestor`},S=np(t.on).map(([e,t])=>Am(e,t,d,x)),{mainExpr:C,joinedExpr:w}=S[0],T=S.some(({joinedExpr:e})=>or(e).some(e=>{let t=x(e);return t===`ancestor`||t===`unknown`})),E=v!==void 0&&(t.from.type===`queryRef`||(t.type===`right`||t.type===`full`)&&!g||T),{alias:D,input:ee,collectionId:te}=jm(t.from,a,o,f,p,m,h,_,`join`,E?v:void 0);if(D!==d)throw new ps;n[d]=ee;let O=s[r],k=s[te];if(!O)throw new ls(r);if(!k)throw new ls(te);let A=Pm(t.type,O,k,g),j=E?void 0:A.activeSource,M=A.lazySource,ne=S.map(e=>il(e.mainExpr)),N=S.map(e=>il(e.joinedExpr)),re=e.pipe(Y(([e,t])=>Em(e,t,i,`main`,ne,E,_))),P=ee.pipe(Y(([e,t,n])=>Em(e,Kc(d,t,n),d,`joined`,N,E,_)));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new ds(t.type);if(j){let e=j===`main`?t.from:u.from,n=e.type===`queryRef`&&(e.query.limit!==void 0||e.query.offset!==void 0||e.query.singleResult),r=e.type===`unionAll`?[]:jp(u,e,j===`main`?d:i,j===`main`?w:C,M,m);if(!n&&r.length>0){for(let e of r)l.add(e.sourceId);let e=r.map(e=>Dm(c,e)),t=new Map,n=j===`main`?re:P;for(let e of r){let t=e.path[0];t&&iu(t,e.path,e.collection)}let i=n.pipe(Na(n=>{for(let[[e,[,,r]],i]of n.getInner()){if(r==null)continue;let n=t.get(e),a=(n?.weight??0)+i;a===0?t.delete(e):t.set(e,{key:n?.key??r,weight:a})}let i=new Set([...t.values()].filter(({weight:e})=>e>0).map(({key:e})=>e));for(let t=0;t<r.length;t++)c[r[t].sourceId]?.setDemand?.(e[t],i)}));j===`main`?re=i:P=i}}return re.pipe(wa(P,t.type),Nm(d,b))}for(let n of t)e=b(e,n),y.add(n.from.bindingId);return e}function km(e){return tr(e)??e.path[0]}function Am(e,t,n,r){let i=or(e),a=or(t),o=new Set(i.map(r)),s=new Set(a.map(r)),c=o.has(`main`)||o.has(`ancestor`),l=s.has(`main`)||s.has(`ancestor`),u=o.has(`joined`),d=s.has(`joined`);if(c&&!u&&d&&!s.has(`main`))return{mainExpr:e,joinedExpr:t};if(u&&!o.has(`main`)&&l&&!d)return{mainExpr:t,joinedExpr:e};throw i.length===0||a.length===0?new ps:i.length===1&&a.length===1&&(i[0].bindingId!==void 0&&a[0].bindingId!==void 0?i[0].bindingId===a[0].bindingId:km(i[0])===km(a[0]))?new fs(km(i[0])):c?d?new gs:new hs(n):new ms(km(i[0]))}function jm(e,t,n,r,i,a,o,s,c,l){switch(e.type){case`descriptorRef`:return Zn(e);case`collectionRef`:{let n=t[e.sourceId];if(!n)throw new is(e.alias,e.collection.id,Object.keys(t));return i[e.alias]=e.collection.id,{alias:e.alias,input:c===`join`&&l?wm(n,l,s):n,collectionId:e.collection.id}}case`queryRef`:{let t=n.get(e.query),s=r(t&&bm(e.query,t)?t:e.query,l);if(Object.assign(i,s.aliasToCollectionId),Object.assign(a,s.aliasRemapping),n.has(e.query)||e.alias!==_r(e.query.from)[0]?.alias)for(let[e,t]of s.sourceWhereClauses)o.set(e,t);let u=Object.keys(s.aliasToCollectionId).find(e=>s.aliasToCollectionId[e]===s.collectionId);u&&u!==e.alias&&(a[e.alias]=u);let d=s.pipeline.pipe(Y(e=>{let[t,[n,r,i,a,o,s]]=e;return c===`join`&&!l?[t,n,s]:[t,Wc(c===`from`&&n instanceof rr?n.value:n,i,a,o),s]}));return{alias:e.alias,input:d,collectionId:s.collectionId,includes:s.includes}}default:throw c===`join`?new _s(e.type):new as(e.type)}}function Mm(e,t){return typeof t==`number`&&!Number.isFinite(t)?{number:String(t)}:t}function Nm(e,t){return n=>n.pipe(Y(n=>{let[r,[i,a]]=n,o=i?.[0],s=i?.[1],c=a?.[0],l=a?.[1],u=(n,r)=>{let a={...n??r};if(i==null)for(let e of t)delete a[e];return r?a[e]=r[e]:delete a[e],a},d=u(s,l),f=s&&qc(s),p=l&&qc(l);return(f!==s||p!==l)&&Object.assign(d,{[Nc]:u(f,p)}),[JSON.stringify([o??null,c??null],Mm),d]}))}function Pm(e,t,n,r){switch(e){case`left`:return{activeSource:`main`,lazySource:n};case`right`:return{activeSource:`joined`,lazySource:t};case`inner`:return r||t.size<n.size?{activeSource:`main`,lazySource:n}:{activeSource:`joined`,lazySource:t};default:return{activeSource:void 0,lazySource:void 0}}}function Fm(e){return e instanceof rr?e.value:e}var Im=new Set([`__proto__`,`prototype`,`constructor`]);function Lm(e){for(let t of e)if(Im.has(t))throw new Xo(t)}function Rm(e,t){for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&Bm(e,n,Fm(Reflect.get(t,n)))}function zm(e,t,n){let r=e;for(let e of t){let t=Object.hasOwn(r,e)?Reflect.get(r,e):void 0;if(typeof t==`object`&&t&&n.has(t)){r=t;continue}let i=Array.isArray(t)?Array(t.length):{};Array.isArray(t)&&Object.setPrototypeOf(i,Object.getPrototypeOf(t)),typeof t==`object`&&t&&Rm(i,t),n.add(i),Bm(r,e,i),r=i}return r}function Bm(e,t,n){Object.defineProperty(e,t,Object.hasOwn(e,t)?{value:n}:{value:n,enumerable:!0,configurable:!0,writable:!0})}function Vm(e,t,n,r){Lm(e.targetPath);let i=e.source(t);i&&typeof i==`object`&&Rm(zm(n,e.targetPath,r),i)}function Hm(e,t,n,r){let i=e.alias.split(`.`);Lm(i),Bm(zm(n,i.slice(0,-1),r),i[i.length-1],Fm(e.compiled(t)))}function Um(e,t){let n={},r=new WeakSet([n]);for(let i of t)if(i.kind===`merge`)Vm(i,e,n,r);else if(i.kind===`field`)Hm(i,e,n,r);else{Lm(i.targetPath);let e=zm(n,i.targetPath.slice(0,-1),r),t={};r.add(t),Bm(e,i.targetPath[i.targetPath.length-1],t)}return n}function Wm([e,t],n){let r=Um(t,n);return[e,{...t,$selected:r}]}function Gm(e,t,n){if(!Ym(t)){let n=qm(t);return e.pipe(Y(([e,t])=>[e,{...t,$selected:n(t)}]))}let r=[];return Xm([],t,r),e.pipe(Y(e=>Wm(e,r)))}function Km(e){let t=[];return Xm([],e,t),e=>Um(e,t)}function qm(e){return e==null?()=>e:Zm(e)?Jm(e):e instanceof rr?()=>e.value:e.type===`includesSubquery`?()=>null:Ym(e)?Km(e):ur(e)?il(e):()=>e}function Jm(e){let t=e.branches.map(e=>({condition:il(e.condition),value:qm(e.value)})),n=e.defaultValue===void 0?void 0:qm(e.defaultValue);return e=>{for(let n of t)if(ul(n.condition(e)))return n.value(e);return n===void 0?null:n(e)}}function Ym(e){return e&&typeof e==`object`&&!ur(e)}function Xm(e,t,n){for(let[r,i]of Object.entries(t)){if(r.startsWith(`__SPREAD_SENTINEL__`)||Lm(r.split(`.`)),r.startsWith(`__SPREAD_SENTINEL__`)){let t=r.slice(19),a=t.lastIndexOf(`__`),o=a>=0?t.slice(0,a):t,s=i&&typeof i==`object`&&`type`in i&&i.type===`ref`;if(o.includes(`.`)||s){let t=[...e],r=o.split(`.`),a=il(s?i:new J(r,r[0]));n.push({kind:`merge`,targetPath:t,source:a})}else{let t=o,r=[...e];n.push({kind:`merge`,targetPath:r,source:e=>e[t]})}continue}let t=i;if(Zm(t))n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:Jm(t)});else if(t&&t.type===`includesSubquery`)n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});else if(Ym(t)){let i=[...e,...r.split(`.`)];n.push({kind:`object`,targetPath:i}),Xm(i,t,n)}else if(t===void 0||!ur(t))n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>t});else if(t instanceof rr){let i=t.value;n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>i})}else n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:il(t)})}}function Zm(e){return e instanceof cr||typeof e==`object`&&!!e&&e.type===`conditionalSelect`&&Array.isArray(e.branches)}function Qm(e,t=new Set){if(e instanceof tu)return`include()`;if(e instanceof fp)return`a child query builder`;if(e instanceof Zl)return`toArray()`;if(e instanceof Ql)return`concat(toArray())`;if(e instanceof eu)return`materialize()`;if(e instanceof $l)return`caseWhen()`;if(ur(e))return e&&typeof e==`object`&&`name`in e&&typeof e.name==`string`?`${e.name}()`:`a query expression`;if(typeof e!=`object`||!e||t.has(e))return;t.add(e);let n=Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t));for(let r of n){let n=e[r],i=Qm(n,t);if(i)return i}}function $m(e){let t=Qm(e);if(t)throw new es(t)}function eh(e,t,n){let r=Vc(e)?.parentContext,i={...Oc(r)},a={...Tc(r)},o=[];for(let r of t){let t=r.compiled(e);if(o.push([r.alias,r.bindingKey,r.field,n.equality(t)]),r.bindingKey!==void 0&&(a[r.bindingKey]=t),r.field.length===0){let e=t;i[r.alias]=typeof e==`object`&&e?{...e}:e;continue}let s=i[r.alias],c=typeof s==`object`&&s?{...s}:{};i[r.alias]=c;let l=c;for(let e=0;e<r.field.length-1;e++){let t=r.field[e],n=l[t],i=typeof n==`object`&&n?{...n}:{};l[t]=i,l=i}l[r.field[r.field.length-1]]=t}return wc(i,[kc(r),o],a)}function th(e,t,n,r){return Vp(e,t,(e,t,i,a)=>{let o={...Oc(a),...t};return o[n]={...o[n],[Ic]:o[n]?.[Ic]??e},Bc(o,i,a),[Er([r.equality(e),r.equality(i),kc(a)]),o]})}function nh(e,t){if(e==null||t==null)return!1;let n=hc(e),r=hc(t);return Object.is(n,r)}var rh=new Set,ih=new WeakMap;function ah(e){return Df(ih,e,Cc)}function oh(...e){return sh(e,!1,!0)}function sh([e,t,n,r,i,a,o,s,c=new WeakMap,l=new WeakMap,u,d,f=!1],p,m=!1){let h=u===void 0?c.get(e)?.[+!!m]:void 0;if(h)return h;let g=ah(c);p||mh(e);let _=fr(e),{optimizedQuery:v,sourceWhereClauses:y}=kf(e),b=lh(e,y),x=v,S=m||x.fnSelect!==void 0;l.set(x,e),Ch(x,e,l);let C=Object.assign(Ap(),t);uh(_,C);let w={},T={},E={},{alias:D,collectionId:ee,pipeline:te,sources:O,sourceIncludes:k,directIncludes:A,isUnionFrom:j,isParentRouted:M}=hh(x.from,C,n,r,i,a,o,Ih,c,l,w,T,b,u,S);Object.assign(E,O);let ne=u!==void 0||k.length>0||A.length>0,N=te,re=d?.path[0],P=!j&&!M&&u!==void 0&&d!==void 0&&re===D;if(u&&d&&P){let e=E[D],t=e,n=d.path.slice(1),r=e.pipe(Y(([e,t,r])=>{let i=Fh(t,n);return[g.serializeEquality(i),[e,t,i,r]]})),i=u.pipe(Y(([e,t])=>[g.serializeEquality(e),t]),ja(e=>e.map(([e,t])=>[e,+(t>0)])));t=r.pipe(wa(i,`inner`)).pipe(Ui(([e,[t]])=>t!=null),Y(([e,[t,n]])=>{let[r,i,a,o]=t,s=Bc({...i,[Ic]:r},a,n);return[n==null?r:Er([g.equality(r),kc(n)]),s,o]})),E[D]=t,N=_h(t,D)}else u&&!M&&(N=th(te,u,D,g));x.join&&x.join.length>0&&(N=Om(N,x.join,E,ee,D,C,l,n,i,a,e,x.from,(e,t)=>sh([e,C,n,r,i,a,o,Ih,c,l,t],!0,S),w,T,b,P,g,u));let ie=x.join?.some(({type:e})=>e===`right`||e===`full`);if(u&&d&&(!P||ie)){let e=il(d);N=N.pipe(Ui(([,t])=>nh(e(t),Hc(t,D)?.correlationKey)))}if(x.where&&x.where.length>0)for(let e of x.where){let t=il(pr(e));N=N.pipe(Ui(([e,n])=>rl(t(n))))}if(x.fnWhere&&x.fnWhere.length>0)for(let e of x.fnWhere)N=N.pipe(Ui(([t,n])=>{let r=Yc(qc(n));return rl(e(r))}));let ae=[...A,...k.map(({include:e})=>e)],F=!!x.fnSelect&&ae.length>0,I=x.select?[]:[...A],L=[],oe=[...k.map(({sourceAlias:e,include:t})=>({include:t,keyPrefix:`${e}.`,paths:x.select==null?x.fnSelect&&!F?[]:[{path:[e,...t.resultPath],guards:[]}]:Th(x.select,[e,...t.resultPath]),route:n=>Lh(n[e],t.fieldName)})),...(x.select?A:[]).map(e=>({include:e,keyPrefix:``,paths:Th(x.select,e.resultPath),route:t=>Lh(t,e.fieldName)}))];for(let{include:e,keyPrefix:t,paths:n,route:r}of oe)for(let{path:i,guards:a}of n){let n=jh(t+i.join(`.`),L);I.push({...e,fieldName:n,resultPath:i}),L.push({fieldName:n,getRouting:zh(a,r)})}let se=Of(x.select),ce=se!==void 0,R=(x.orderBy?.length??0)>0,le=R||!!x.singleResult,ue=[];if(x.select){let t=Oh(x.select);if(t.length>0&&((x.groupBy?.length??0)>0||ce))throw new ys(t[0].path.join(`.`));t.length>0&&(x={...x,select:{...x.select}});for(let{key:s,path:u,subquery:d,guards:p}of t){if(typeof d.runtime?.materializeCompilation!=`function`)throw new Wo(s);let t=jh(s,L),m=il(d.correlationField),h=d.parentProjection?.map(e=>({alias:e.path[0],field:e.path.slice(1),bindingKey:e.bindingId?JSON.stringify([e.bindingId,e.path.slice(1)]):void 0,compiled:il(e)}))??[],_=zh(p,e=>({active:!0,correlationKey:m(e),parentContext:h.length>0?eh(e,h,g):null})),v=s=>{let p=(s?s.pipe(Y(([,[e]])=>Rh(e,t))):N.pipe(Y(([,e])=>_(e)))).pipe(Ui(e=>e.active),Y(e=>[e.correlationKey,e.parentContext]),ja(e=>e.map(([e,t])=>[e,+(t>0)]))),m=d.childCorrelationField.path[0],h=d.query.from.type===`collectionRef`?d.query.from.collection:void 0,v=jp(d.query,d.query.from,m,d.childCorrelationField,h,T);if(v.length>0){for(let e of v){a.add(e.sourceId);let t=e.path[0];t&&iu(t,e.path,e.collection)}let t=Bh(e,d.correlationField),n=!f&&(!s||x.singleResult&&x.offset===void 0&&(x.limit??1)>0&&t.size===1)?t:new Set,r=v.map(e=>Dm(i,e,n)),o=new Map;p=p.pipe(Na(e=>{for(let[[t],n]of e.getInner()){if(t==null)continue;let e=g.serializeEquality(t),r=(o.get(e)?.weight??0)+n;r===0?o.delete(e):o.set(e,{key:t,weight:r})}let t=new Set([...o.values()].filter(({weight:e})=>e>0).map(({key:e})=>e));v.forEach((e,n)=>i[e.sourceId]?.setDemand?.(r[n],t))}))}let y=sh([d.parentFilters&&d.parentFilters.length>0?{...d.query,where:[...d.query.where||[],...d.parentFilters]}:d.query,C,n,r,i,a,o,Ih,c,l,p,d.childCorrelationField,f||le],!0,d.materialization===`collection`);for(let[e,t]of y.sourceWhereClauses)b.set(e,t);I.push({pipeline:y.pipeline,fieldName:t,resultPath:u,correlationField:d.correlationField,childCorrelationField:d.childCorrelationField,hasOrderBy:(d.query.orderBy?.length??0)>0,childCompilationResult:y,parentProjection:d.parentProjection,materialization:d.materialization,scalarField:d.scalarField,runtime:d.runtime})};le?ue.push(v):v(),L.push({fieldName:t,getRouting:_}),x={...x,select:Ph(x.select,u)}}}if(x.distinct&&!x.fnSelect&&!x.select&&x.from.type!==`unionAll`)throw new Zo;if(x.fnSelect&&x.groupBy&&x.groupBy.length>0)throw new Qo;let de=L,fe=e=>Object.fromEntries(de.map(({fieldName:t,getRouting:n})=>[t,n(e)]));if(F){if(!ae.every(ch))throw Error(q(128));let e=N.pipe(Y(([e,t])=>[e,[{...t,[Lc]:{...t[Lc],...fe(t)}},void 0]]));N=I[0].runtime.materializeCompilation({pipeline:e,includes:I,valueIdentity:g,collectionId:ee,sourceWhereClauses:b,aliasToCollectionId:w,aliasRemapping:T}).pipeline.pipe(Y(([e,[t]])=>{let n={...t};return delete n[Lc],[e,n]})),I=[],L=[]}let pe=new Map(wh(x).map(e=>[e.alias,e.bindingId])),me=x.from.type===`unionAll`;if(x.fnSelect){let e=[...pe.keys()];N=N.pipe(Y(([t,n])=>{let r=Yc(qc(n)),i=x.fnSelect(r);$m(i);let a=i;if(Zc(i)){a=xh(i);let e=n[Lc];e&&(a[Lc]=e)}let o=e.some(e=>i===r[e])?a:Sh(a,{},!0,[]);return m&&(a=o),[t,{...n,$selected:a,[Pc]:o}]}))}else x.select?!ce&&!(x.groupBy&&x.groupBy.length>0)&&(N=Gm(N,x.select)):N=N.pipe(Y(([e,t])=>{let n=Gc(t),r=j&&n?n.value:!j&&!x.join&&!x.groupBy?t[D]:t;return[e,{...t,$selected:r}]}));L.length>0&&(N=N.pipe(Y(([e,t])=>{let n=xh(t.$selected);return n[Lc]=fe(t),[e,{...t,$selected:n}]})));let he=u?D:void 0,z=e=>{let t=pe.get(e.path[0]);return t===void 0?me&&e.bindingId===void 0&&e.path[0]!==`$selected`:(e.bindingId??t)===t},B=se??Of([x.having,x.orderBy?.map(e=>e.expression)]),V=x.grouping??B?.grouping,ge=(x.groupBy?.length??0)>0;if((ge||B)&&!V)throw new $o;if(V&&(ge||se)&&(N=V.processGroupBy(N,x.groupBy??[],g,z,x.having,x.select,x.fnHaving,ee,he,ne||L.length>0)),x.having&&(!x.groupBy||x.groupBy.length===0)&&!ce)throw new ns;if(x.fnHaving&&x.fnHaving.length>0&&(!x.groupBy||x.groupBy.length===0))for(let e of x.fnHaving)N=N.pipe(Ui(([t,n])=>{let r=Yc(qc(n));return e(r)}));!ce&&x.distinct&&(N=dh(N,x,D,u!==void 0)),x.distinct&&(N=N.pipe(Vi(([e,t])=>t.$selected)));let H=x.select?bh(x.select):x.from.type===`unionAll`?void 0:[D],_e=(e,t,n)=>{let r=yh(t.$selected),i=Jc(x.fnSelect&&m?r:Sh(r,t,m,H)),a=qc(t),o=Object.entries(a).filter(([e,n])=>e!==`$selected`&&n!==t[e]),s=x.fnSelect?t[Pc]:Sh(Xc(r,e=>o.find(([n])=>e===t[n])?.[1]??e,rh),a,!0,H),c=u?Hc(t,D):void 0;return[e,[i,n,c?.correlationKey,u?c?.parentContext??null:void 0,u?t[D]?.[Ic]??t[Ic]??e:void 0,Jc(s)]]},ve=x.singleResult?Math.min(x.limit??1,1):x.limit;if(!R&&(x.limit!==void 0||x.offset!==void 0))throw new rs;let ye,be;if(R||x.singleResult){let t=u&&(ve!==void 0||x.offset!==void 0)?(e,t)=>{let n=Hc(t,D),r=n?.correlationKey,i=n?.parentContext;return i==null?g.equality(r):Er([g.equality(r),kc(i)])}:void 0,r=pu(e,N,x.orderBy??[],x.select||{},V,n[ee],o,e=>be=e,ve,x.offset,t);for(let e of ue)e(r);be&&s(be),ye=r.pipe(Y(([e,[t,n]])=>_e(e,t,n)))}else ye=N.pipe(Y(([e,t])=>_e(e,t,void 0)));let xe={collectionId:ee,pipeline:ye,valueIdentity:g,sourceWhereClauses:b,aliasToCollectionId:w,aliasRemapping:T,includes:I.length>0?I:void 0};return u===void 0&&(Df(c,e,()=>[])[+!!m]=xe),xe}function ch(e){return e.materialization!==`collection`&&(e.childCompilationResult.includes??[]).every(ch)}function lh(e,t){let n=wh(e).filter(e=>e.type===`collectionRef`),r=new Map(n.map(e=>[e.alias,e])),i=new Map;for(let[e,n]of t){let t=r.get(e);t&&i.set(t.sourceId,n)}return i}function uh(e,t){for(let n of e){let e=t[n.sourceId]??t[n.alias];e&&(t[n.sourceId]=e)}}function dh(e,t,n,r){let i=(t.orderBy??[]).map(({expression:e})=>il(e)),a=e=>{let t=r?Hc(e,n):void 0;return{value:e.$selected,routing:e.$selected?.[Lc],outerCorrelation:t?.correlationKey,parentContext:r?t?.parentContext??null:void 0,order:i.map(t=>t(e))}};return e.pipe(ja(e=>{let t=e.reduce((e,[,t])=>e+t,0);if(t===0)return[];if(t<0)throw Error(q(129));let n=e.find(([,e])=>e>0)?.[0];if(!n)throw Error(q(130));let r=a(n);for(let[t,n]of e)if(n>0&&!Bs(r,a(t)))throw Error(q(131));return[[n,1]]}))}function fh(e,t){for(let n of or(e))if(n.bindingId!==void 0&&!t.has(n.bindingId))throw new Yo(q(238,{path:n.path}))}function ph(e,t){if(!(e instanceof sr)){if(lr(e))fh(e,t);else if(e instanceof cr){for(let n of e.branches)fh(n.condition,t),ph(n.value,t);e.defaultValue!==void 0&&ph(e.defaultValue,t)}else if(Mh(e))for(let n of Object.values(e))ph(n,t)}}function mh(e,t=new Set){let n=wh(e).map(e=>e.alias);for(let[e,t]of n.entries())if(n.indexOf(t)!==e)throw new Yo(q(211,{alias:t}));let r=new Set(t);if(e.from.type===`unionAll`)for(let n of e.from.queries)mh(n,t);else for(let n of _r(e.from))n.type===`queryRef`&&mh(n.query,t),r.add(n.bindingId);if(e.join)for(let n of e.join){n.from.type===`queryRef`&&mh(n.from.query,t);let e=new Set(r);e.add(n.from.bindingId),fh(n.on,e),r.add(n.from.bindingId)}for(let t of e.where??[])fh(pr(t),r);for(let t of e.groupBy??[])fh(t,r);for(let t of e.having??[])fh(mr(t),r);for(let{expression:t}of e.orderBy??[])fh(t,r);if(e.select){ph(e.select,r);for(let{subquery:t}of Oh(e.select)){fh(t.correlationField,r);let e=new Set(r);for(let n of wh(t.query))e.add(n.bindingId);fh(t.childCorrelationField,e);for(let n of t.parentFilters??[])fh(pr(n),e);mh(t.query,r);let n=new Set((t.parentProjection??[]).map(e=>JSON.stringify([e.bindingId,e.path]))),i=[...yp(t.query),...(t.parentFilters??[]).flatMap(e=>or(pr(e)))];for(let e of i)if(e.bindingId!==void 0&&r.has(e.bindingId)&&!n.has(JSON.stringify([e.bindingId,e.path])))throw new Yo(q(239,{path:e.path}))}}}function hh(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m=!1){let h=ah(c);if(e.type===`unionAll`)return gh(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m);let g=e=>{let g=jm(e,t,l,(e,u)=>sh([e,t,n,r,i,a,o,s,c,l,u],!0,m),u,d,f,h,`from`,p);return{...g,sourceIncludes:g.includes?.map(t=>({sourceAlias:e.alias,include:t}))??[],isParentRouted:e.type===`queryRef`&&p!==void 0}};if(e.type!==`unionFrom`){let{alias:t,input:n,collectionId:r,sourceIncludes:i,isParentRouted:a}=g(e);return{alias:t,pipeline:_h(n,t),collectionId:r,sources:{[t]:n},sourceIncludes:i,directIncludes:[],isUnionFrom:!1,isParentRouted:a}}if(e.sources.length===0)throw new as(`empty unionFrom`);let _={},v=[],y,b=``,x=``;for(let t of e.sources){let{alias:e,input:n,collectionId:r,sourceIncludes:i,isParentRouted:a}=g(t);b||(b=e,x=r),_[e]=n,v.push(...i);let o=(p&&!a?th(_h(n,e),p,e,h):_h(n,e)).pipe(Y(([t,n])=>{let r=`${e}:${vh(t)}`,i=n[e]?.[Ic]??t,a=`${e}:${vh(i)}`;return[r,p?{...n,[Ic]:a,[e]:{...n[e],[Ic]:a}}:n]}));y=y?y.pipe(Ii(o)):o}return{alias:b,pipeline:y,collectionId:x,sources:_,sourceIncludes:v,directIncludes:[],isUnionFrom:!0,isParentRouted:p!==void 0}}function gh(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m=!1){if(e.queries.length===0)throw new as(`empty unionAll`);let h={},g=[],_=[],v,y=``,b=new Set;for(let g=0;g<e.queries.length;g++){let x=e.queries[g];for(let e of wh(x)){if(b.has(e.alias))throw Error(q(132,{alias:e.alias}));b.add(e.alias)}let S=sh([x,t,n,r,i,a,o,s,c,l,p,void 0],!0,m);y||=S.collectionId,Object.assign(u,S.aliasToCollectionId),Object.assign(d,S.aliasRemapping),_.push(...S.includes??[]),Object.assign(h,t);for(let[e,t]of S.sourceWhereClauses)f.set(e,t);let C=S.pipeline.pipe(Y(e=>{let[t,[n,r,i,a,o,s]]=e,c=`${g}:${vh(t)}`,l=`${g}:${vh(o??t)}`,u=p?Wc(n,i,a,l):n;return[c,s!==void 0&&s!==n&&Ac(u)?{...u,[Nc]:[s]}:u]}));v=v?v.pipe(Ii(C)):C}return{alias:``,pipeline:v,collectionId:y,sources:h,sourceIncludes:g,directIncludes:_,isUnionFrom:!0,isParentRouted:p!==void 0}}function _h(e,t){return e.pipe(Y(([e,n,r])=>[e,Kc(t,n,r)]))}function vh(e){let t=typeof e;return`${t}:${t===`string`||t===`number`||t===`bigint`?String(e):JSON.stringify(e)}`}function yh(e){return e instanceof rr?e.value:e}function bh(e){return e instanceof J&&e.path.length===1?[e.path[0]]:Ac(e)?Object.entries(e).flatMap(([e,t])=>e.startsWith(`__SPREAD_SENTINEL__`)&&t instanceof J&&t.path.length===1?[t.path[0]]:[]):[]}function xh(e){return Array.isArray(e)?[...e]:{...e}}function Sh(e,t,n,r){if(!Zc(e))return e;let i=e,a=r===void 0?t:r.reduce((e,n)=>t[n]??e,void 0),o=n&&typeof a==`object`&&a?a:void 0,s=i;for(let e of ml){let r=n&&e in i;if(!r&&(i[e]!=null||!(e in t)))continue;let a=r?o:t,c=a!==void 0&&e in a,l=c?a[e]:void 0;r&&c&&i[e]===l||(s===i&&(s=xh(i)),c?s[e]=l:delete s[e])}return s}function Ch(e,t,n){if(Dh(e.from,t.from,n),e.join&&t.join)for(let r=0;r<e.join.length&&r<t.join.length;r++)Dh(e.join[r].from,t.join[r].from,n)}function wh(e){return[..._r(e.from),...e.join?.map(e=>e.from)??[]]}function Th(e,t){let n=[],r=(e,t,n)=>{for(let[r,o]of Object.entries(e))r.startsWith(`__SPREAD_SENTINEL__`)?i(r,o,t,n):a(o,[...t,r],n)},i=(e,r,i,a)=>{let o=e.slice(19),s=o.lastIndexOf(`__`),c=s>=0?o.slice(0,s):o,l=r&&typeof r==`object`&&`type`in r&&r.type===`ref`?r.path:c.split(`.`).filter(Boolean);Eh(t,l)&&n.push({path:[...i,...t.slice(l.length)],guards:a})},a=(e,i,o)=>{e instanceof J&&Eh(t,e.path)?n.push({path:[...i,...t.slice(e.path.length)],guards:o}):e instanceof cr?kh(e,o,(e,t)=>a(e,i,t)):Mh(e)&&r(e,i,o)};return r(e,[],[]),n}function Eh(e,t){return t.length<=e.length&&t.every((t,n)=>e[n]===t)}function Dh(e,t,n){if(e.type===`unionAll`&&t.type===`unionAll`){for(let r=0;r<e.queries.length&&r<t.queries.length;r++){let i=e.queries[r],a=t.queries[r];n.set(i,a),Ch(i,a,n)}return}let r=_r(e),i=_r(t);for(let e=0;e<r.length&&e<i.length;e++){let t=r[e],a=i[e];t.type===`queryRef`&&a.type===`queryRef`&&(n.set(t.query,a.query),Ch(t.query,a.query,n))}}function Oh(e){let t=[];for(let[n,r]of Object.entries(e))n.startsWith(`__SPREAD_SENTINEL__`)||(Mh(r)?Nh(r,n):Ah(r,[n],[],t));return t}function kh(e,t,n){let r=[];for(let i of e.branches)n(i.value,[...t,...r,{condition:i.condition,expected:!0}]),r.push({condition:i.condition,expected:!1});e.defaultValue!==void 0&&n(e.defaultValue,[...t,...r])}function Ah(e,t,n,r){if(e instanceof sr){let i=jh(t.join(`.`),r);r.push({key:i,path:t,subquery:e,guards:n})}else if(e instanceof cr)kh(e,n,(e,n)=>Ah(e,t,n,r));else if(Mh(e))for(let[i,a]of Object.entries(e))i.startsWith(`__SPREAD_SENTINEL__`)||Ah(a,[...t,i],n,r)}function jh(e,t){let n=new Set(t.map(e=>e.key??e.fieldName));if(!n.has(e))return e;let r=t.length;for(;n.has(`${e}#${r}`);)r++;return`${e}#${r}`}function Mh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!ur(e)&&!Wn(e)}function Nh(e,t){for(let[n,r]of Object.entries(e))if(!n.startsWith(`__SPREAD_SENTINEL__`)){if(r instanceof sr)throw Error(q(133,{parentPath:t,key:n}));Mh(r)&&Nh(r,`${t}.${n}`)}}function Ph(e,t){if(t.length===0&&e instanceof sr)return new rr(null);if(e instanceof cr){let n=e.branches.map(e=>{let n=Ph(e.value,t);return Object.is(n,e.value)?e:{...e,value:n}}),r=e.defaultValue===void 0?void 0:Ph(e.defaultValue,t);return n.some((t,n)=>t!==e.branches[n])||!Object.is(r,e.defaultValue)?new cr(n,r):e}if(t.length===0||!Mh(e))return e;let[n,...r]=t,i=e[n],a=Ph(i,r);return Object.is(a,i)?e:{...e,[n]:a}}function Fh(e,t){let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}var Ih=()=>{};function Lh(e,t){return e?.[Lc]?.[t]}function Rh(e,t){let n=Lh(e.$selected,t);if(!n)throw Error(q(243));return n}function zh(e,t){let n=e.map(e=>({condition:il(e.condition),expected:e.expected}));return e=>(n.every(t=>ul(t.condition(e))===t.expected)?t(e):void 0)??{active:!1,correlationKey:null,parentContext:null}}function Bh(e,t){let n=[],r=e=>{if(e.type!==`func`)return;if(e.name===`and`){e.args.forEach(r);return}if(e.name!==`eq`&&e.name!==`in`)return;let[i,a]=e.args,o=i?.type===`ref`&&Vh(i.path,t.path)&&a instanceof rr?a.value:a?.type===`ref`&&Vh(a.path,t.path)&&i instanceof rr?i.value:void 0;o!==void 0&&n.push(new Set(Array.isArray(o)?o:[o]))};return e.where?.forEach(e=>r(pr(e))),n.length===0?new Set:new Set([...n[0]].filter(e=>n.slice(1).every(t=>t.has(e))))}function Vh(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Hh(e){return e.pipe(Y(([e,t])=>{let n=t;return[e,[n[0],n[1],n[2],n[3],n[0][Lc],n[4]]]}))}function Uh(e,t,n,r){return e.pipe(Y(([e,i])=>{let a=i,o=t?t(a[0]):a[5]??e;return[Er(n===`root`?[`root`,o]:[Gh(a[2],a[3],r),o]),{publicKey:o,tuple:a}]}),ja(e=>{let t=e.reduce((e,[,t])=>e+t,0);if(t===0)return[];if(t<0)throw Error(q(154));let n=e.find(([,e])=>e>0)?.[0];if(!n)throw Error(q(155));for(let[t,r]of e)r<=0||Wh(n,t);return[[n,1]]}),Y(([e,{publicKey:t,tuple:r}])=>[n===`root`?t:e,r]))}function Wh(e,t){let[n,r,i,a,o]=e.tuple,[s,c,l,u,d]=t.tuple;if(r!==c||!Bs(n,s)||!Bs(i,l)||!Bs(a,u)||!Bs(o,d))throw Error(q(156,{publicKey:e.publicKey}))}function Gh(e,t,n){return Er([n.equality(e??null),kc(t??null)])}function Kh(e,t){return{pipeline:Uh(Hh(e.pipeline),t,`root`,e.valueIdentity),facades:void 0}}var qh=e=>e.kind===`full-source`?e.status:e.kind,Jh=class extends Error{};function Yh(e){if(e instanceof Jh)throw e;Fu(e)}var Xh=class{constructor(e){this.cause=e}},Zh=class{constructor(e,t,n,r=()=>{},i=()=>!1,a,o=()=>!1){this.info=e,this.subscription=t,this.alias=n,this.f_=r,this.f0=i,this.getGraphInputRevision=a,this.hasPendingJoinedWork=o,this.aL=!1,this.settledSourcePrefix=[],this.gO=`none`,this.fT=!1,this.work={kind:`idle`},this.aF=new Map,this.a_=new Map,this.active=!0,this.orderedLoadGeneration=0,this.orderingInvalidationGeneration=0,this.authorityGeneration=0,this.F=!1,this.l=!1,this.cr=0,this.bG=!1,this.info.isRequesting=()=>this.fT,this.gp=e.sourceHoldsAllRows&&e.index!==void 0&&e.orderBy.length===1&&!e.joinedFilterSourceIds?.length}get ap(){return this.gO!==`none`}ae(e,t,n=this.gO){if(!t.includes(qh(this.work)))throw new Jh(`Ordered loader work cannot move from ${qh(this.work)} to ${qh(e)}`);this.work=e,this.gO=n,this.gQ()}gS(e){this.gO=e,this.gQ()}gQ(){let e=qh(this.work);if(e===`complete`&&this.gO!==`none`||e===`repair`&&this.gO===`none`||e===`failed`&&this.gO!==`full`)throw new Jh(`Ordered loader work ${e} cannot owe ${this.gO} debt`)}gL(){return this.work.kind===`full-source`&&this.work.status===`complete`}gK(){return this.work.kind===`repair`&&(this.work.epoch!==this.orderingInvalidationGeneration||this.gO===`full`)}onSourceChanges(e,t,n){let r=!1,i=!1;for(let a of e){let e=t?.get(a.key);if(a.type===`delete`&&this.l){let t=e===void 0||this.ah===void 0?1:this.info.comparator(e,this.ah);if(t>0||t===0&&this.settledSourcePrefix.every(({key:e})=>e!==a.key))continue}if(a.type!==`insert`&&e!==void 0&&(a.type===`delete`||this.info.comparator(e,a.value)!==0)){if(n(a.key))i=!0;else{this.invalidateSourceOrdering();return}}a.type!==`delete`&&e===void 0&&(r=!0)}i&&!this.info.sourceHoldsAllRows&&this.subscription.readOrderedSnapshot({orderBy:fu(this.info.orderBy,this.alias),limit:this.info.offset+this.info.limit}).filter(({key:e})=>!n(e)).length<this.info.offset+this.info.limit&&(this.F=!0,this.invalidateCursor()),r&&this.invalidateCursor()}start(){let{index:e,limit:t,offset:n,requiresFullSource:r}=this.info;e&&this.subscription.setOrderByIndex(e),t!==0&&(r?this.loadFullSource():e?this.fK(n+t):this.e$(n+t))}loadMore(e,t=!1){if(this.fT&&(this.W=this.getGraphInputRevision?.()),!this.active||this.info.limit===0||this.fT)return;if(e??=this.bN?.windowOperationGeneration,t||=this.bN?.continuesOrderedPrefixRepair??!1,this.info.joinedFilterSourceIds?.length&&this.hasPendingJoinedWork())return(e!==void 0||t)&&(this.bN={windowOperationGeneration:e,continuesOrderedPrefixRepair:t}),this.pending;if(this.bN=void 0,this.S&&(this.c3(e),!this.active||this.pending)||!(this.aj===void 0||e!==void 0&&e!==this.aj.windowOperationGeneration))return this.pending;if(this.work.kind===`full-source`&&this.work.status===`failed`&&this.ae({kind:`idle`},[`failed`]),(this.aj||this.a_.size>0)&&e!==void 0&&!t&&(this.cG(),this.cr=0,this.aj&&(this.aj.windowOperationGeneration=e),this.gP(this.a_,()=>!0)),this.work.kind!==`idle`&&!(t&&this.work.kind===`repair`))return e!==void 0&&(this.bN={windowOperationGeneration:e,continuesOrderedPrefixRepair:t}),this.pending;if(this.ap&&!(t&&this.work.kind===`repair`)||this.info.requiresFullSource)return this.gO===`bounded`&&!this.info.requiresFullSource?this.dw(e):this.loadFullSource(e),this.pending;if(!this.info.index)return e!==void 0||this.F||(this.info.dataNeeded?.(this.ah)??0)>0||this.bQ!==void 0&&this.bQ<this.info.offset+this.info.limit?(this.F=!1,this.e$(this.info.offset+this.info.limit,e,t)):t&&this.au(e),this.pending;if(!this.info.dataNeeded||this.pending)return this.pending&&e!==void 0&&(this.bN={windowOperationGeneration:e,continuesOrderedPrefixRepair:t}),t&&!this.pending&&this.au(e),this.pending;let n=Math.max(this.info.dataNeeded(this.ah),this.aL?0:this.info.offset+this.info.limit,+!!this.F);if(e!==void 0&&this.ah!==void 0){let e=this.info.offset+this.info.limit;n=Math.max(n,e-this.em())}return n>0?(this.F=!1,this.fK(n,e,t)):t&&this.au(e),this.pending}loadFullSource(e){this.active&&this.work.kind===`idle`&&(this.pending=void 0,this.ae({kind:`full-source`,status:`held`},[`idle`]),this.bY(e=>this.subscription.requestSnapshot(e),`full-source`,e))}dw(e){this.active&&this.work.kind===`idle`&&(this.pending=void 0,this.ae({kind:`repair`,epoch:this.orderingInvalidationGeneration},[`idle`]),this.gI=this.info.offset+this.info.limit,this.bY(e=>this.subscription.requestSnapshot({...e,orderBy:fu(this.info.orderBy,this.alias),limit:this.info.offset+this.info.limit,boundedPrefix:this.gp}),`ordered-repair`,e,!0,this.info.offset+this.info.limit))}e$(e,t,n=!1){if(!this.active||this.pending||this.S)return;let r=this.bQ??0;if(r>=e){if((this.info.dataNeeded?.(this.ah)??0)===0){n&&this.au(t);return}let i=this.subscription.readOrderedSnapshot({orderBy:fu(this.info.orderBy,this.alias),limit:r}).length;if(i<=(this.gZ??-1)){n&&this.au(t);return}this.gZ=i,e=r*2}this.bY(t=>this.subscription.requestSnapshot({...t,orderBy:fu(this.info.orderBy,this.alias),limit:e,boundedPrefix:this.gp}),`ordered`,t,n,e),this.bQ=e,this.gI=e}resetCursor(){this.cG(),this.cr=0,this.orderedLoadGeneration++,this.gL()&&this.ae({kind:`full-source`,status:`held`},[`complete`]),this.pending=void 0,this.bN=void 0,this.dl=void 0,this.ah=void 0,this.S=void 0,this.invalidateCursor()}settleFullSourceReplay(){if(this.work.kind===`repair`)this.au();else{if(this.work.kind===`full-source`&&this.work.status===`failed`)for(let[e,{kind:t}]of this.a_)t===`full-source`&&this.a_.delete(e);this.work.kind!==`idle`&&this.fN([`held`,`failed`,`complete`])}}fN(e){this.cG(),this.cr=0,this.ae({kind:`full-source`,status:`complete`},e,`none`),Pu([()=>this.aB(),()=>this.gH()])}aB(e,t){!this.gL()&&!e&&t===void 0||this.subscription.hasPendingTruncateReplacement||this.gP(this.aF,(n,{count:r,chain:i})=>t===void 0?this.gL()||e!==void 0&&n!==e.release&&r!==void 0&&r<=e.count:i!==t)}gH(){this.subscription.hasPendingTruncateReplacement||this.gP(this.a_,(e,{superseded:t})=>t)}gP(e,t){let n=this.orderedLoadGeneration,r=this.fT;this.fT=!0;try{Pu(Array.from(e,([r,i])=>()=>{if(n===this.orderedLoadGeneration&&t(r,i)){if(e.get(r)!==i)throw new Jh(`Ordered loader lease was released by another pass`);e.delete(r);try{r()}catch(e){Yh(e)}}}))}finally{this.fT=r}}invalidateCursor(){(this.S?.role??`finite`)===`finite`&&(this.S=void 0),this.eZ=void 0,this.bQ=void 0,this.gZ=void 0}invalidateSourceOrdering(){this.orderingInvalidationGeneration++,this.invalidateCursor(),this.dl=void 0,this.gO===`none`&&!this.gL()&&this.gS(this.aL&&this.work.kind===`idle`?`bounded`:`full`),this.ah=void 0}revalidateLoadedCoverage(){if(!this.aL)return;let e=this.he();e!==void 0&&((this.gI??0)>this.info.offset+this.info.limit||Object.is(this.info.valueExtractorForRawRow(e),this.dl))||this.invalidateSourceOrdering()}he(){let e=this.info.offset+this.info.limit;if((this.gI??0)<e||!this.info.dataNeeded||this.subscription.hasHeldSyncTransaction)return;let t=this.subscription.readOrderedSnapshot({orderBy:fu(this.info.orderBy,this.alias),limit:e+1});if(t.length<=e)return;let n=t[e-1].value;return this.info.comparator(t[e].value,n)>0&&this.info.dataNeeded(n)===0?n:void 0}au(e){if(this.work.kind!==`repair`)return;let t=this.work.epoch;if(this.gK())this.ae({kind:`idle`},[`repair`]),this.gO===`full`?this.loadFullSource(e):this.dw(e);else{this.l=!0;try{this.aB(void 0,t)}finally{this.l=!1;let e=[...this.aF.values()].some(({chain:e})=>e!==t);this.active&&e||(this.cG(),this.cr=0,this.ae({kind:`idle`},[`repair`],this.gK()?this.gO:`none`))}}}bi(){this.work.kind===`repair`&&this.ae({kind:`idle`},[`repair`],`full`)}dispose(){this.active=!1,this.resetCursor(),this.a_.clear(),this.aF.clear()}em(){return this.subscription.readOrderedSnapshot({orderBy:fu(this.info.orderBy,this.alias),limit:this.info.offset+this.info.limit}).filter(({value:e})=>this.info.comparator(e,this.ah)<=0).length}fK(e,t,n=!1){if(!this.active||this.pending||this.S)return;let r=this.ah===void 0,i=this.ah,a;if(i!==void 0){let e=this.info.valueExtractorForRawRow(i);if(!Vu(this.info.orderBy,[e])){this.e$(this.info.offset+this.info.limit,t,n);return}a=[e]}let o=a?.[0];this.eZ?.count===e&&Object.is(this.eZ.boundary,o)?n&&this.au(t):(this.eZ={count:e,boundary:o},this.gI=r?e:void 0,this.bY(t=>this.subscription.requestLimitedSnapshot({...t,orderBy:fu(this.info.orderBy,this.alias),limit:e,minValues:a,offset:r?0:this.em()}),`ordered`,t,n,e))}gM(e){return e.orderedLoadGeneration===this.orderedLoadGeneration?(e.role===`repair`?this.gR(e):e.role===`finite`&&e.orderingInvalidationGeneration!==this.orderingInvalidationGeneration)?`stale`:`current`:`dead`}gR(e){return e.authorityGeneration!==this.authorityGeneration}eI(e,t=e.windowOperationGeneration){if(this.active&&this.gM(e)===`current`){if(e.kind===`boundary`)this.fJ(t,e.continuesOrderedPrefixRepair);else{if(this.info.joinedFilterSourceIds?.length&&this.hasPendingJoinedWork()){this.S=e;return}this.loadMore(t,e.continuesOrderedPrefixRepair)}}}c3(e){let t=this.S;t&&(this.S=void 0,this.eI(t,e))}gJ(e){let t=this.getGraphInputRevision?.();return t===e||t===this.W}es(e){if(!this.bG){this.bG=!0;try{for(;this.S&&!this.pending&&this.gJ(e);)this.c3()}finally{this.bG=!1}}}fJ(e,t=!1){let n=this.ah;if(n===void 0)return t?this.loadMore(e,!0):void 0;let r=this.info.valueExtractorForRawRow(n),i=fu(this.info.orderBy,this.alias);if(!Vu(i.slice(0,1),[r]))return t&&this.bi(),this.loadFullSource(e),this.pending;if(Object.is(this.dl,r))return this.loadMore(e,t);let a=Bu(i,[r]);return a?(this.dl=r,this.bY(e=>this.subscription.requestSnapshot({...e,where:a}),`boundary`,e,t)):(t&&this.bi(),this.loadFullSource(e),this.pending)}dy(){this.ah=void 0,this.gL()||this.gS(`full`)}cG(){clearTimeout(this.dK),this.dK=void 0}eh(){if(!this.active||!this.f0()||this.cr>=2)return;let e=this.orderedLoadGeneration,t=this.aj;this.dK=setTimeout(()=>{this.dK=void 0;let n=Promise.resolve().then(()=>{this.active&&this.f0()&&e===this.orderedLoadGeneration&&this.aj===t&&(this.ae({kind:`idle`},[`idle`,`failed`]),this.gP(this.a_,()=>!0),this.active&&e===this.orderedLoadGeneration&&!this.subscription.hasPendingTruncateReplacement&&(this.aj=void 0,this.loadFullSource()))});n.catch(()=>{}),this.f_(n,!0,!0)},250*2**this.cr++)}d5(e){this.aj={windowOperationGeneration:e},this.S=void 0,this.bN=void 0,this.invalidateCursor(),this.dl=void 0}bY(e,t,n,r=!1,i){let a=t===`full-source`,o=t===`ordered-repair`,s=a||o||r,c;this.fT=!0,this.W=void 0;let l=!1,u=this.getGraphInputRevision?.(),d=this.orderingInvalidationGeneration;try{try{e({...(a?this.ap:s)?{refetch:!0}:{},trackLoadSubsetPromise:!1,onLoadSubsetResult:(e,t,n)=>{c={result:e,options:t,release:n}}})}finally{this.fT=!1}if((a||o)&&this.authorityGeneration++,!c)return;l=!0;let{result:f,options:p,release:m}=c,h=s&&this.aL&&this.ap&&n===void 0,g=(o||r)&&this.work.kind===`repair`?this.work.epoch:void 0,_={orderedLoadGeneration:this.orderedLoadGeneration,authorityGeneration:this.authorityGeneration,orderingInvalidationGeneration:d,role:a?`full-source`:s?`repair`:`finite`},v=f instanceof Promise,y=!v&&n===void 0&&(!s||(a?!this.ap:this.gp))&&u!==void 0,b,x=e=>({..._,kind:e,windowOperationGeneration:n,continuesOrderedPrefixRepair:r}),S=(e,t)=>{t?this.S=e:this.eI(e)},C=(e,c=!1)=>{e&&this.pending===e&&(this.pending=void 0),this.active&&Pu([()=>{if(!a){let e=p.orderBy&&!p.cursor?p.limit:void 0;if(this.aF.set(m,{count:e,chain:g}),this.aB(),!r&&this.gM(_)===`current`&&e!==void 0&&this.aB({release:m,count:e}),this.gM(_)===`stale`&&this.work.kind===`idle`&&!this.ap&&this.aF.delete(m)){this.l=!0;try{m()}catch(e){Yh(e)}finally{this.l=!1}}}},()=>{if(this.gM(_)===`current`&&(s||!this.aj&&this.work.kind===`idle`)){if(this.aj=void 0,t!==`boundary`&&(this.aL=!0,p.orderBy&&!p.cursor&&(this.bQ=p.limit),!a&&p.orderBy))try{let e=this.subscription.readOrderedSnapshot({...p,limit:i??p.limit}),t=e.at(-1)?.value;t&&(this.ah=t,this.settledSourcePrefix=e)}catch(e){if(y)throw b={error:e},e;w(e)}(o||r)&&(this.work.kind!==`repair`||this.gK())?this.au(n):(a&&this.fN([`held`,`complete`]),S(x(o||t===`ordered`?`boundary`:`more`),c))}}])},w=(e,r)=>{if(this.aF.delete(m),r&&this.pending===r&&(this.pending=void 0),a&&this.gL()||(this.dy(),this.gM(_)===`dead`))return;let i=s&&this.gM(_)===`current`&&(a||this.work.kind===`repair`);if((i||(this.S?.role??`finite`)===`finite`)&&(this.S=void 0),s?!i:this.gR(_)){if(this.a_.set(m,{kind:t,superseded:!0}),this.gL()&&this.gH(),this.invalidateCursor(),this.dl=void 0,this.aj===void 0&&this.work.kind===`idle`)try{this.loadFullSource(n)}catch(e){if(e instanceof Jh)throw e}throw e}throw a?this.ae({kind:`full-source`,status:`failed`},[`held`]):s&&this.ae({kind:`idle`},[`repair`]),this.d5(n),this.a_.set(m,{kind:t,superseded:!1}),h&&this.eh(),e};if(y){try{Pu([()=>C(void 0,!0),()=>{b||this.f_(!0,!1,!1)},()=>{!b&&this.gJ(u)&&this.es(u)}])}catch(e){throw b?b.error:new Xh(e)}return this.pending}let T=(v?f:Promise.resolve()).then(()=>C(T),e=>w(e,T));return this.pending=T,T.catch(()=>{}),this.f_(T,s&&this.ap,v,p),T}catch(e){if(e instanceof Xh)throw e.cause;if(e instanceof Jh)throw e;this.fT=!0;try{let t=Hu(e);l&&(this.orderedLoadGeneration++,this.pending=void 0),this.dy(),this.d5(n),s&&this.ae({kind:`idle`},[`held`,`repair`]);try{c?.release({error:t})}catch(e){Yh(e)}if(s&&this.aL&&(n===void 0&&this.eh(),!l)){let e=Promise.reject(t);e.catch(()=>{}),this.f_(e,!0,!0)}throw t}finally{this.fT=!1}}}};function Qh(e){let t={};for(let n of fr(e))t[n.collection.id]=n.collection;return t}function $h(e){return e.config.syncMode===`on-demand`||e.isReady()}function eg(e){let t=e.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`descriptorRef`)return Zn(t);if(t.type===`queryRef`)return eg(t.query);if(t.type===`unionFrom`)return eg({from:t.sources[0]});if(t.type===`unionAll`)return eg(t.queries[0]);throw Error(q(160))}function tg(e){return!(typeof e!=`object`||!e||ur(e)||Wn(e))}function ng(e){let t=typeof e.query==`function`?kp(e.query):ip(e.query);if(e.requireObjectResult&&t.select&&!tg(t.select))throw new ts;return t}function rg(e,t){let n=[];for(let e of t){let t=e.key;e.type===`insert`?n.push([[t,e.value],1]):e.type===`update`?(n.push([[t,e.previousValue],-1]),n.push([[t,e.value],1])):n.push([[t,e.value],-1])}return n.length!==0&&e.sendData(new Ci(n)),n.length}function*ig(e){for(let t of e)t.type===`update`?(yield{type:`delete`,key:t.key,value:t.previousValue},yield{type:`insert`,key:t.key,value:t.value}):yield t}function ag(e,t){let n=[];for(let r of e){let e=t.get(r.key);if(r.type===`insert`){if(e!==void 0)continue;t.set(r.key,r.value),n.push(r)}else if(r.type===`delete`){if(e===void 0)continue;t.delete(r.key),n.push({...r,value:e})}else t.set(r.key,r.value),n.push(e===void 0?{type:`insert`,key:r.key,value:r.value}:{...r,previousValue:e})}return n}function og(e,t,n){let{orderBy:r,limit:i,offset:a}=e,o=i!==void 0&&a!==void 0?i+a:i,s=r?fu(r,t):void 0,c=!(s?.some(e=>(e.compareOptions.stringSort??n.stringSort)===`custom`)??!1)&&(s?.every(e=>{let t=e.expression;if(t.type!==`ref`)return!1;let n=t.path;return Array.isArray(n)&&n.length===1})??!1);return{orderBy:c?s:void 0,limit:c?o:void 0}}var sg=class{constructor(e){this.fs=e,this.states=new Map,this.eO=new Set,this.valueIdentity=Cc()}clearRequestErrors(){for(let[e,t]of this.states)for(let n of t.keys.keys())this.fs?.(e,n)}setDemand(e,t,n){let r=lg(n,this.valueIdentity),i=this.states.get(t.id),a=i?.segments.some(e=>e.state===`failed`&&dg(e.keys,r));if(i&&ug(i.keys,r)&&!a)return{changed:!1,empty:r.size===0,ready:!0};let o=(i?.segments??[]).filter(e=>e.state!==`failed`&&dg(e.keys,r)&&(!e.replaces||ug(e.keys,r))),s=(i?.segments??[]).filter(e=>!o.includes(e)),c=i?.segments.some(e=>e.replaces&&e.state===`failed`&&ug(e.keys,r)),l={keys:r,segments:o};this.states.set(t.id,l);for(let e of i?.keys.keys()??[])r.has(e)||this.fs?.(t.id,e);let u=()=>hg(e,s);if(r.size===0)return this.states.delete(t.id),u(),{changed:!0,empty:!0,ready:!0};let d=new Set(o.flatMap(e=>[...e.keys.keys()])),f=new Map([...r].filter(([e])=>!d.has(e))),p=i?[...i.keys.keys()].some(e=>!r.has(e)):!1,m=c||p&&(f.size>0||o.length>1),h=m?r:f,g;try{if(h.size>0){let n=fg(t,h);m&&(n.replaces=[...o],g=n),o.push(n);let r=pg(e,n,()=>this.fB(t),e=>this.ha(t.id,n,e));if(this.states.get(t.id)!==l)return{changed:!1,empty:!1,ready:!0};if(!r)throw Error(q(159));m&&(e.replaceSnapshots(n.where,(n.replaces??[]).map(e=>e.where)),n.ready instanceof Promise?n.ready.then(()=>this.ep(e,t.id,n),()=>{}):this.ep(e,t.id,n))}}finally{u()}if(this.states.get(t.id)!==l)return{changed:!1,empty:!1,ready:!0};let _=(g?[g]:l.segments).filter(e=>e.state===`pending`&&dg(e.keys,r)).map(e=>e.ready).filter(e=>e instanceof Promise);return{changed:!0,empty:!1,ready:_.length>0?Promise.all(_):!0}}ha(e,t,n){let r=this.states.get(e);if(!r?.segments.includes(t))return;let i=r.segments.slice(r.segments.indexOf(t)+1);for(let a of t.keys.keys())r.keys.has(a)&&!(n&&i.some(e=>e.keys.has(a)))&&this.fs?.(e,a,n)}clear(){for(let e of this.states.values())for(let t of e.segments)t.abortController.abort();this.states.clear(),this.eO.clear(),this.valueIdentity=Cc()}hasPendingDemand(e){return this.states.get(e)?.segments.some(e=>e.state===`pending`)??!1}ep(e,t,n){let r=this.states.get(t);if(!r?.segments.includes(n)||!ug(n.keys,r.keys)){hg(e,[n]);return}let i=n.replaces??[];n.replaces=void 0,r.segments=[n],hg(e,i)}fB(e){}};function cg(e,t,n,r){return(t[e]?.plans?.some(e=>r(e.id))??!1)||n[e]?.status===`loadingSubset`}function lg(e,t){return new Map([...e].map(e=>[t.serializeEquality(e),e]))}function ug(e,t){return e.size===t.size&&[...e.keys()].every(e=>t.has(e))}function dg(e,t){return[...e.keys()].some(e=>t.has(e))}function fg(e,t){return{keys:t,where:Yl(new J(e.path),[...t.values()]),abortController:new AbortController,ready:!0,state:`starting`}}function pg(e,t,n,r){let i=!1;return e.requestSnapshot({where:t.where,signal:t.abortController.signal,trackLoadSubsetPromise:!1,onUnoptimized:n,onLoadSubsetResult:(n,a)=>{if(i=!0,!(n instanceof Promise)){t.state=`settled`;return}t.state=`pending`;let o=n=>{if(a.signal?.aborted)return mg(e).then(()=>{t.state=`settled`});if(t.state=n?`failed`:`settled`,e.pendingTruncateReplacement)return;let i=n&&Hu(n.error);if(r(i),i)throw i};t.ready=n.then(()=>o(),e=>o({error:e}))}})&&i}function mg(e){let t=e.pendingTruncateReplacement;if(!t)return Promise.resolve();let n=()=>mg(e);return t.then(n,n)}function hg(e,t){if(t.length!==0){for(let e of t)e.abortController.abort();e.releaseSnapshot(...t.map(e=>e.where))}}var gg=class{constructor(e,t,n,r){this.sourceId=e,this.alias=t,this.collection=n,this.fQ=r,this.gX=0,this.cI=0,this.az=new Map,this.fh=new Map,this.demand=new sg((e,t,n)=>{let r=`${e}:${t}`;n?this.fQ.reportFailedRequest(r,[n]):this.fQ.clearFailedRequest(r)})}owner(){return this.fQ.dependent()}subscribe(){let e=this.fQ.sourceWhereClausesCache?.get(this.sourceId);return this.fi(e?du(e,this.alias):void 0)}c_(){return!this.fQ.hasSubscriberOrPreload()}fi(e){let t=this.fQ.optimizableOrderByCollections[this.sourceId],n=(e,t)=>{let n=++this.gX,r=()=>!t?.signal?.aborted&&!t?.subscription?.pendingTruncateReplacement;if(Promise.resolve(e).then(()=>{n>this.cI&&r()&&this.fQ.settleRootLoad(this.sourceId)},()=>{r()&&(this.cI=this.gX)}),e instanceof Promise){let t=e.catch(async e=>{throw await Promise.resolve(),e});this.fQ.trackSubsetLoadPromise(t)}},r=e=>{if(this.fQ.isLazySource(this.sourceId)){e.status===`ready`&&this.fQ.scheduleGraphRun();return}let t=e.subscription;if(e.status===`loadingSubset`)this.d$(t);else{let e=this.az.get(t);e&&(this.az.delete(t),e.resolve())}},i=e=>{let t=this.fQ.recordSubsetError(e.error,!this.fQ.isLazySource(this.sourceId)&&this.fQ.liveQueryCollection?._lifecycle.inFirstLoad===!0);!this.fQ.isLazySource(this.sourceId)&&!e.subscription.pendingTruncateReplacement&&this.fQ.failRootLoad(this.sourceId,t)},a;if(t)a=this.da(e,t,r,n,i);else{let t=(this.collection.config.syncMode!==`on-demand`||this.fQ.query.limit!==0)&&!this.fQ.isLazySource(this.sourceId);a=this.ek(e,t,r,n,i),this.cQ(a)}return!this.fQ.isLazySource(this.sourceId)&&a.status===`loadingSubset`&&this.d$(a),a}cQ(e){this.fQ.currentSyncState.unsubscribeCallbacks.add(()=>{let t=this.az.get(e);t&&(this.az.delete(e),t.resolve());try{this.demand.clear()}finally{e.unsubscribe()}})}setDemand(e,t,n){let r=this.demand.setDemand(e,t,n);if(!r.changed)return;if(r.empty){this.fQ.retireDemand(t.id);return}let i=this.fQ.beginDemand(t.id,r.ready instanceof Promise),a=()=>this.fQ.settleDemand(t.id,i);r.ready instanceof Promise?r.ready.then(a,n=>this.fQ.failDemand(e,this.collection,t.id,i,n)):a()}dV(e){let t=ag(Array.isArray(e)?e:[...e],this.fh),n=this.fQ.currentSyncState.inputs[this.sourceId];rg(n,t)>0&&this.fQ.advanceGraphInputRevision(),this.fQ.scheduleGraphRun()}ek(e,t,n,r,i){let a=e=>{this.dV(e)},o=og(this.fQ.query,this.alias,this.fQ.queryCompareOptions);return this.collection.subscribeChanges(a,{...t&&{includeInitialState:t},whereExpression:e,onStatusChange:n,onLoadSubsetError:i,deferAcquisition:this.c_(),owner:this.owner(),truncateReplayPublication:this.ci(),orderBy:o.orderBy,limit:o.limit,onLoadSubsetResult:t?r:void 0})}da(e,t,n,r,i){let a={},o=this.collection.subscribeChanges(e=>{if(!a.current)return;let t=Array.isArray(e)?e:[...e];this.bk?.onSourceChanges(t,this.fh,e=>this.collection._hasOptimisticOverlay(e));let n=ig(t);this.dV(n)},{whereExpression:e,onStatusChange:n,onLoadSubsetError:i,deferAcquisition:this.c_(),owner:this.owner(),truncateReplayPublication:this.ci(e=>{let t=this.bk;e&&t?.resetCursor();let n=a.current?.pendingTruncateReplacement;if(n){let e=n.catch(e=>{if(!(e instanceof Cs))throw e});e.catch(()=>void 0),this.fQ.trackSubsetLoadOperationPromise(e)}this.fQ.trackOrderedLoadPromise(Promise.resolve().then(()=>t?.loadFullSource()),!0)})});a.current=o,this.cQ(o);let s=this.collection.on(`truncate`,()=>{this.bk?.resetCursor()}),c=this.collection.on(`loadedSubsets:invalidated`,()=>{let e=this.bk;e&&(e.revalidateLoadedCoverage(),this.fQ.scheduleGraphRunIfSyncRunCurrent(this.fQ.getSyncRunGeneration()))});return o.on(`unsubscribed`,()=>{s(),c(),a.current=void 0,this.bk?.dispose(),this.bk=void 0}),this.bk=new Zh(t,o,this.alias,(e,t,n,i)=>{e instanceof Promise&&this.fQ.trackOrderedLoadPromise(e,t&&n&&!o.hasPendingTruncateReplacement),r(e,i)},()=>this.fQ.liveQueryCollection?.status===`ready`&&!this.fQ.hasActiveWindowOperation(),()=>this.fQ.getGraphInputRevision(),()=>t.joinedFilterSourceIds?.some(e=>this.fQ.hasPendingJoinedWork(e))??!1),this.bk.start(),o}ci(e){let t=this.fQ.getSyncRunGeneration(),n=()=>t===this.fQ.getSyncRunGeneration(),r=(e=[])=>{e.length>0?this.fQ.failReplay(this.sourceId,e):this.fQ.settleReplayedRequests(this.sourceId),this.fQ.settleRootLoad(this.sourceId),this.demand.clearRequestErrors()};return{start:t=>e?.(t),siblingReplays:()=>this.fQ.siblingReplays(this.collection,this.sourceId),succeed:()=>{n()&&(this.bk?.settleFullSourceReplay(),r(),this.fQ.scheduleGraphRunIfSyncRunCurrent(t))},fail:e=>{n()&&r(e)}}}loadMoreIfNeeded(e){if((!e.hasPendingTruncateReplacement||this.fQ.hasActiveWindowOperation())&&this.fQ.optimizableOrderByCollections[this.sourceId])try{let e=this.bk?.loadMore(this.fQ.getActiveWindowOperationGeneration());e&&this.fQ.trackSubsetLoadOperationPromise(e)}catch(t){if(!Object.is(e.lastError,t))throw t}}d$(e){if(this.az.has(e))return;let t,n=new Promise(e=>{t=e});this.az.set(e,{resolve:t}),this.fQ.trackSubsetLoadPromise(n)}};function _g(e,t,n,r=nf()?.id??ju()){let i=[...t];if(r!==void 0)for(let e of i)e.scheduleGraphRun({contextId:r});Du.schedule({contextId:r,jobId:e,dependencies:i,run:n})}var vg=0,yg=class{constructor(e){this.config=e,this.fz=new WeakMap,this.cN=new WeakMap,this.br=!1,this.bq=0,this.cv=!1,this.al=!1,this.bh=new Set,this.eY=new Set,this.subscriptions=Ap(),this.lazySourcesCallbacks=Ap(),this.lazySources=new Set,this.aQ=new Map,this.fp=0,this.aG=new Set,this.ba=!1,this.dq=!1,this.syncRunGeneration=0,this.windowOperationGeneration=0,this.av=0,this.optimizableOrderByCollections=Ap(),this.id=e.id||`live-query-${++vg}`,this.query=ng({query:e.query,requireObjectResult:!0}),this.cV=this.query.orderBy?.length||this.query.singleResult?{offset:this.query.offset??0,limit:this.query.singleResult?Math.min(this.query.limit??1,1):this.query.limit??1/0}:void 0,this.bD=this.cV,this.collections=Qh(this.query),this.ai=fr(this.query),dr(this.query,this.eY),this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=bg(this.cN)),this.queryCompareOptions=eg(this.query).compareOptions,this.compareOptions=this.config.defaultStringCollation??this.queryCompareOptions,this.ef()}async reload(e=this.liveQueryCollection){if(e?.status===`crashed`)return e._sync.reload();let t=this.ai.map(({collection:e})=>e).filter((e,t,n)=>n.indexOf(e)===t&&hf(e.health).some(e=>e.error!==null)),n=e?.status===`idle`||e?.status===`cleaned-up`;if(await Promise.all(t.map(e=>e.reload())),n)return e.preload();(e?._lifecycle.problems.error||e?._lifecycle.reloading)&&await e._sync.reload()}dependent(){let e=this.liveQueryCollection;if(e)return this.g7??={kind:`live-query`,collection:e,get active(){return e.subscribers.length>0},end:()=>e.cleanup({dependents:!0})}}hasSubscriberOrPreload(){return this.liveQueryCollection?._hasSubscriberOrPreload()??!0}getSourceCollections(){return this.ai.map(({collection:e})=>e)}hasJoins(e){if(e.join&&e.join.length>0)return!0;if(e.from.type===`queryRef`){if(this.hasJoins(e.from.query))return!0}else if(e.from.type===`unionFrom`){for(let t of e.from.sources)if(t.type===`queryRef`&&this.hasJoins(t.query))return!0}else if(e.from.type===`unionAll`){for(let t of e.from.queries)if(this.hasJoins(t))return!0}return!1}getConfig(){let e=this;return{id:this.id,getKey:this.config.getKey||(e=>this.fz.get(e)??e.$key),sync:this.fE(),compare:this.compare,defaultStringCollation:this.compareOptions,gcTime:this.config.gcTime??5e3,autoIndex:this.config.autoIndex,defaultIndexType:this.config.defaultIndexType,schema:this.config.schema,onInsert:this.config.onInsert,onUpdate:this.config.onUpdate,onDelete:this.config.onDelete,startSync:this.config.startSync,singleResult:this.query.singleResult,utils:{get lastSubsetError(){return e.lastSubsetError},setWindow:this.setWindow.bind(this),getWindow:this.getWindow.bind(this),[Ns]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){let t=this.f$;if(!t)throw new Ds;if(this.query.singleResult){if(!this.query.orderBy?.length&&(e.offset??0)!==0)throw new Ds;if((e.limit??this.cV.limit)!==this.cV.limit)throw new Os}if(this.ag||this.br||Object.values(this.optimizableOrderByCollections).some(e=>e.isRequesting?.()))throw new ks;rp(e.limit);let n=this.L??this.bD??this.cV,r={offset:e.offset??n?.offset,limit:e.limit??n?.limit},i=++this.av,a=this.eV();if(a){let e=this.syncRuns(),t=(async()=>{for(let t=a;t;t=this.eV())try{await t}catch(t){if(!(t instanceof Cs)||e!==this.syncRuns())throw t}if(i!==this.av){await this.gE;return}let n=this.setWindow(r);this.gE=t,n!==!0&&await n})();return this.gE=t}if(this.eF())return this.gE=Promise.reject(this.lastSubsetError??Error(q(147)));let o=++this.windowOperationGeneration,s=this.liveQueryCollection?._sync.beginLoadSubsetOperation();for(let e of Object.values(this.optimizableOrderByCollections))for(let t of e.joinedFilterSourceIds??[])for(let e of this.lazySourcesCallbacks[t]?.plans??[]){let t=this.aQ.get(e.id)?.participant;t?.isPending()&&this.trackSubsetLoadOperationPromise(t.promise)}let c={generation:o,failed:!1};this.ag=c,this.dq=!1,this.aG.size===0&&(this.ba=!1);try{if(this.L=r,Nu(()=>{t(r),this.bx?.()}),c.failed)throw c.error}catch(e){throw o===this.windowOperationGeneration&&(this.dq=!0,this.L=this.bD),s?.cancel(),e}finally{this.ag=void 0}let l=s?.wait()??!0;return l===!0?(this.bD=r,this.gE=void 0,!0):this.gE=l.then(()=>(o===this.windowOperationGeneration&&(this.bD=r),i===this.av?void 0:this.gE),e=>{throw o===this.windowOperationGeneration&&(this.dq=!0,this.L=this.bD),e})}getWindow(){let e=this.bD??this.cV;if(this.f$&&e)return{offset:e.offset??0,limit:e.limit??0}}isLazySource(e){return this.lazySources.has(e)}beginDemand(e,t=!1){let n=++this.fp,r=this.aQ.get(e),i=t?Uu():void 0;return i&&(i.promise.catch(()=>{}),this.trackSubsetLoadOperationPromise(i.promise)),this.aQ.set(e,{generation:n,settled:!1,participant:i}),r?.participant?.resolve(),n}healthSources(){return this.ai.map(({sourceId:e,alias:t,collection:n})=>({id:e,alias:t,collection:n,...this.eY.has(e)?{kind:`include`}:{}}))}settleDemand(e,t){let n=this.aQ.get(e);if(n&&n.generation===t&&!n.settled){n.settled=!0;try{this.bx?.(),n.participant?.resolve()}catch(e){throw n.participant?.reject(e),e}}}hasPendingJoinedWork(e){return cg(e,this.lazySourcesCallbacks,this.subscriptions,e=>this.aQ.get(e)?.settled===!1)}failDemand(e,t,n,r,i){let a=this.aQ.get(n);if(!a||a.generation!==r)return;let o=this.recordSubsetError(i);a.participant?.reject(o),this.liveQueryCollection?._lifecycle.status===`ready`?(a.settled=!0,this.ai.some(e=>e.collection===t&&this.subscriptions[e.sourceId]?.hasPendingTruncateReplacement)&&e.failReplacement(o),this.bx?.()):this.failQuery(q(228,{planId:n,cause:o.message}),o)}recordSubsetError(e,t=!1){let n=Hu(e);return this.lastSubsetError=n,this.ag&&(this.ag.failed=!0,this.ag.error=n,this.ba=!0),t&&this.failQuery(q(229,{cause:n.message}),n),n}trackSubsetLoadPromise(e){this.liveQueryCollection._sync.trackLoadPromise(e)}trackSubsetLoadOperationPromise(e){this.liveQueryCollection._sync.trackLoadSubsetOperationPromise(e)}hasActiveWindowOperation(){return this.ag!==void 0}getActiveWindowOperationGeneration(){return this.ag?.generation}scheduleGraphRunIfSyncRunCurrent(e){e===this.syncRunGeneration&&this.currentSyncConfig&&this.currentSyncState&&this.scheduleGraphRun()}trackOrderedLoadPromise(e,t=!1){if(!t&&!this.ag&&this.liveQueryCollection?._lifecycle.inFirstLoad!==!0&&this.aG.size===0)return;let n=this.syncRunGeneration;this.aG.size===0&&(this.ba=!1),this.aG.add(e);let r=t=>{n===this.syncRunGeneration&&this.aG.delete(e)&&(t||(this.ba=!0),!this.ba&&this.aG.size===0&&this.scheduleGraphRun())};e.then(()=>r(!0),()=>r(!1))}retireDemand(e){let t=this.aQ.get(e);this.aQ.delete(e),t?.participant?.resolve()}failRootLoad(e,t){this.reportFailedRequest(`root:${e}`,[t])}settleRootLoad(e){this.clearFailedRequest(`root:${e}`)}settleReplayedRequests(e){this.settleRootLoad(e),this.clearFailedRequest(`replay:${e}`)}failReplay(e,t){this.reportFailedRequest(`replay:${e}`,t)||this.failQuery(t[0].message,t[0])}reportFailedRequest(e,t){let n=this.liveQueryCollection?._lifecycle;return n?.status===`ready`&&(n.reportRequestError(e,t),!0)}clearFailedRequest(e){this.liveQueryCollection?._lifecycle.clearRequestError(e)}syncRuns(){return[this.syncRunGeneration,...this.ai.map(({collection:e})=>e._sync.getSyncRunGeneration())].join()}siblingReplays(e,t){let n=this.ai.flatMap(n=>{let r=this.subscriptions[n.sourceId];return n.sourceId!==t&&n.collection===e&&r?.hasTruncateReplayWork&&r.pendingTruncateReplacement?[r.pendingTruncateReplacement]:[]});return n.length>0?Promise.allSettled(n):void 0}hasPendingSourceRecovery(){return Object.values(this.subscriptions).some(e=>e.hasPendingTruncateReplacement)}eV(){let e=Object.values(this.subscriptions).flatMap(e=>e.pendingTruncateReplacement?[e.pendingTruncateReplacement]:[]);return e.length>0?Promise.all(e).then(()=>void 0):void 0}eF(){return Object.values(this.subscriptions).some(e=>e.hasFailedTruncateReplacement)}getSyncRunGeneration(){return this.syncRunGeneration}advanceGraphInputRevision(){this.bq++}getGraphInputRevision(){return this.bq}maybeRunGraph(){if(!this.br){if(!this.currentSyncConfig||!this.currentSyncState)throw Error(q(148));this.br=!0;try{let e=this.syncRunGeneration,t=this.currentSyncConfig,{begin:n,commit:r}=t,i=this.currentSyncState,a=()=>e===this.syncRunGeneration&&this.currentSyncConfig===t&&this.currentSyncState===i;if(this.cv)return;if(i.subscribedToAllCollections){let e=!1;for(;i.graph.pendingWork()||!e;){if(i.graph.pendingWork()){try{i.graph.run()}catch(e){throw a()&&this.liveQueryCollection?._lifecycle.stoppedThisRun!==!0&&this.g0(q(212),e),e}if(!a())return}if(this.e_?.(),!a())return;e=!0}if(i.flushPendingChanges?.(),!a())return;i.messagesCount===0&&!this.al&&(n(),r()),this.bS(t)}}finally{this.br=!1}}}scheduleGraphRun(e){if(!this.currentSyncConfig||!this.currentSyncState)throw Error(q(149));let t=this.syncRunGeneration;_g(this,this.bh,()=>{t===this.syncRunGeneration&&this.currentSyncConfig&&this.currentSyncState&&this.maybeRunGraph()},e?.contextId)}fE(){return{rowUpdateMode:`full`,sync:this.fP.bind(this)}}fP(e){let t=++this.syncRunGeneration;this.liveQueryCollection=e.collection,this.al=e.collection._lifecycle.reloading,this.cv=!1,this.lastSubsetError=void 0,this.currentSyncConfig=e;let n={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},r=!1,i=()=>{if(!r){r=!0,this.syncRunGeneration===t&&this.syncRunGeneration++;try{Pu(n.unsubscribeCallbacks)}finally{n.unsubscribeCallbacks.clear(),this.fl()}}};try{let t=this.dC(e,n);this.currentSyncState=t;let r=e.collection.on(`loadingSubset:change`,t=>{t.isLoadingSubset||(this.bS(e),this.hasPendingSourceRecovery()&&this.bx?.())});n.unsubscribeCallbacks.add(r),this.e_=this.ev(e,t),this.bx=()=>this.scheduleGraphRun(),this.scheduleGraphRun()}catch(e){try{i()}catch{}throw e}return i}fl(){this.windowOperationGeneration++,this.currentSyncConfig=void 0,this.currentSyncState=void 0,this.bx=void 0,this.e_=void 0;let e=this.liveQueryCollection?._lifecycle;e?.reloading&&!e.hasStartedCleanup()?this.L=this.bD:(this.L=void 0,this.bD=this.cV),this.cv=!1,this.al=!1,this.d3=void 0,this.cY=void 0,this.dL=void 0,this.sourceWhereClausesCache=void 0,this.dg=void 0,this.ch=void 0,this.lazySources.clear();for(let e of this.aQ.values())e.participant?.reject(new Cs);this.aQ.clear(),this.aG.clear(),this.ba=!1,this.dq=!1,this.optimizableOrderByCollections=Ap(),this.lazySourcesCallbacks=Ap(),Object.keys(this.subscriptions).forEach(e=>delete this.subscriptions[e])}ef(){this.d3=new Mi;let e=Ap();for(let t of this.ai)e[t.sourceId]=this.d3.newInput();this.cY=e;let t=oh(this.query,this.cY,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,e=>{this.f$=e,this.L&&e(this.L)}),n=t.includes?.[0]?.runtime,r=this.config.getKey,i=n?n.materializeCompilation(t,r):r&&this.hasJoins(this.query)?Kh(t,r):{pipeline:t.pipeline,facades:void 0};this.dL=i.pipeline,this.sourceWhereClausesCache=t.sourceWhereClauses,this.dg=i.facades,this.ch=n;let a=this.ai.map(e=>e.sourceId).filter(e=>!Object.hasOwn(this.cY,e));if(a.length>0)throw new Es(a)}eA(){return this.d3&&this.cY&&this.dL||this.ef(),{graph:this.d3,inputs:this.cY,pipeline:this.dL}}dC(e,t){let{begin:n,commit:r}=e,{graph:i,inputs:a,pipeline:o}=this.eA(),s=new Map;o.pipe(Da(e=>{let n=e.getInner();t.messagesCount+=n.length,n.reduce(xg,s)}));let c=this.dg,l=this.ch,u=c&&l?l.createBucketFacades(this.id,c,e=>{t.messagesCount+=e}):void 0;return u&&t.unsubscribeCallbacks.add(()=>u.cleanup()),t.flushPendingChanges=()=>{let t=s.size>0,i=u?.hasPendingChanges()??!1,a=this.al;if(a&&!this.e8())return;let o=t||a;if(!o&&!i||this.dq||this.ba||this.hasPendingSourceRecovery()||this.aG.size>0||Object.values(this.optimizableOrderByCollections).some(e=>e.joinedFilterSourceIds?.some(e=>this.hasPendingJoinedWork(e))))return;for(let[e,{inserts:t,deletes:n}]of s)if(Math.abs(t-n)>1)throw Error(q(150,{key:e,change:t-n}));let c,l;try{c=u?.flush(),l=o?e.collection._deferPublication():void 0;let t=u?new Map([...s].map(([e,t])=>{let n={...t,value:u.resolve(t.value)};return t.previousValue!==void 0&&(n.previousValue=u.resolve(t.previousValue)),[e,n]})):s;if(c?.prepare(),o){n(a?{snapshot:a}:void 0);let i;t.forEach(this.fG.bind(this,e,t=>!a&&(i??=e.collection._state.createSyncedKeyLookup(),i(t)))),Sg(t)&&Cg(e.collection),r(),this.al=!1}}catch(e){throw l?.discard(),c?.rollback(),e}s=new Map;let d;for(let e of[l?.publish,c?.publish])if(e)try{e()}catch(e){d??=e}if(d!==void 0)throw d},i.finalize(),t.graph=i,t.inputs=a,t.pipeline=o,t}fG(e,t,n,r){let{write:i,collection:a}=e,{deletes:o,inserts:s,value:c,orderByIndex:l}=n;if(this.fz.set(c,r),l!==void 0&&this.cN.set(c,l),s&&o===0)i({value:c,type:`insert`});else if(s>o||s===o&&t(a.getKeyFromItem(c)))i({value:c,type:`update`});else if(o>0)i({value:c,type:`delete`});else throw Error(q(151))}dj(e,t,n,r){let{status:i}=r;if(i===`crashed`)this.g0(q(172,{collectionId:n}),r.collection._lifecycle.getSyncError());else if(i===`error`){if(this.liveQueryCollection?.status===`ready`)return;this.failQuery(q(260,{collectionId:n}),r.collection._lifecycle.getSyncError())}else i===`cleaned-up`?this.di(n):(i===`ready`&&Object.values(this.optimizableOrderByCollections).some(e=>e.joinedFilterSourceIds?.includes(t))&&this.bx?.(),this.bS(e))}di(e){if(this.cv)return;let t=Error(q(152,{collectionId:e,id:this.id}));return this.g0(t.message,t),t}bS(e){!this.cv&&this.e8()&&(this.al&&this.currentSyncState?.flushPendingChanges?.(),this.al||e.markReady())}e8(){let e=this.currentSyncState,t=this.eD(),n=[...this.aQ.values()].every(e=>e.settled),r=this.liveQueryCollection?.isLoadingSubset;return e?.subscribedToAllCollections===!0&&!e.graph.pendingWork()&&t&&n&&r!==!0&&!this.hasPendingSourceRecovery()}failQuery(e,t){this.gY(e)&&this.liveQueryCollection?._lifecycle.fail(t??Error(e))}g0(e,t){this.gY(e),this.liveQueryCollection?._lifecycle.crash(t??Error(e))}gY(e){return!this.cv&&(this.cv=!0,console.error(e),!0)}eD(){return this.ai.every(({collection:e})=>$h(e))}ev(e,t){if(this.ai.length===0)throw Error(q(153,{id:this.id}));let n=new Set,r=this.ai.map(r=>{let{sourceId:i,alias:a,collection:o}=r,s=o.id,c=Ls(o);c&&c!==this&&this.bh.add(c);let l=new gg(i,a,o,this),u=o.on(`status:change`,t=>{this.dj(e,i,s,t)});n.has(o)||(n.add(o),t.unsubscribeCallbacks.add(o.on(`health:change`,()=>this.liveQueryCollection?._emitHealthChange())));let d,f=o._onCleanupStart(()=>{d=this.di(s)});if(d)throw f(),u(),d;t.unsubscribeCallbacks.add(u),t.unsubscribeCallbacks.add(f),qu(o.status)&&this.dj(e,i,s,{type:`status:change`,collection:o,status:o.status,previousStatus:o.status});let p=l.subscribe();this.subscriptions[i]=p,p.isDeferringAcquisition()&&(t.unsubscribeCallbacks.add(this.liveQueryCollection._onFirstSubscriberOrPreload(()=>p.resumeDeferredAcquisition())),this.hasSubscriberOrPreload()&&p.resumeDeferredAcquisition());let m=this.lazySourcesCallbacks[i];if(m){m.setDemand=(e,t)=>l.setDemand(p,e,t);for(let e of m.plans??[])e.initialKeys.size>0&&!this.L?.offset&&m.setDemand(e,e.initialKeys)}return l.loadMoreIfNeeded.bind(l,p)});return t.subscribedToAllCollections=!0,()=>Pu(r)}};function bg(e){return(t,n)=>{let r=e.get(t),i=e.get(n);return r&&i?r<i?-1:+(r>i):0}}function xg(e,[[t,n],r]){let[i,a]=n,o=e.get(t)||{deletes:0,inserts:0,value:i,orderByIndex:a};return r<0?(o.deletes===0&&(o.previousValue=i,o.previousOrderByIndex=a),o.deletes+=Math.abs(r)):r>0&&(o.inserts+=r,o.value=i,a!==void 0&&(o.orderByIndex=a)),e.set(t,o),e}function Sg(e){for(let t of e.values())if(t.inserts>0&&t.deletes>0&&t.previousValue!==void 0&&Bs(t.previousValue,t.value)&&t.orderByIndex!==t.previousOrderByIndex)return!0;return!1}function Cg(e){e._markLayoutChange()}function wg(e){return new yg(e).getConfig()}function Tg(e){if(typeof e==`function`)return Eg(wg({query:e}));{let t=e,n=wg(t);return t.utils&&Object.defineProperties(n.utils,Object.getOwnPropertyDescriptors(t.utils)),Eg(n)}}function Eg(e){let t=Cf(e),n=Fs(e);return n&&Is(t,n),t}var Dg={state:void 0,data:void 0,collection:void 0,layoutRevision:0,status:`disabled`,isLoading:!1,isReady:!0,isIdle:!1,isLoadingError:!1,isCrashed:!1,isCleanedUp:!1,isEnabled:!1,isSyncError:!1,health:void 0},Og=class{constructor(e,t,n,r,i,a){if(this.aD=!0,this.eN=!1,this.bp=Dg,this.layoutRevision=0,this.subscriptions=new Set,this.aE=[],this.b4=!1,this.bC=!1,this.fV=!1,this.cu=null,this.disposed=!1,e&&(!Number.isFinite(e._stateRevision)||!Number.isFinite(e._layoutRevision)))throw Error(q(262));this.collection=e,this.wholesale=t,this.onPreload=i,this.aO=n?._bindLiveQueryObserver(e,r,a,{observer:this,read:e=>this.getSnapshot(e),entries:()=>e?this.cH(e):[],isAttached:()=>this.fV,isDisposed:()=>this.disposed,dirty:()=>{this.aD=!0},publish:(t,n)=>{let r=n&&e?e._stateRevision:void 0,i=n&&e?e._layoutRevision:void 0;this.emit(this.wholesale?void 0:t,void 0,n,e?.status,r,i,n!==void 0)},preload:()=>this.bs()}),this.aO?.registerResource()}getSnapshot(e=!1){let t=this.collection;if(!t)return Dg;if(this.aO?.sync(e),this.fV||this.d6(t),this.eN!==e&&this.aO?.seed&&qu(this.cs??t.status)&&(this.aD=!0),this.aD){let n=this.cH(t),r=this.dB;if(!r||r.entries!==n){let e=r?.entries;(e?.length!==n.length||n.some(([t],n)=>e[n][0]!==t))&&this.layoutRevision++,r=this.dB={entries:n,data:n.map(([,e])=>e)}}let i=Ku(t),a=this.cs??t.status,o=this.aO?.failed?`error`:this.aO?.seed&&(e||!qu(a))?this.aO.seed.snapshot.status??`ready`:a;this.eN=e;let s=this.aU?this.aU.tree:t.health;this.bp={get state(){return r.state??=new Map(r.entries)},data:i?r.data[0]:r.data,collection:Gu(t),layoutRevision:this.layoutRevision,status:o,...Ju(o,s),isEnabled:!0},this.aD=!1}return this.bp}getServerSnapshot(e=!1){return this.aO?.getServerSnapshot(e)??this.getSnapshot()}getError(){return this.aO?.sync(),this.aO?.error}dehydrate(){let e=this.collection;return e?{rows:(this.aO?.seed&&this.aO.seed.snapshot.status===void 0?this.aO.seed.entries:this.cZ(e).entries).map(([e,t])=>({key:e,value:t}))}:{rows:[]}}cH(e){return this.aO?.seed?this.aO.seed.entries:this.cT??this.eQ(e)}cZ(e){let t=e._stateRevision,n=e._layoutRevision;return{entries:this.cT&&t===this.ca&&n===this.bu?this.cT:Array.from(e.entries()),revision:t,layoutRevision:n}}eQ(e){let{entries:t,revision:n,layoutRevision:r}=this.cZ(e);return this.bF(t,n,r),this.cT}bF(e,t,n){(this.cT===void 0||t!==this.ca||n!==this.bu)&&(this.cT=e,this.aD=!0),this.ca=t,this.bu=n}d6(e){let t=e.status;this.eQ(e),(this.cs!==t||this.bp.health!==e.health)&&(this.cs=t,this.aD=!0)}subscribe(e){if(this.disposed)throw new oo;this.subscriptions.size===0&&this.aO?.assertSources();let t={listener:e,active:!0},n=()=>{t.active&&(t.active=!1,this.subscriptions.delete(t),this.subscriptions.size===0&&this.gC())};this.subscriptions.add(t);let r=!this.fV;try{r?this.gF():this.wholesale||this.seed(t)}catch(e){throw r&&this.gC(),n(),e}return n}seed(e){let t=this.collection;if(!t)return;let n=[];for(let[e,r]of this.cH(t))n.push({type:`insert`,key:e,value:r});n.length!==0&&this.emit(n,[e])}gF(){let e=this.collection;if(!e||this.disposed)return;let t=[],n=()=>Pu(t.splice(0));this.cu=n;let r=e=>{this.cu===n?t.push(e):e()};this.aO?.registerResource(),this.aO?.sync(),this.d6(e),this.fV=!0,this.cs??=e.status,this.cm=e._layoutRevision;let i=!!this.aO?.seed;this.bC=this.wholesale||i;let a=(t,n=e.status,r=!1)=>{if(this.disposed||this.subscriptions.size===0)return;if(this.aO?.seed){qu(n)&&!this.bC?this.aO.handoff():(n===`ready`||qu(n))&&this.aO.scheduleHandoff();return}n===`ready`&&!e.isLoadingSubset&&this.aO?.markAuthoritative();let i=e._layoutRevision,a=r;if(!r&&t!==void 0&&t.length===0){if(i===this.cm)return;a=!0}t!==void 0&&(this.cm=i);let o=t!==void 0||n===`cleaned-up`?this.cZ(e):void 0;this.emit(t,void 0,o?.entries,n,o?.revision,i,a)},o=()=>e.health;this.aU={tree:o()},r(()=>{this.aU=void 0}),r(e.on(`status:change`,({status:e})=>{this.aU={tree:o()},a(void 0,e)})),r(e.on(`health:change`,()=>{let t=o();t!==this.aU?.tree&&(this.aU={tree:t},this.aD=!0,a(void 0,e.status))})),e._subscribeLayoutChanges&&r(e._subscribeLayoutChanges(()=>a([],e.status,!0))),this.aO&&(r(this.aO.subscribe()),r(e.on(`loadingSubset:change`,()=>{this.aO?.seed&&this.aO.scheduleHandoff()})));let s=e.subscribeChanges(e=>a(e),{includeInitialState:!this.wholesale&&!i});r(()=>s.unsubscribe()),this.bC=!1,this.cu===n&&((this.wholesale||i)&&(this.er(!this.wholesale),this.eQ(e)),this.aO?.seed&&(this.wholesale||this.seed(Array.from(this.subscriptions)[0]),(e.status===`ready`||qu(e.status))&&this.aO.scheduleHandoff()))}gC(){let e=this.cu,t=this.aO?.takeResourceRelease();this.cu=null,this.fV=!1,this.bC=!1,this.aE.length=0,Pu([()=>e?.(),()=>t?.()])}emit(e,t=Array.from(this.subscriptions),n,r=this.collection?.status??`cleaned-up`,i,a,o=!1){this.aE.push({changes:e,targets:t,entries:n,status:r,collectionRevision:i,collectionLayoutRevision:a,layoutChanged:o}),!(this.b4||this.bC)&&this.er()}er(e=!0){if(this.b4)return;let t;this.b4=!0;try{for(;this.aE.length>0;){let n=this.aE.shift();if(n.entries&&this.bF(n.entries,n.collectionRevision,n.collectionLayoutRevision),n.layoutChanged&&(this.aD=!0),this.cs!==n.status&&(this.cs=n.status,this.aD=!0),e)for(let e of n.targets){if(this.disposed)break;try{e.listener(n.changes)}catch(e){t??={error:e}}}}}finally{this.b4=!1}if(t)throw t.error}preload(){return this.aO?.preload()??this.bs()}bs(){if(this.preloadPromise)return this.preloadPromise;this.onPreload?.();let e=this.collection?.preload()??Promise.resolve();this.preloadPromise=e;let t=()=>{this.preloadPromise===e&&(this.preloadPromise=void 0)};return e.then(t,t),e}dispose(){if(!this.disposed){this.disposed=!0,this.gC();for(let e of this.subscriptions)e.active=!1;this.subscriptions.clear(),this.aE.length=0}}};function kg(e,t={}){return new Og(e??null,t.mode===`wholesale`,t.client,t.queryHash,t.onPreload,t.suspendUntilReady===!0)}function Ag(e){let{pool:t}=e;if(t!==void 0&&typeof t?.createPooledLiveQuery!=`function`)throw new Ms;return t}function jg(e,t){try{e&&Ng(e)}catch{}throw t}function Mg(e,t){if(t.size===0)return;let n=new Set(t),r=()=>{try{Ng(n)}catch{}},i=e.config.gcTime??3e5;if(i>0&&Number.isFinite(i)&&e.status!==`idle`)return e.once(`status:cleaned-up`,r);let a=setTimeout(r,50);return()=>clearTimeout(a)}function Ng(e,t=!1){let n=Array.from(e);e.clear();let r;for(let e of n)try{if(e._resumeSyncStart(),t&&qu(e.status))throw e._lifecycle.getSyncError()}catch(e){r??={error:e}}if(r)throw r.error}function Pg(e,t,n){if(typeof e==`function`)return Pg(e(new fp),t,n);if(e instanceof fp)return e._bindCollectionSources(t?e=>{let r=e,i=n?t._materializeCollectionForRender(r):t.collection(r);return n&&i._deferSyncStart()&&n.add(i),i}:void 0);if(e&&typeof e==`object`&&!Wu(e)&&`query`in e){let r=Ag(e),{query:i,queryKey:a,client:o,pool:s,...c}=e,l=Pg(i,t,n);return l==null?l:{...c,...r&&!t?{pool:r}:{},query:l}}return e}function Fg(e,t){if(Wu(e))return[e];let n=zg(e)?.query??e;return n instanceof fp?dr(n._getQuery()).map(e=>e.type===`descriptorRef`&&t?t(e.alias):Zn(e)):Wu(n)?[n]:[]}function Ig(e,t){if(Wu(e))return[`collection`,e.id];if(e instanceof fp){let n=t?.getPooledQueryIdentity(e);return n===void 0?[`query`,Up(e)]:[`pooled`,n]}if(e&&typeof e==`object`&&`query`in e){let t=e;return[`config`,Ig(t.query,Ag(t)),[`singleResult`,t.singleResult===!0],[`defaultStringCollation`,tc(t.defaultStringCollation)]]}return e==null?[`disabled`]:[`value`,e]}function Lg(e,t){if(t?.length){let n=zg(e)?.query,r=Wu(e)?Fs(e.config)?.getWindow():n instanceof fp?n._getQuery():void 0,i=[`queryKey`,t];return r&&(r.limit!==void 0||(r.offset??0)!==0)&&i.push({limit:r.limit,offset:r.offset??0}),Wp(i,`queryKey`)}return Wp(Wu(e)?[`collection`,e.id]:[`derived`,Ig(e)],`queryKey`)}var Rg=new WeakMap;function zg(e){return e instanceof fp?{query:e}:e&&typeof e==`object`?e:void 0}function Bg(e,t,n){if(!t||t.status!==`ready`&&t.status!==`loading`)return;let r=n&&Rg.get(n);if(!r||r.collection!==t)return;let i=r.config;if(!(i.query instanceof fp)||!(e?.query instanceof fp))return;let a=i.query._getQuery(),o=e.query._getQuery(),s=o.limit,c=o.offset??0;if(e.singleResult===!0||o.singleResult||!o.orderBy?.length||a.limit===void 0||s===void 0||!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(c)||c<0)return;let l=Object.keys(i);if(l.length!==Object.keys(e).length||l.some(t=>t!==`query`&&i[t]!==e[t]))return;let u=Fg(i),d=Fg(e);if(u.length!==d.length||u.some((e,t)=>e!==d[t]))return;try{if(Gp({...a,limit:void 0,offset:void 0})!==Gp({...o,limit:void 0,offset:void 0}))return}catch(e){if(e instanceof As)return;throw e}let f=Fs(t.config);if(f)return()=>{queueMicrotask(()=>{if(Rg.get(n)?.collection!==t||t.subscriberCount===0)return;let e=f.setWindow({offset:c,limit:s});e!==!0&&e.catch(()=>{})})}}function Vg(e,{gcTime:t,pool:n,startSync:r=!0,previousCollection:i,windowOwner:a,onWindowChange:o}={}){i!==void 0&&(e=Pg(e,void 0));let s=zg(e),c=Bg(s,i,a);if(c)return o?o(c):c(),i;if(e==null)return null;if(Wu(e))return e.startSyncImmediate(),e;if(s){let e=Ag(s),{pool:o,...c}=s,l=n===!1?void 0:e??n,u=l&&typeof c.query==`function`?c.query(new fp):void 0,d=u instanceof fp?{...c,query:u}:c,f=(l&&d.query instanceof fp&&Object.keys(d).every(e=>e===`query`||e===`gcTime`)?l.createPooledLiveQuery(d.query,{gcTime:d.gcTime??t}):void 0)??Tg({...d,startSync:d.startSync??r,gcTime:d.gcTime??t});return i!==void 0&&a&&Rg.set(a,{collection:f,config:s}),f}throw Error(q(102,{type:typeof e}))}var Hg=Symbol.for(`@tanstack/db.collectionConfig.factory`);function Ug(e,t,n){return Object.defineProperty(e,Hg,{value:t,enumerable:!1}),n&&Object.defineProperty(e,Ha,{value:n,enumerable:!0}),e}function Wg(e){let t=e&&typeof e==`object`&&!Wu(e)?e.queryKey:void 0;return Array.isArray(t)&&t.length>0?t:void 0}var Gg=new WeakMap,Kg=0;function qg(e){let t=Gg.get(e);return t===void 0&&(t=++Kg,Gg.set(e,t)),t}var Jg={};function Yg(){return new WeakMap}function Xg(e,t,n,r){let i=n??Jg,a=e.get(i),o=new Map;for(let e of t){let t=qg(e),n=o.get(e.id)??a?.get(e.id);if(n!==void 0&&n!==t)throw new js(r,e.id);o.set(e.id,t)}let s=a??new Map;for(let[e,t]of o)s.set(e,t);e.set(i,s)}function Zg(e,t,n=Ig){let r=n(e);return Xg(t.claims,Fg(e,t.onUnboundDescriptor),t.client,t.bindingName),r}var Qg=`@tanstack/db/sync-persistence`;function $g(e){return typeof e==`object`&&!!e}function e_(e,t,n=t){if(typeof e[t]!=`function`)throw new qa(`${n} must be a function`)}function t_(e){if(e===null)return null;if(!$g(e))throw new qa(`expected null or a complete capability object`);if(e.protocol!==`@tanstack/db/sync-persistence`)throw new qa(`protocol must be "${Qg}"`);if(e.version!==1)throw new qa(`version must be 1`);if(e.managedCacheGeneration!==void 0&&typeof e.managedCacheGeneration!=`boolean`)throw new qa(`managedCacheGeneration must be a boolean`);if(e.startupCacheGenerationRotated!==void 0&&typeof e.startupCacheGenerationRotated!=`boolean`)throw new qa(`startupCacheGenerationRotated must be a boolean`);e_(e,`hydrateBaseline`),e.startScopedRecovery!==void 0&&e_(e,`startScopedRecovery`),e_(e,`reserveCommitTurn`),e_(e,`scanPersistedRows`);let t=e.resumeSnapshot;if(!$g(t))throw new qa(`resumeSnapshot must be an object`);return e_(t,`certify`,`resumeSnapshot.certify`),e_(t,`getKeySetEvidence`,`resumeSnapshot.getKeySetEvidence`),e_(t,`expectCurrentCommit`,`resumeSnapshot.expectCurrentCommit`),t.expectSourceProgress!==void 0&&(e_(t,`expectSourceProgress`,`resumeSnapshot.expectSourceProgress`),e_(t,`getSourceProgressCompatible`,`resumeSnapshot.getSourceProgressCompatible`)),e}function n_(e){let{onMutate:t,mutationFn:n,strategy:r,...i}=e,a=null,o=new WeakMap,s;function c(e=!1){if(!e&&a?.state===`pending`)return a;let t=tf({...i,mutationFn:n,autoCommit:!1});return o.set(t,t.commit.bind(t)),t.commit=()=>{throw new wo},e||(a=t),t}function l(e,t){if(a===e&&(a=null),e.state===`failed`)return e;if(e.state!==`pending`)throw Error(q(107,{state:e.state}));let n=o.get(e);if(!n)throw Error(q(108));let r=n();return t?.(r),r.catch(()=>{}),e}function u(e,n,r){let i=s;i?.transaction===e&&(i.admittedNestedCall=!0);let o={transaction:e,admittedNestedCall:!1};s=o;try{e.mutate(()=>t(n))}catch(t){throw(r||o.admittedNestedCall)&&(e.rollback({error:Hu(t),isSecondaryRollback:!o.admittedNestedCall}),a===e&&(a=null)),t}finally{s=i}}function d(e){if(r._type===`debounce`||r._type===`throttle`){let t,n,i=()=>{if(t)return t;let n=a;return t=c(),u(t,e,t!==n),t};if(r.execute(()=>l(i(),e=>{n=e}),i,()=>n)!==!1)return i();let o=c(!0);return u(o,e,!0),o.rollback({error:r._type===`debounce`?new Oo:new Do,isSecondaryRollback:!0}),o}let t=a,n=c(r._type===`queue`);u(n,e,n!==t);try{let e,t=r.execute(()=>l(n,t=>{e=t}),void 0,()=>e);r._type===`queue`&&t===!1&&n.rollback({error:new To,isSecondaryRollback:!0})}catch(e){if(!(e instanceof Eo))throw e;n.rollback({error:e,isSecondaryRollback:!0})}return n}return d}function r_(e,t){let n=e();return t?.()??n.when(`settled`)}var i_=class{constructor(e,t={}){if(this.fn=e,this.options=t,this.items=[],this.timeoutId=null,this.isRunning=!0,this.pendingTick=!1,this.addItem=(e,t=this.options.addItemsTo,n=!0)=>{if(this.items.length>=this.options.maxSize)return!1;if(this.options.getPriority){let n=this.options.getPriority(e);if(n!==void 0){let t=this.items.findIndex(e=>(this.options.getPriority(e)??-1/0)<n);t===-1?this.items.push(e):this.items.splice(t,0,e)}else this.insertAtPosition(e,t)}else this.insertAtPosition(e,t);return n&&this.isRunning&&!this.pendingTick&&this.tick(),!0},this.insertAtPosition=(e,t)=>{t===`front`?this.items.unshift(e):this.items.push(e)},this.getNextItem=(e=this.options.getItemsFrom)=>{if(this.items.length===0)return;let t;return t=this.options.getPriority||e===`front`?this.items.shift():this.items.pop(),t},this.execute=e=>{let t=this.getNextItem(e);return t!==void 0&&this.fn(t),t},this.tick=()=>{if(!this.isRunning)this.pendingTick=!1;else{for(this.pendingTick=!0;this.items.length>0&&this.execute(this.options.getItemsFrom)!==void 0;){let e=this.options.wait;if(e>0){this.timeoutId=setTimeout(()=>this.tick(),e);return}}this.pendingTick=!1}},this.start=()=>{this.isRunning=!0,!this.pendingTick&&this.items.length>0&&this.tick()},this.stop=()=>{this.clearTimeout(),this.isRunning=!1,this.pendingTick=!1},this.clearTimeout=()=>{this.timeoutId&&=(clearTimeout(this.timeoutId),null)},this.peekNextItem=(e=`front`)=>{if(this.items.length!==0)return this.options.getPriority||e===`front`?this.items[0]:this.items[this.items.length-1]},this.peekAllItems=()=>[...this.items],this.flush=(e=this.items.length,t)=>{this.clearTimeout();for(let n=0;n<e&&this.items.length>0;n++)this.execute(t);this.isRunning&&this.items.length>0&&!this.pendingTick&&this.tick()},this.flushAsBatch=e=>{let t=this.peekAllItems();this.clear(),e(t)},this.clear=()=>{this.items=[]},this.options.addItemsTo=this.options.addItemsTo??`back`,this.options.getItemsFrom=this.options.getItemsFrom??`front`,this.options.maxSize=this.options.maxSize??1/0,this.options.started=this.options.started??!0,this.options.wait=this.options.wait??0,this.isRunning=this.options.started,this.options.initialItems)for(let e of this.options.initialItems)this.addItem(e,this.options.addItemsTo,!1);this.isRunning&&this.items.length>0&&this.tick()}get size(){return this.items.length}get isEmpty(){return this.items.length===0}get isQueueRunning(){return this.isRunning}};function a_(e){let t=Promise.resolve(),n=!1,r=new i_(({run:e,onCommit:n})=>{t=t.then(async()=>{await r_(e,n)}).catch(()=>{})},{wait:e?.wait??0,maxSize:e?.maxSize,addItemsTo:e?.addItemsTo??`back`,getItemsFrom:e?.getItemsFrom??`front`,started:!0});return{_type:`queue`,options:e,execute:(e,t,i)=>{if(n)throw new Eo;return r.addItem({run:e,onCommit:i})},cleanup:()=>{n=!0,r.isEmpty&&r.stop()}}}var Q=t(),o_=(0,K.createContext)(void 0);function s_(){return(0,K.useContext)(o_)}function c_(e,t){if(!e)return e=>{throw Error(`[${t}] Collection descriptor "${e}" requires a DbClient when the query is consumed. Wrap this component in <DbProvider client={client}> or use a concrete Collection.`)}}function l_(e,t,n){return Fg(e,c_(t,n))}var u_=typeof window>`u`?K.useEffect:K.useLayoutEffect,d_=1,f_=5e3,p_=Symbol(`unpreparedQueryValue`);function m_(e,t,n){return{claims:e,client:t,bindingName:n,onUnboundDescriptor:c_(t,n)}}function h_(e,t,n,r){let i=Pg(e,n.client,r);try{return{value:i,identityDeps:[`derived`,Zg(i,n)]}}finally{}}function g_(e){return __(e)}function __(e,t){let n=t!==void 0,r=s_(),i=Wu(e),a=(i||typeof e!=`object`?void 0:e?.client)??r,o=(0,K.useRef)(null),s=o.current??={collection:null,identityDeps:null,derivedIdentityProfiler:void 0,deferredCollections:new Set,sourceIds:Yg()},c=()=>{s.cancelReclaimRelease?.(),s.cancelReclaimRelease=void 0,Ng(s.deferredCollections)};try{let r=i?void 0:Wg(e),o=p_,l;if(r)l=r;else if(i)l=[];else{let t=h_(e,s.derivedIdentityProfiler,m_(s.sourceIds,a,`useLiveQuery`),s.deferredCollections);o=t.value,l=t.identityDeps}let u=t?.needsOwnCollection||!s.collection||(i?s.config!==e:s.client!==a||!Bs(s.identityDeps,l));u&&!i&&o===p_&&(o=Pg(e,a,s.deferredCollections));let d=s.queryHash,f,p;u&&(d=r?Lg(o,r):Wp(i?[`collection`,e.id]:l,`queryKey`),i?(e.startSyncImmediate(),s.collection=e):(p=(e,t)=>{!a&&r!==void 0&&l_(o,a,`useLiveQuery`);let i=Vg(o,{gcTime:n?f_:d_,pool:n||a?!1:void 0,previousCollection:e&&s.client===a?s.collection:null,windowOwner:t,onWindowChange:e=>{f=e},startSync:!n||a!==void 0});return i&&!Wu(o)&&(s.cancelReclaimRelease?.(),s.cancelReclaimRelease=Mg(i,s.deferredCollections)),i},s.collection=t?t.resolve(o,d,a,p):p(!0,s),f||(s.identityDeps=[...l])),s.config=e,s.client=a,f||(s.queryHash=d)),f&&!a&&(u=!1);let m=s.observer,h=s.subscribe,g=()=>{m=kg(s.collection,{mode:`wholesale`,client:a,queryHash:d,onPreload:c,suspendUntilReady:n}),h=e=>{let t=m.subscribe(e);return c(),t}};u&&g(),u_(()=>{f&&(s.identityDeps=[...l],s.queryHash=d,s.observer=m,s.subscribe=h,f()),y?.()}),n&&!a&&(s.collection?.status===`idle`||s.collection?.status===`cleaned-up`)&&m.preload().catch(()=>{});let _=p&&t?.forkReady(m,p);_&&(s.collection=_,g()),f||(s.observer=m,s.subscribe=h);let v=(0,K.useSyncExternalStore)(h,()=>{let e=m.getSnapshot();return t?t.read(e):e},()=>{let e=m.getServerSnapshot(n);return t?t.read(e):e}),y=v.isReady?t?.claim():void 0;return n?{result:v,client:a,queryHash:d,observer:m,deferredCollections:s.deferredCollections}:v}catch(e){return jg(s.deferredCollections,e)}}var v_=({key:e,field:t})=>`${e}\u0000${t}`;function y_({conflict:{field:e,current:t}}){if(t===null)return(0,Q.jsx)(Q.Fragment,{children:`Someone else deleted this record.`});if(t===void 0)return(0,Q.jsx)(Q.Fragment,{children:`Someone else changed this record.`});let n=_n(t.record[e]);return(0,Q.jsxs)(Q.Fragment,{children:[t.updatedBy,` set `,n===``?`nothing`:(0,Q.jsx)(`strong`,{className:`font-medium`,children:n}),` `,(0,Q.jsx)(je,{at:Date.parse(t.updatedAt)}),`.`]})}function b_({conflicts:e,columns:t,onKeep:n,onUseMine:r}){return(0,Q.jsx)(Vt,{className:`bg-tone-waiting hover:bg-tone-waiting`,children:(0,Q.jsx)(Ht,{colSpan:t,className:`sticky left-0 whitespace-normal text-tone-waiting-foreground`,children:(0,Q.jsx)(`ul`,{className:`flex flex-col gap-2`,children:e.map(e=>(0,Q.jsxs)(`li`,{role:`alert`,className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Q.jsx)(Kt,{"aria-hidden":`true`,className:`size-4 shrink-0`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`code`,{children:e.field}),` changed since you read it: `,(0,Q.jsx)(y_,{conflict:e})]}),(0,Q.jsxs)(`span`,{className:`flex gap-2`,children:[(0,Q.jsx)(dt,{size:`sm`,variant:`outline`,onClick:()=>n(e),children:`Keep theirs`}),e.current!==null&&(0,Q.jsx)(dt,{size:`sm`,onClick:()=>r(e),children:`Use mine`})]})]},e.field))})})})}var x_=`Save or discard the staged changes first`;function S_(e,t){return(e?.tx.mutations??[]).flatMap(e=>{let n=e.type===`insert`?{}:e.original.record,r=e.modified.record,i=e.type===`delete`?[]:[...new Set([...Object.keys(n),...Object.keys(r)])].filter(e=>!Bs(n[e],r[e])).map(e=>({field:e,before:n[e],after:r[e]}));return e.type===`update`&&i.length===0?[]:[{key:e.key,name:_n(e.type===`insert`?r[t]:e.key),type:e.type,fields:i}]})}function C_(e,t,n,r){if(!e)return[];let i=new Set(e.tx.mutations.flatMap(e=>e.type===`delete`?[]:[e.key])),a=new Map;for(let t of e.steps)for(let e of t.cells??[])a.set(`${e.key}\u0000${e.field}`,e);let o=[...a.values()].flatMap(({key:e,field:t,error:n})=>n&&i.has(e)?[{key:e,field:t,error:n}]:[]),s=new Set(o.map(v_)),c=e.tx.mutations.filter(e=>e.type===`insert`),l=Map.groupBy(c,e=>_n(e.modified.record[t])),u=(e,t,n)=>{s.has(v_({key:e,field:t}))||o.push({key:e,field:t,error:n})};for(let e of c){let n=_n(e.modified.record[t]);n===``?u(e.key,t,`Needs a key`):(r(n)||l.get(n).length>1)&&u(e.key,t,`A record has this key already`)}for(let e of c)for(let r of n)r!==t&&e.modified.record[r]===void 0&&u(e.key,r,`Needs a value`);return o}var w_=e=>{let t=[...new Set(e.steps.map(e=>e.what))];return t.length>1?`${t.slice(0,-1).join(`, `)} and ${t.at(-1)}`:t[0]};function T_(e){let t=e.filter(e=>e.type===`update`),n=t.reduce((e,t)=>e+t.fields.length,0),r=e.filter(e=>e.type===`insert`).length,i=e.filter(e=>e.type===`delete`).length;return{changes:n+r+i,records:e.length,cells:n,updated:t.length,added:r,deleted:i}}function E_({staged:e,counts:t,issues:n,conflicts:r,saving:i,onReview:a,onDiscard:o,onSave:s}){let c=[t.cells>0&&`${G(t.cells,`cell`)} changed in ${G(t.updated,`record`)}`,t.added>0&&G(t.added,`new record`),t.deleted>0&&`${G(t.deleted,`record`)} deleted`].filter(Boolean),l=[r>0&&`${G(r,`conflict`)} to settle first`,n>0&&`${G(n,`cell`)} to fix first`].filter(Boolean),u=l.length>0,d=(0,Q.jsx)(dt,{size:`sm`,disabled:i||u||t.records===0,onClick:s,children:i?`Saving…`:`Save as one change`});return(0,Q.jsxs)(`div`,{role:`region`,"aria-label":`Staged changes`,className:`flex flex-wrap items-center gap-x-3 gap-y-2 border-t bg-tone-waiting px-3 py-2 text-sm`,children:[(0,Q.jsxs)(`span`,{className:`font-medium`,children:[G(t.changes,`change`),` in `,G(t.records,`record`)]}),(0,Q.jsxs)(`span`,{className:`text-muted-foreground`,children:[`from your `,w_(e),c.length>0&&`: ${c.join(`, `)}`,l.map(e=>` · ${e}`)]}),(0,Q.jsxs)(`span`,{className:`ml-auto flex gap-2`,children:[(0,Q.jsx)(dt,{size:`sm`,variant:`ghost`,onClick:a,children:`Review`}),(0,Q.jsx)(dt,{size:`sm`,variant:`ghost`,disabled:i,onClick:o,children:`Discard`}),u?(0,Q.jsx)(Ae,{tip:`Settle the conflicts and fix the cells first, or Review to save the rest`,children:d}):d]})]})}function D_({count:e,runId:t,onClose:n}){return(0,Q.jsxs)(`div`,{role:`status`,className:`flex flex-wrap items-center gap-x-3 gap-y-1 border-t bg-tone-waiting px-3 py-2 text-sm text-tone-waiting-foreground`,children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`size-2.5 shrink-0 rounded-full border-2 border-tone-waiting-foreground`}),(0,Q.jsxs)(`span`,{children:[`Your change of `,G(e,`record`),` waits for approval`]}),t&&(0,Q.jsx)(A,{...pe({workflow:`call`,runId:t}),className:`underline underline-offset-4`,children:`Open the run`}),(0,Q.jsx)(Pe,{tip:`Close`,size:`icon-sm`,className:`ml-auto`,onClick:n,children:(0,Q.jsx)(nn,{"aria-hidden":`true`})})]})}var O_=20;function k_({changes:e,issues:t,blocked:n,saving:r,onSave:i,onClose:a}){let o=e.filter(e=>!n.has(e.key)).length;return(0,Q.jsxs)(Oe,{role:`region`,"aria-label":`Review the change`,className:mt(xe,`z-20 gap-3 overflow-auto py-4`),children:[(0,Q.jsxs)(Fe,{className:`flex items-center gap-2 px-4`,children:[(0,Q.jsxs)(Me,{children:[`Review: `,G(e.length,`record`)]}),(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`saved as one run, recorded as you`}),(0,Q.jsx)(Pe,{tip:`Close`,size:`icon-sm`,className:`ml-auto`,onClick:a,children:(0,Q.jsx)(nn,{"aria-hidden":`true`})})]}),(0,Q.jsxs)(De,{className:`flex flex-col gap-3 px-4 text-sm`,children:[t.length>0&&(0,Q.jsx)(`ul`,{"aria-label":`To fix first`,className:`flex flex-col gap-1 rounded-md bg-tone-bad p-2 text-tone-bad-foreground`,children:t.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`font-medium`,children:e.name||`New record`}),` · `,(0,Q.jsx)(`code`,{children:e.field}),`:`,` `,e.error]},`${e.key}\u0000${e.field}`))}),(0,Q.jsx)(`dl`,{className:`grid grid-cols-[minmax(0,10rem)_minmax(0,1fr)] gap-x-3 gap-y-1.5`,children:e.slice(0,O_).map(e=>(0,Q.jsxs)(`div`,{className:`contents`,children:[(0,Q.jsx)(`dt`,{className:`truncate text-muted-foreground`,children:e.name||`New record`}),(0,Q.jsx)(`dd`,{className:`flex flex-col gap-1`,children:e.type===`delete`?(0,Q.jsx)(`span`,{children:(0,Q.jsx)(W,{tone:Ee.removed,children:`deleted`})}):e.type===`insert`?(0,Q.jsx)(`span`,{children:(0,Q.jsx)(W,{tone:Ee.added,children:`new record`})}):e.fields.map(({field:e,before:t,after:n})=>(0,Q.jsxs)(`span`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,Q.jsx)(`code`,{className:`text-xs text-muted-foreground`,children:e}),(0,Q.jsx)(`span`,{className:`text-muted-foreground line-through`,children:_n(t)||`none`}),(0,Q.jsx)(`span`,{"aria-hidden":!0,children:`→`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`to`}),(0,Q.jsx)(W,{tone:Ee.changed,children:_n(n)||`none`})]},e))})]},e.key))}),e.length>O_&&(0,Q.jsxs)(`p`,{className:`text-muted-foreground`,children:[`and `,G(e.length-O_,`more record`)]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 border-t pt-3`,children:[(0,Q.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[G(o,`record`),n.size>0&&` · ${n.size} wait for what to settle or fix first`]}),(0,Q.jsx)(dt,{size:`sm`,className:`ml-auto`,disabled:r||o===0,onClick:i,children:r?`Saving…`:`Save ${o} now`})]})]})]})}function A_({staged:e,changes:t}){let n=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,children:`·`}),(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[`Not saved: `,G(t,`change`),` `,(0,Q.jsx)(ke,{tone:`waiting`,className:`size-1.5`})]}),(0,Q.jsx)(`span`,{"aria-hidden":!0,children:`·`}),(0,Q.jsxs)(`span`,{children:[e.steps.at(-1)?.said,` · `,(0,Q.jsxs)(`kbd`,{className:`font-mono`,children:[n?`Cmd`:`Ctrl`,` Z`]}),` undoes it`]})]})}function j_({view:{collection:e,stage:t},keyField:n,required:r,listed:a,reading:o,onSaved:s}){let c=(0,K.useSyncExternalStore)(t.subscribe,t.current,t.current),l=c?.saving===!0,u=(0,K.useMemo)(()=>S_(c,n),[c,n]),d=(0,K.useMemo)(()=>T_(u),[u]),f=(0,K.useMemo)(()=>new Map(u.map(e=>[e.key,e])),[u]),m=(0,K.useMemo)(()=>new Set(u.flatMap(({key:e,fields:t})=>t.map(({field:t})=>v_({key:e,field:t})))),[u]),h=(0,K.useMemo)(()=>C_(c,n,r,t=>e.has(t)),[c,n,r,e,a]),g=(0,K.useMemo)(()=>new Map(h.map(e=>[v_(e),e])),[h]),[_,v]=(0,K.useState)(new Map),y=[..._.values()].filter(e=>f.has(e.key));y.length!==_.size&&v(new Map(y.map(e=>[v_(e),e])));let b=new Set([...h,...y].map(e=>e.key)),[x,S]=(0,K.useState)(!1);x&&!c&&S(!1);let[C,w]=(0,K.useState)(),[T,E]=(0,K.useState)(new Set),D=()=>l&&(i.info(`Saving the change: try again once it is saved`),!0);return{staged:c,saving:l,changes:u,counts:d,changeOfKey:f,changedCells:m,issues:h,issueAt:g,conflicts:y,blocked:b,reviewing:x,setReviewing:S,held:C,closeHeld:()=>w(void 0),denied:T,add(e){if(o)return i.info(`Reading the records: try again once they show`),!1;try{if(D()||!t.add(e))return!1}catch(e){return i.error(p(e)),!1}return w(void 0),E(new Set),!0},async save(e){if(!D())try{let r=await t.save(e);if(`conflicts`in r){let e=new Map(S_(t.current(),n).map(e=>[e.key,e]));v(t=>{let i=new Map(t);for(let{key:t,current:a}of r.conflicts){let r=e.get(t),o=r?.fields.length?r.fields:[{field:n,after:void 0}];for(let{field:e,after:n}of o){let r={key:t,field:e,mine:n,current:a,staged:!0};i.set(v_(r),r)}}return i}),r.conflicts.length?i.warning(`${G(r.conflicts.length,`record`)} changed since you staged them`,{description:`Nothing was saved: settle each one, then save again.`}):i.warning(`A record has a new record's key already`,{description:`Nothing was saved: change its key, then save again.`})}else`denied`in r?(E(new Set(r.denied)),i.error(r.denied.length?`Could not save ${r.denied.join(`, `)}`:`Could not save the change`,{description:p(r.error)})):`held`in r?(S(!1),w(r)):(S(!1),s(),i.success(`Saved ${G(r.saved,`record`)}`))}catch(e){i.error(`Could not save: nothing saved, the change still staged`,{description:p(e)})}},settle(e,n){D()||(v(t=>{let n=new Map(t);return n.delete(v_(e)),n}),n===`theirs`&&t.drop(e.key,f.get(e.key)?.type===`delete`?void 0:e.field),y.some(t=>t.key===e.key&&v_(t)!==v_(e))||t.rebase(e.key,e.current??null))}}}var M_=`/data/$name/`,N_=250;function P_({collection:e,search:t,staged:n}){let r=L({from:M_}),i=e=>void r({search:t=>({...t,...e}),replace:!0,resetScroll:!1}),[a,s]=(0,K.useState)(t.key??``),c=(0,K.useRef)(t.key);(0,K.useEffect)(()=>{t.key!==c.current&&(c.current=t.key,s(t.key??``))},[t.key]),(0,K.useEffect)(()=>{if((a||void 0)===c.current)return;let e=setTimeout(()=>{c.current=a||void 0,i({key:c.current})},N_);return()=>clearTimeout(e)},[a]);let l=t.limit??te.default,u=(0,Q.jsxs)(`fieldset`,{disabled:n,className:`flex flex-wrap items-end gap-3`,children:[(0,Q.jsxs)(en,{className:`w-56`,children:[(0,Q.jsxs)($t,{htmlFor:`grid-key`,children:[e.key,` starts with`]}),(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(vn,{"aria-hidden":`true`,className:`pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground`}),(0,Q.jsx)(Wt,{id:`grid-key`,type:`search`,autoComplete:`off`,className:`pl-8`,value:a,onChange:e=>s(e.target.value)})]})]}),o(e.fields).map(({name:e,values:n})=>(0,Q.jsxs)(en,{className:`w-auto`,children:[(0,Q.jsx)($t,{htmlFor:`grid-where-${e}`,children:e}),(0,Q.jsxs)(tn,{id:`grid-where-${e}`,value:t.where?.[e]??``,onChange:n=>{let{[e]:r,...a}=t.where??{},o=n.target.value?{...a,[e]:n.target.value}:a;i({where:Object.keys(o).length?o:void 0})},children:[(0,Q.jsx)(Jt,{value:``,children:`Any`}),n.map(e=>(0,Q.jsx)(Jt,{value:e,children:e},e))]})]},e)),(0,Q.jsxs)(en,{className:`w-auto`,children:[(0,Q.jsx)($t,{htmlFor:`grid-limit`,children:`Show at most`}),(0,Q.jsx)(tn,{id:`grid-limit`,value:String(l),onChange:e=>i({limit:Number(e.target.value)}),children:[...new Set([...R,l])].toSorted((e,t)=>e-t).map(e=>(0,Q.jsx)(Jt,{value:String(e),children:e},e))})]}),(0,Q.jsx)(F_,{collection:e,hide:t.hide,set:i})]});return n?(0,Q.jsx)(Ae,{tip:x_,children:u}):u}function F_({collection:e,hide:t=[],set:n}){let r=fe(e.fields).filter(t=>t!==e.key),i=e.declared!==void 0;if(r.length===0&&!i)return null;let a=r.filter(e=>t.includes(e)),o=(e,t)=>{let r=t?a.filter(t=>t!==e):[...a,e];n({hide:r.length?r:void 0})};return(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsxs)(wt,{children:[(0,Q.jsxs)(yt,{render:(0,Q.jsx)(dt,{variant:`outline`}),children:[(0,Q.jsx)(Rn,{"aria-hidden":`true`,"data-icon":`inline-start`}),`Fields`]}),(0,Q.jsxs)(gt,{className:`min-w-44`,children:[r.map(e=>(0,Q.jsx)(bt,{checked:!a.includes(e),onCheckedChange:t=>o(e,t),children:e},e)),i&&r.length>0&&(0,Q.jsx)(vt,{}),i&&(0,Q.jsx)(Tt,{onClick:()=>n({column:{change:`add`},record:void 0,new:void 0}),children:`New column`})]})]}),a.length>0&&(0,Q.jsxs)(dt,{variant:`secondary`,size:`sm`,onClick:()=>n({hide:void 0}),children:[G(a.length,`field`),` hidden`,(0,Q.jsx)(nn,{"aria-hidden":`true`,"data-icon":`inline-end`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`: show them all`})]})]})}function I_({field:e,order:t,staged:n,children:r,...i}){let a=t===e?`ascending`:t===`-${e}`?`descending`:void 0,o=a===void 0?e:a===`ascending`?`-${e}`:void 0,s=(0,Q.jsxs)(A,{from:M_,search:e=>({...e,order:o}),disabled:n,replace:!0,resetScroll:!1,preload:!1,className:`inline-flex items-center gap-1 underline-offset-4 hover:underline aria-disabled:no-underline`,children:[e,(0,Q.jsx)(a===`ascending`?xt:a===`descending`?Et:In,{"aria-hidden":!0,className:a?`size-3.5`:`size-3.5 text-muted-foreground`})]});return(0,Q.jsxs)(zt,{"aria-sort":a,...i,children:[n?(0,Q.jsx)(Ae,{tip:x_,children:s}):s,r]})}function L_({value:e}){return e==null?(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`-`}):typeof e==`boolean`?e?`yes`:`no`:typeof e==`object`?(0,Q.jsx)(`code`,{className:`text-xs`,children:JSON.stringify(e)}):String(e)}function R_({issues:e}){let t=e.map(Sn).join(`; `);return(0,Q.jsx)(Ae,{tip:`Saved before its fields changed: ${t}`,children:(0,Q.jsx)(W,{tone:`bad`,tabIndex:0,children:`needs fixing`})})}var z_=class extends Wa{constructor(e){super(e),this.name=`QueryCollectionError`}},B_=class extends z_{constructor(){super(`[QueryCollection] queryKey must be provided.`),this.name=`QueryKeyRequiredError`}},V_=class extends z_{constructor(){super(`[QueryCollection] queryFn must be provided.`),this.name=`QueryFnRequiredError`}},H_=class extends z_{constructor(){super(`[QueryCollection] queryClient must be provided.`),this.name=`QueryClientRequiredError`}},U_=class extends z_{constructor(){super(`[QueryCollection] getKey must be provided.`),this.name=`GetKeyRequiredError`}},W_=class extends z_{constructor(){super(`[QueryCollection] initialData and initialDataUpdatedAt are only supported when syncMode is 'eager'. Seed or hydrate the exact Query cache key for on-demand subsets instead.`),this.name=`InitialDataInOnDemandModeError`}},G_=class extends z_{constructor(e){super(e),this.name=`InvalidQueryResultError`}},K_=class extends z_{constructor(){super(`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`),this.name=`SyncNotInitializedError`}},q_=class extends z_{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name=`DuplicateKeyInBatchError`}},J_=class extends z_{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name=`UpdateOperationItemNotFoundError`}},Y_=class extends z_{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name=`DeleteOperationItemNotFoundError`}},X_=new WeakMap,Z_=new WeakSet;function Q_(e,t){let n=Array.isArray(e)?e:[e],r=[];for(let e of n)if(e.type===`delete`){let t=Array.isArray(e.key)?e.key:[e.key];for(let e of t)r.push({type:`delete`,key:e})}else{let n=Array.isArray(e.data)?e.data:[e.data];for(let i of n){let n;if(e.type===`update`)n=t.getKey(i);else{let r=t.collection.validateData(i,e.type===`upsert`?`insert`:e.type);n=t.getKey(r)}r.push({type:e.type,key:n,data:i})}}return r}function $_(e,t){let n=new Set;for(let r of e){if(n.has(r.key))throw new q_(r.key);if(n.add(r.key),r.type===`insert`){if(t.collection._state.getAcceptedSyncedRow(r.key))throw new fo(r.key,t.collection.id)}else if(r.type===`update`){if(!t.collection._state.getAcceptedSyncedRow(r.key))throw new J_(r.key)}else if(r.type===`delete`&&!t.collection._state.getAcceptedSyncedRow(r.key))throw new Y_(r.key)}}function ev(e,t,n){let r;try{r=Q_(e,t)}catch(e){return Promise.reject(e)}let i=t.reserveDirectWrite?.()??0,a=t.earlierCommits?.();if(!a)try{return tv(r,t,i)}catch(e){return Promise.reject(e)}let o=a.then(()=>{if(!n())throw new xs;return tv(r,t,i)});return t.noteWaitingDirectWrite?.(o.then(()=>void 0,()=>void 0)),o}function tv(e,t,n){$_(e,t),t.claimDirectWriteKeys?.(e.map(e=>e.key),n),t.begin();for(let n of e)switch(n.type){case`insert`:{let e=t.collection.validateData(n.data,`insert`);t.write({type:`insert`,value:e});break}case`update`:{let e={...t.collection._state.getAcceptedSyncedRow(n.key),...n.data},r=t.collection.validateData(e,`update`,n.key);t.write({type:`update`,value:r});break}case`delete`:{let e=t.collection._state.getAcceptedSyncedRow(n.key);t.write({type:`delete`,value:e});break}case`upsert`:{let e=t.collection._state.getAcceptedSyncedRow(n.key)!==void 0,r=t.collection.validateData(n.data,e?`update`:`insert`,n.key);e?t.write({type:`update`,value:r}):t.write({type:`insert`,value:r});break}}let r=md(t.commit()),i=()=>{let r=e=>e?e.map(e=>t.collection._state.getAcceptedSyncedRow(e)).filter(e=>e!==void 0):Array.from(t.collection._state.acceptedSyncedEntries(),([,e])=>e);t.updateCacheData?t.updateCacheData(r,e.map(e=>e.key),n):t.queryClient.setQueryData(t.queryKey,r())};r===!0&&i();let a=Promise.resolve(r).then(()=>{r!==!0&&i()});return a.catch(()=>void 0),a}function nv(e){function t(){let t=e();if(!t)throw new K_;return t}function n(n){let r=t(),i=X_.get(r);if(i)return i.operations.push(n),i.completion;let a=ev(n,r,()=>e()===r);return Z_.add(a),a}return{writeInsert(e){return n({type:`insert`,data:e})},writeUpdate(e){return n({type:`update`,data:e})},writeDelete(e){return n({type:`delete`,key:e})},writeUpsert(e){return n({type:`upsert`,data:e})},writeBatch(n){let r=t();if(X_.get(r))throw Error(`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`);let i,a,o=new Promise((e,t)=>{i=e,a=t});Z_.add(o),o.catch(()=>void 0);let s={operations:[],completion:o};X_.set(r,s);try{let t=n();if(typeof t==`object`&&t&&`then`in t&&typeof t.then==`function`&&!Z_.has(t))throw Promise.resolve(t).catch(()=>void 0),Error(`writeBatch does not support async callbacks. The callback must be synchronous.`);return X_.delete(r),i(s.operations.length>0?ev(s.operations,r,()=>e()===r):Promise.resolve()),o}catch(e){throw a(e),e}finally{X_.get(r)===s&&X_.delete(r)}}}}function rv(e,t){let n;try{n=e?.()}catch(e){try{t()}catch(t){throw av(e,t)}throw e}try{t()}catch(e){if(!iv(n))throw e;return Promise.resolve(n).then(()=>{throw e},t=>{throw av(t,e)})}return iv(n)?Promise.resolve(n):void 0}function iv(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function av(e,t){return AggregateError([e,t],`Adapter cleanup and local teardown both failed`,{cause:e})}function ov(e){return typeof e==`object`&&!!e}var sv=[`enabled`,`refetchInterval`,`retry`,`retryDelay`,`staleTime`,`gcTime`,`refetchOnWindowFocus`,`refetchOnReconnect`,`refetchOnMount`,`networkMode`];function cv(e){let t={};for(let n of sv)e[n]!==void 0&&(t[n]=e[n]);return t}var lv=`queryCollection:gc:`,uv=0,dv=new WeakMap,fv=new WeakMap,pv=new WeakMap,mv=new WeakMap,hv=new WeakMap,gv=new WeakMap,_v=new WeakMap,vv=class{constructor(e,t,n){this.state=e,this.refetch=t,this.writeInsert=n.writeInsert,this.writeUpdate=n.writeUpdate,this.writeDelete=n.writeDelete,this.writeUpsert=n.writeUpsert,this.writeBatch=n.writeBatch}get isFetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isFetching)}get isRefetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isRefetching)}get isLoading(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isLoading)}get dataUpdatedAt(){return Math.max(0,...Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().dataUpdatedAt))}get fetchStatus(){let e=`idle`;for(let t of this.state.observers.values()){let n=t.getCurrentResult().fetchStatus;if(n===`fetching`)return`fetching`;n===`paused`&&(e=`paused`)}return e}};function yv(e){let{queryKey:t,queryFn:n,select:r,queryClient:i,enabled:a,refetchInterval:o,retry:s,retryDelay:c,staleTime:l,gcTime:u,refetchOnWindowFocus:d,refetchOnReconnect:f,refetchOnMount:p,networkMode:m,initialData:h,initialDataUpdatedAt:g,persistedGcTime:_,getKey:v,onInsert:y,onUpdate:b,onDelete:x,meta:S,...C}=e,w=C.syncMode??`eager`;if(w===`on-demand`&&(h!==void 0||g!==void 0))throw new W_;let T=w===`eager`?{...h!==void 0&&{initialData:h},...g!==void 0&&{initialDataUpdatedAt:g},placeholderData:void 0}:{initialData:()=>void 0,initialDataUpdatedAt:void 0,placeholderData:void 0},E=typeof t==`function`?t({}):t,D=w===`on-demand`&&typeof t!=`function`?E:void 0,te=D&&M(D),O=e=>{typeof t==`function`&&(e.length>=E.length&&E.every((t,n)=>Bs(t,e[n]))||console.warn(`[QueryCollection] queryKey function must return keys that extend the base key prefix. Base: ${JSON.stringify(E)}, Got: ${JSON.stringify(e)}. This can cause stale cache issues.`))};if(!t)throw new B_;if(!n)throw new V_;if(!i)throw new H_;if(!v)throw new U_;let k={observers:new Map},A=0,j=new WeakMap,ne=new WeakMap,N=new WeakSet,re={},ie,ae=new WeakMap,F,I=0,L=!1,oe=(e,t)=>{if(ie.add(e),t!==void 0){let n=ae.get(e)??new Set;n.add(t),ae.set(e,n)}},se=(e,t)=>{N.add(e),oe(e,t);let n=gv.get(e)??new Set;n.add(re),gv.set(e,n)},ce=e=>ae.get(e)??new Set([M(e.queryKey)]),R=(e,t,n)=>{let r=ne.get(e)??new Map;ne.set(e,r);let i=r.get(t)??new Map;r.set(t,i);let a=i.get(n)??{};return i.set(n,a),a},ue=(e,t)=>j.get(t)?.get(e),de=(e,t,n)=>{let r=j.get(t)??new Map;r.set(e,n),j.set(t,r)},fe=(e,t)=>{for(let n of ce(e)){let r=k.observers.get(n);if(!r||r.getCurrentQuery()!==e)continue;let i=r.getCurrentResult(),a=R(e,t,n);a.result=i;let o=ue(n,i);o&&(a.settlement=o)}},pe=(e,t)=>{let n=ne.get(e)?.get(t);if(n)for(let[e,t]of n){if(!t.result)continue;let n=ue(e,t.result);n&&(t.settlement=n)}},me=(e,t)=>{let n=ne.get(e);if(n){for(let e of t)n.delete(e);n.size===0&&ne.delete(e)}},he=e=>F===void 0||(pv.get(e)??0)>F,z=new Map,B=new Map,V=new WeakSet,ge=e=>{let t=B.get(e);return t!==void 0&&!V.has(t)},H=new Map,_e=new Map,ve=new Map,ye=0,be=new Map,xe=new Map,Se=0,Ce=new WeakSet,we=new WeakMap,Te=new Map,Ee=(e,t)=>{let n=fv.get(e)??Te.get(t);e.state.fetchStatus===`fetching`&&(n??ye)<ye&&e.cancel({silent:!0})},U=new Map,De=new Map,Oe,ke=!1,Ae=new WeakMap,je=0,W=new Map,Me=new Map,Ne=()=>{},Pe=(e,t)=>!1,Fe=e=>void 0,Ie,Le=(e,t)=>{let n=H.get(e)||new Set;n.add(t),H.set(e,n);let r=B.get(t)||new Set;r.add(e),B.set(t,r)},Re=(e,t)=>{t.size===0?H.delete(e):(H.set(e,new Set(t)),t.forEach(t=>{let n=B.get(t)||new Set;n.add(e),B.set(t,n)}))},ze=(e,t)=>{let n=H.get(e);return n?.delete(t),n?.size||H.delete(e),B.get(t)?.delete(e),!n?.size},Be=e=>{let t=new Map;B.get(e)?.forEach(n=>{let r=new Set(H.get(n));r.delete(e),t.set(n,r),r.size===0?H.delete(n):H.set(n,r)});let n=new Set;return V.add(n),B.set(e,n),t},Ve=e=>{let h={};Ie=h,U.clear(),F=void 0,L=!1,ie=new Set(i.getQueryCache().findAll({queryKey:E}));for(let e of ie)e.state.fetchStatus===`fetching`&&Te.set(M(e.queryKey),fv.get(e)??Te.get(M(e.queryKey))??ye);let{begin:g,write:y,commit:b,markReady:x,fail:C,reportError:A,reportHealthy:j,invalidateLoadedSubsets:ae,collection:R,metadata:V}=e,Ve=!1,He=!1,We=()=>{Ve||He||(Ve=!0,x())},Ge=e=>!Ve&&(He=!0,C(e),!0),qe=new WeakMap,Je=new Map,Ye,Xe=(e,t,n)=>{let r=e.meta?.loadSubsetOptions;if(w!==`on-demand`||!ov(r)||!r.orderBy?.length)return;let i=qe.get(e),{where:a,orderBy:o}=r,s={readKey:i?.readKey??Kp({where:a,orderBy:o}),leadingValue:i?.leadingValue??al(o[0].expression),compare:i?.compare??sc(o[0].compareOptions),keys:JSON.stringify(n.map(e=>JSON.stringify(v(e))).sort()),last:void 0};for(let e of n){let t=s.leadingValue(e);(s.last===void 0||s.compare(t,s.last.value)>0)&&(s.last={value:t})}if(qe.set(e,s),Ye!==void 0||Je.has(t)||i?.last===void 0)return;let c=i.last.value;(s.last===void 0||s.compare(s.last.value,c)<0||i.keys!==s.keys&&[...k.observers.values()].some(e=>{let t=qe.get(e.getCurrentQuery());return t!==void 0&&t!==s&&t.readKey===s.readKey&&(t.last===void 0||s.compare(t.last.value,c)>0)}))&&(Ye=setTimeout(()=>{Ye=void 0,Ie===h&&ae()},0))},Ze=V===void 0?null:t_(V.persistence);if(Ze?.startupCacheGenerationRotated===!0){F=uv;for(let e of ie)e.state.fetchStatus!==`idle`&&fv.get(e)===void 0&&fv.set(e,F)}let Qe=!1,$e=!1,et=new Map,tt=new Set,nt=new WeakMap,rt=new Map,it=e=>rt.get(e)??0,at=e=>{rt.set(e,it(e)+1)},ot=new Map,st=new Map,ct=e=>{for(let t of st.values())if(t===e)return;j(e)},lt=(e,t)=>{let n=st.get(e);st.set(e,t),Ve&&(A(t),n!==void 0&&ct(n))},ut=e=>{let t=st.get(e);st.delete(e)&&Ve&&(st.size===0?j():ct(t))},dt=new WeakMap,ft=new Set,pt=new Map,G=e=>dt.get(e),mt=(e,t)=>{dt.set(e,t)};Fe=G;let ht=new Map,gt=new Map,_t=new Map,vt=Promise.resolve(),yt=e=>{let t=ht.get(e);t?.rollback?.(),U.delete(e),ot.delete(e),ht.delete(e),t?.abort()},bt=async e=>{for(;;){let t=U.get(e);if(!t)return;try{await t}catch(n){if(U.get(e)===t||ot.has(e)&&ot.get(e)===n)throw n}}},xt=(e,t,n,r=()=>!0)=>new Promise((i,a)=>{let o=!0,s=()=>{},c=ve.get(t)??new Set,l=e=>{o&&(o=!1,s(),c.delete(u),c.size===0&&ve.delete(t),e())},u=()=>{l(()=>a(n()))};c.add(u),ve.set(t,c),s=e.subscribe(e=>{queueMicrotask(()=>{(e.isSuccess&&!R.deferDataRefresh||e.isError&&!e.isFetching)&&r(e)&&l(()=>i(e))})})}),St=(e,t)=>{let n=pt.get(t)??new Map,r=n.get(e);if(r)return r;let i=t.then(async()=>{let t=k.observers.get(e);if(!t)throw new P;let n=await t.refetch();for(;;){if(!n.isSuccess)return n;if(await new Promise(e=>queueMicrotask(e)),R.deferDataRefresh){n=await xt(t,e,()=>new P);continue}let r=G(n);if(r?.type===`rejected`)throw r.error;if(r?.type===`pending`)return r.promise;let i=wt(e);return i!==!0&&await i,n}});n.set(e,i),pt.set(t,n);let a=()=>{n.get(e)===i&&(n.delete(e),n.size===0&&pt.delete(t))};return i.then(a,a),i},Ct=(e,t,n)=>{let r=G(t);if(r?.type===`pending`)return r;let i,a=new Promise((e,t)=>{i=t,n.then(e,t)});a.catch(()=>{});let o={type:`pending`,promise:a,reject:i};return mt(t,o),ft.add(o),a.then(()=>{ft.delete(o)},()=>{ft.delete(o)}),o},wt=e=>U.get(e)?bt(e):!ot.has(e)||Promise.reject(ot.get(e)),Tt=e=>V?.row.get(e),Et=(e,t)=>{if(!e||typeof e!=`object`)return new Set;let n=e.queryCollection;if(!n||typeof n!=`object`)return new Set;let r=n.owners;if(!r||typeof r!=`object`)return new Set;let i=new Set(Object.keys(r));return t===void 0||i.forEach(e=>{let n=B.get(e);n&&!n.has(t)&&i.delete(e)}),i},Dt=e=>Et(Tt(e),e),Ot=(e,t)=>{if(!V)return;let n={...Tt(e)??{}};t.size===0?(delete n.queryCollection,Object.keys(n).length===0?V.row.delete(e):V.row.set(e,n)):V.row.set(e,{...n,queryCollection:{owners:Object.fromEntries(Array.from(t.values()).map(e=>[e,!0]))}})},kt=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.queryHash===t){if(n.mode===`until-revalidated`)return{queryHash:t,mode:`until-revalidated`};if(n.mode===`ttl`&&typeof n.expiresAt==`number`&&Number.isFinite(n.expiresAt))return{queryHash:t,mode:`ttl`,expiresAt:n.expiresAt}}},At=e=>(vt=vt.then(e,e),vt),jt=e=>{let t=_t.get(e);t&&(clearTimeout(t),_t.delete(e))},Mt=e=>{let t=B.get(e);if(t)return new Set(t);let n=new Set,r=Array.from(R._state.syncedData.keys(),e=>[e,Dt(e)]);for(let[t,i]of r)i.size!==0&&(Re(t,i),i.has(e)&&n.add(t));return n},Nt=async(e,t=!1)=>{let n=I,r=B.get(e);if(r&&(r.size>0||t)&&Array.from(r).every(e=>R.has(e))){let e=new Map;return r.forEach(t=>{let n=R.get(t),r=H.get(t);n&&r&&e.set(t,{value:n,owners:new Set(r)})}),e}let i=Ze?.scanPersistedRows;if(!i){let t=new Map;return Mt(e).forEach(e=>{let n=R.get(e),r=H.get(e);n&&r&&t.set(e,{value:n,owners:new Set(r)})}),t}let a=new Map,o=await i();if(n!==I||L)return a;let s=o.map(e=>Et(e.metadata,e.key));return o.forEach((t,n)=>{let r=s[n];r.size!==0&&(Re(t.key,r),r.has(e)&&a.set(t.key,{value:t.value,owners:r}))}),a},Pt=async e=>{if(!V)return;let t=I,n=await Nt(e);if(t!==I||L)return;let r=[];g(),n.forEach(({value:t,owners:n},i)=>{n.delete(e),Ot(i,n),ze(i,e)&&r.push(t)}),r.forEach(e=>{y({type:`delete`,value:e})}),V.collection.delete(`${lv}${e}`),b(),B.delete(e)},Ft=e=>{if(e.mode!==`ttl`)return;jt(e.queryHash);let t=Math.max(0,e.expiresAt-Date.now()),n=setTimeout(()=>{_t.delete(e.queryHash),At(async()=>{let t=V?.collection.get(`${lv}${e.queryHash}`),n=kt(t,e.queryHash);if(n?.mode===`ttl`){if(n.expiresAt>Date.now())return Ft(n);await Pt(e.queryHash)}})},t);_t.set(e.queryHash,n)},It=async()=>{if(!V)return;let e=V.collection.list(lv),t=Date.now();for(let{key:n,value:r}of e){let e=n.slice(lv.length),i=kt(r,e);i&&(i.mode===`ttl`&&i.expiresAt<=t?await Pt(i.queryHash):i.mode===`ttl`&&Ft(i))}},Lt=e=>{if(typeof t==`function`){let{refetch:n,...r}=e;return t(r)}if(w===`on-demand`){let n=Kp(e);return n===void 0?t:[...t,n]}return t},Rt=V?.collection.list(lv),zt=!Rt||Rt.length===0?($e=!0,Promise.resolve()):At(async()=>{try{await It()}finally{$e=!0}}),Bt=(e,t,n)=>xt(e,t,()=>new Cs,n).then(e=>{if(e.isError)throw e.error}),Vt=(e,t,n)=>Bt(e,t,n).then(()=>{let e=wt(t);return e===!0?void 0:e}),Ht=async(e,t)=>new Promise((n,r)=>{let i=!0,a=ve.get(t)??new Set,o=e=>{if(!i)return;i=!1;let n=Je.get(t)-1;n===0?Je.delete(t):Je.set(t,n),a.delete(s),a.size===0&&ve.delete(t),e()},s=()=>{o(()=>r(new Cs))};a.add(s),ve.set(t,a),Je.set(t,(Je.get(t)??0)+1),(async()=>{let n=!!R.deferDataRefresh;for(Ee(e.getCurrentQuery(),t);;){if(!i)return;try{await e.refetch({throwOnError:!0})}catch(t){let n=fv.get(e.getCurrentQuery());if(F===void 0||n===void 0||n>F)throw t;continue}if(await new Promise(e=>queueMicrotask(e)),!i)return;if(he(e.getCurrentQuery()))break}if(n||!he(e.getCurrentQuery())){await Vt(e,t);return}let r=wt(t);r!==!0&&await r})().then(()=>o(n),e=>o(()=>r(e)))}),Ut=(e,t)=>{let n=e.getCurrentQuery();if(typeof a==`function`?a(n):a!==!1)return Ht(e,t);let r=n.state.dataUpdateCount;return Vt(e,t,t=>{if(t.isError)return!0;let n=e.getCurrentQuery();return n.state.dataUpdateCount>r&&hv.get(n)===n.state.dataUpdateCount&&he(n)})},Wt=(e={},t=n)=>{if(!$e){let n={},r=et.get(e)??new Set;return r.add(n),et.set(e,r),zt.then(()=>{if(!et.get(e)?.delete(n))throw new Cs;r.size===0&&et.delete(e);let i=Wt(e,t);return i===!0?void 0:i})}let g=Lt(e),y=M(g),b=te===void 0?void 0:k.observers.get(te),x=Me.has(y);if(x&&b===void 0)throw Error(`A full-source dependent lost its Query observer`);let C=b?.getCurrentQuery(),E=b?.getCurrentResult(),ee=E!==void 0&&ue(te,E)!==void 0,A=V?.collection.get(`${lv}${y}`),j=kt(A,y)!==void 0,ne=!e.refetch&&D!==void 0&&te!==y&&(x||!j&&!k.observers.has(y)&&(W.get(te)??0)>0&&E?.isSuccess===!0&&C?.state.fetchStatus===`idle`&&he(C)&&!U.has(te)&&!ot.has(te)&&ee),N=ne?D:g,P=ne?te:y,{subscription:ie,refetch:ae,...I}=e,L={...S};Object.defineProperty(L,"loadSubsetOptions",{value:I,enumerable:!1,configurable:!0,writable:!0});let oe=P===y?A:V?.collection.get(`${lv}${P}`);if(kt(oe,P)!==void 0&&tt.add(P),jt(P),O(N),k.observers.has(P)){W.set(P,(W.get(P)||0)+1),ne&&Me.set(y,(Me.get(y)??0)+1);let t=k.observers.get(P),n=t.getCurrentResult();if(e.refetch)return Ht(t,P);let r=t.getCurrentQuery(),i=_v.get(r);return Ae.has(r)||w===`on-demand`&&i!==void 0&&(i.owner!==re||i.session!==h)||ye>0&&r.state.dataUpdateCount>(hv.get(r)??0)||!he(t.getCurrentQuery())?Ut(t,P):n.isSuccess?R.deferDataRefresh?Vt(t,P):wt(P):n.isError&&!n.isFetching?Promise.reject(n.error):Vt(t,P)}let ce={...cv({enabled:a,refetchInterval:o,retry:s,retryDelay:c,staleTime:l,gcTime:u,refetchOnWindowFocus:d,refetchOnReconnect:f,refetchOnMount:p,networkMode:m}),...T,queryKey:N,queryFn:e=>{let n=M(e.queryKey),r=i.getQueryCache().find({queryKey:e.queryKey,exact:!0});Te.set(n,Math.max(Te.get(n)??0,ye));let a=()=>{let n=Object.defineProperties({},Object.getOwnPropertyDescriptors(e));return n.meta={...e.meta,loadSubsetOptions:{...I,get signal(){return e.signal}}},t(n)};if((W.get(n)??0)>1||(r?.getObserversCount()??0)>1||P===te&&Me.size||I.signal?.aborted)return a();let o=t=>{let n=typeof t==`object`&&!!t&&`name`in t&&t.name===`AbortError`;if(!I.signal?.aborted||t!==I.signal.reason&&!n||!r||r.getObserversCount()===0||i.getQueryCache().find({queryKey:e.queryKey,exact:!0})!==r||r.state.fetchStatus!==`fetching`)throw t;return a()};try{return Promise.resolve(t(e)).catch(o)}catch(e){return o(e)}},meta:L,structuralSharing:!0,notifyOnChangeProps:`all`},de=new le(i,ce),fe=de.getCurrentQuery();se(fe,P);let pe=i.getQueryCache().find({queryKey:N,exact:!0})?.gcTime,me=_??pe;z.set(P,N),k.observers.set(P,de);let B=fv.get(fe);B!==void 0&&(fe.state.fetchStatus===`fetching`||mv.get(fe)===fe.state.data)&&Te.set(P,B),me===void 0?gt.delete(P):gt.set(P,me),W.set(P,(W.get(P)||0)+1);let ge=i.getQueryData(N);if(ge!==void 0){let t=_v.get(fe),n=w===`on-demand`&&t!==void 0&&(t.owner!==re||t.session!==h),i=ye>0&&fe.state.dataUpdateCount>(hv.get(fe)??0),a=Ze?.scanPersistedRows===void 0?void 0:r?r(ge):ge,o=Ze?.scanPersistedRows!==void 0&&Array.isArray(a)&&a.some(e=>{let t=v(e);return R._state.getAcceptedSyncedRow(t)!==void 0&&!be.has(t)&&!H.has(t)});(Qe||R.subscriberCount>0)&&tn(de,P,n||i||o?{data:fe.state.data,version:fe.state.dataUpdateCount,fetchStart:fv.get(fe)}:void 0);let s=de.getCurrentResult();return e.refetch||Ae.has(fe)||n||i||o?e.refetch?Ht(de,P):Ut(de,P):he(de.getCurrentQuery())?s.isError&&!s.isFetching?Promise.reject(s.error):!s.isSuccess||R.deferDataRefresh?Vt(de,P):wt(P):Ut(de,P)}if(F!==void 0)return(Qe||R.subscriberCount>0)&&tn(de,P),Ut(de,P);let _e=Vt(de,P);return(Qe||R.subscriberCount>0)&&tn(de,P),_e},Gt=(e,t)=>{let n=t.data,i=r?r(n):n,a=r?`select()`:`queryFn`;if(!Array.isArray(i))return{error:new G_(`@tanstack/query-db-collection: ${a} must return an array of objects. Got: ${typeof i} for queryKey ${JSON.stringify(e)}`)};let o=i.findIndex(e=>typeof e!=`object`||!e);if(o!==-1){let t=i[o];return{error:new G_(`@tanstack/query-db-collection: ${a} must return an array of objects. Invalid item at index ${o}: ${t===null?`null`:typeof t} for queryKey ${JSON.stringify(e)}`)}}return{items:i}},Kt=(e,t,n)=>{let r=new Map(e.map(e=>[v(e),e]));for(let[e,i]of De){if(i<=t||w===`on-demand`&&!r.has(e)&&!B.get(n)?.has(e))continue;let a=R._state.getAcceptedSyncedRow(e);a===void 0?r.delete(e):r.set(e,a)}return Array.from(r.values())},qt=async()=>{for(;Oe;)await Oe},Jt=(e,t)=>{let n=Gt(e,t);if(`error`in n)throw mt(t,{type:`rejected`,error:n.error}),n.error;return n.items},Yt=(e,t,n,r,a,o)=>{let s=M(e);if(R.status===`cleaned-up`||a?.aborted)throw new Cs;Ue()&&n.settleRefetchAtFetchBoundary?.();let c=o??Jt(e,t),l=new Map(R._state.acceptedSyncedEntries()),u=r!==void 0,d=u?new Set(r.keys()):Mt(s),f=i.getQueryCache().find({queryKey:e,exact:!0}),p=f!==void 0&&mv.get(f)===f.state.data?pv.get(f):void 0;if(w===`eager`)be.forEach((e,t)=>{l.has(t)&&p!==void 0&&p>e&&d.add(t)});else if(p!==void 0&&(be.size>0||Ze?.scanPersistedRows!==void 0)){let e=k.observers.get(s)?.options.meta?.loadSubsetOptions;if(ov(e)&&e.limit===void 0&&e.offset===void 0&&e.cursor===void 0){let t=e.where?al(e.where):void 0;l.forEach((e,n)=>{let r=be.get(n);if(!(r===void 0?!Ze?.scanPersistedRows||Dt(n).size>0:p<=r)){try{if(t&&!rl(t(e)))return}catch{return}d.add(n)}})}}let m=new Map;c.forEach(e=>{let t=v(e),n=xe.get(t);m.set(t,p!==void 0&&n!==void 0&&n>p&&l.has(t)?l.get(t):e)});let h=new Map,_=new Set,x=B.get(s),S=new Set([...d,...m.keys()]),C=new Map;S.forEach(e=>{let t=H.get(e);C.set(e,t?new Set(t):void 0)});let T=!1,E,D=()=>{E?.applicationStarted||E===void 0&&Array.from(S).every(e=>{let t=H.get(e)??new Set,n=Et(R._state.syncedMetadata.get(e));return t.size===n.size&&Array.from(t).every(e=>n.has(e))})||k.observers.has(s)&&ht.get(s)===n&&(x===void 0?B.delete(s):B.set(s,x),C.forEach((e,t)=>{e===void 0?H.delete(t):H.set(t,e)}))};n.rollback=D;let ee=e=>{if(D(),T){let e=new AbortController;e.abort();try{b(e.signal)}catch{}}throw e};try{B.set(s,new Set(d)),g(),T=!0,V&&V.collection.delete(`${lv}${s}`),d.forEach(e=>{let t=u?r.get(e)?.value:l.get(e),n=m.get(e);if(n)t&&!Bs(t,n)&&y({type:`update`,value:n});else{let t=be.get(e);t!==void 0&&h.set(e,t);let n=Dt(e);n.delete(s),Ot(e,n),ze(e,s)&&(y({type:`delete`,key:e}),_.add(e))}}),m.forEach((e,n)=>{let r=be.get(n);if(!d.has(n)&&r!==void 0&&(p??0)<=r)return;r!==void 0&&p!==void 0&&p>r&&h.set(n,r);let i=Dt(n),a=!i.has(s),o=!l.has(n);a&&i.add(s),Le(n,s),o?y({type:`insert`,value:e}):!d.has(n)&&(t.isFetchedAfterMount||r!==void 0&&p!==void 0&&p>r)&&!Bs(l.get(n),e)&&y({type:`update`,value:e}),(a||o)&&Ot(n,i)}),E=R._state.pendingSyncedTransactions.at(-1),Ue()&&n.settleRefetchAtFetchBoundary?.();let e=b();n.rollback=void 0,T=!1,tt.delete(s),jt(s);let i=()=>{f&&Xe(f,s,c),_.forEach(e=>{R._state.getAcceptedSyncedRow(e)===void 0&&xe.delete(e)});let e=e=>{m.forEach((t,n)=>{R._state.getAcceptedSyncedRow(n)!==void 0&&e>(xe.get(n)??0)&&xe.set(n,e)}),Se=Math.max(Se,e)};if(p!==void 0)e(p);else if(f){let t=f.state.data;queueMicrotask(()=>{if(mv.get(f)===t){let t=pv.get(f);t!==void 0&&e(t)}})}h.forEach((e,t)=>{be.get(t)===e&&be.delete(t)}),a?.aborted||We()},o=md(e);return o===!0?i():o.then(i,()=>void 0),e===!0||e.then(()=>void 0,ee)}catch(e){return ee(e)}},Xt=async(e,t,n,r,a,o)=>{let s=M(e),c=a??Jt(e,t),l=await Nt(s,c.length===0);if(R.status===`cleaned-up`||ht.get(s)!==n)throw new Cs;let u=ye,d=i.getQueryCache().find({queryKey:e,exact:!0}),f=d?fv.get(d):void 0,p=o!==void 0&&o<u?Kt(c,o,s):c;await Yt(e,t,n,l,r,p),o!==void 0&&o<u&&Te.get(s)===o&&d&&fv.get(d)===f&&Te.set(s,u)},Zt=(e,t,n,r)=>{U.set(e,t);let i=()=>U.get(e)===t&&(U.delete(e),!0);t.then(()=>{i()&&(ot.delete(e),!n&&r===it(e)&&ut(e))},t=>{i()&&(ot.set(e,t),at(e),console.error(`[QueryCollection] Error applying query ${String(z.get(e))}:`,t),Ge(t)||lt(e,t))})},Qt=(e,t,n)=>{yt(e);let r=it(e),i=new AbortController,a=()=>{},o=new Promise(e=>{a=e});i.settleRefetchAtFetchBoundary=a,ht.set(e,i);let s;try{s=n(i.signal,i)}catch(e){s=Promise.reject(e)}if(s===!0){ht.get(e)===i&&(de(e,t,Promise.resolve()),ht.delete(e),ot.delete(e),!t.isFetching&&r===it(e)&&ut(e));return}let c=Promise.race([s,o]);c.catch(()=>void 0),de(e,t,c);let l=()=>{ht.get(e)===i&&ht.delete(e)};s.then(l,l),ht.get(e)===i&&Zt(e,s,t.isFetching,r)},$t=e=>{let t=M(e),n=I,r=a=>{if(Ie!==h||L||n!==I)return;let o=k.observers.get(t),s=o?.getCurrentQuery();if(o&&s&&se(s,t),!ke){if(s){let e=fv.get(s);if(a.isError&&F!==void 0&&e!==void 0&&e<=F)return;if(a.isSuccess){if(a.isFetching&&!R.deferDataRefresh&&ge(t)&&mv.get(s)===s.state.data)return;if(!he(s)){queueMicrotask(()=>{let e=k.observers.get(t);e&&e===o&&he(e.getCurrentQuery())&&r(e.getCurrentResult())});return}if((ye>0||Se>(fv.get(s)??Se))&&s.state.dataUpdateCount>(hv.get(s)??0)){let e=s.state.dataUpdateCount;if(we.get(s)!==e){we.set(s,e),queueMicrotask(()=>{k.observers.get(t)===o&&s.state.data===a.data&&s.state.dataUpdateCount===e&&r(a)});return}if(ye>0&&mv.get(s)!==s.state.data)return}let e=fv.get(s);if(!a.isFetching&&(be.size>0||Ze?.scanPersistedRows!==void 0)&&e!==void 0&&e!==pv.get(s)&&!Ce.has(a)){Ce.add(a),queueMicrotask(()=>{k.observers.get(t)?.getCurrentResult()===a&&r(a)});return}let n=Ae.get(s);if(n!==void 0){if(s.state.dataUpdateCount<=n)return;Ae.delete(s)}}}if(a.isSuccess&&R.deferDataRefresh){if(a.isFetching){St(t,R.deferDataRefresh);return}Ct(t,a,St(t,R.deferDataRefresh))}else{if(a.isSuccess&&!a.isFetching&&(Oe!==void 0||(Te.get(t)??ye)<ye)){let n=o?.getCurrentQuery(),i=Te.get(t)??0;if(G(a)?.type===`pending`)return;let s=Gt(e,a);if(n&&`items`in s){je++;let o=(async()=>{await qt();let o=k.observers.get(t);if(o?.getCurrentQuery()!==n)throw new P;let c=Kt(s.items,i,t),l=()=>{},u=new Promise(e=>{l=o.subscribe(()=>e())}),d=o.getCurrentResult();try{if(Te.set(t,ye),!Ke(e,c)){Qt(t,a,(n,r)=>tt.has(t)?Xt(e,a,r,n,c,i):Yt(e,a,r,void 0,n,c));let n=wt(t);return n!==!0&&await n,o.getCurrentResult()}o.getCurrentResult()===d?r(d):await u}finally{l()}await new Promise(e=>queueMicrotask(e));let f=wt(t);return f!==!0&&await f,o.getCurrentResult()})(),c=()=>{je--};o.then(c,c),Ct(t,a,o);return}}if(a.isSuccess){if(tt.has(t)){if(i.getQueryCache().find({queryKey:e,exact:!0})?.state.dataUpdateCount===0){a.isFetching||k.observers.get(t)?.refetch().catch(()=>{});return}if(a.isFetching)return;Qt(t,a,(n,r)=>Xt(e,a,r,n,void 0,Te.get(t)??ye))}else Qt(t,a,(t,n)=>Yt(e,a,n,void 0,t))}if(s&&a.errorUpdateCount<(nt.get(s)??0)&&nt.delete(s),a.isError&&a.fetchStatus===`idle`){let n=!s||a.errorUpdateCount!==nt.get(s);n&&(s&&nt.set(s,a.errorUpdateCount),at(t)),console.error(`[QueryCollection] Error observing query ${String(e)}:`,a.error),!Ge(a.error)&&n&<(t,a.error)}}}};return r},en=e=>_e.has(e);Pe=(e,t)=>{if(en(e))return!1;let n=z.get(e);return n?($t(n)(t),!0):!1};let tn=(e,t,n)=>{if(!en(t)){w===`eager`&&e.setOptions(e.options);let r=z.get(t),i=$t(r),a=t=>{if(n&&t.isSuccess){let t=e.getCurrentQuery();if(t.state.data===n.data&&t.state.dataUpdateCount===n.version&&(t.state.fetchStatus!==`idle`||fv.get(t)===n.fetchStart))return}i(t)},o=e.subscribe(a);_e.set(t,o);let s=e.getCurrentResult();(s.isSuccess||s.isError)&&a(s)}},nn=()=>{k.observers.forEach((e,t)=>tn(e,t))},rn=()=>{_e.forEach(e=>{e()}),_e.clear()};Ne=()=>{w===`eager`&&k.observers.forEach((e,t)=>{let n=e.getCurrentQuery();i.getQueryCache().get(n.queryHash)!==n&&tn(e,t)})},Qe=!0;let an=R.on(`subscribers:change`,({subscriberCount:e})=>{e>0?nn():e===0&&rn()});if(w===`eager`){let e=Wt({});e instanceof Promise&&e.catch(()=>{})}else $e?We():zt.then(We);nn(),k.observers.forEach((e,t)=>{let n=e.getCurrentQuery(),r=_v.get(n);if(w===`on-demand`&&r&&(r.owner!==re||r.session!==h))return;let i=z.get(t);$t(i)(e.getCurrentResult())});let on=e=>{ve.get(e)?.forEach(e=>{e()}),ve.delete(e)},sn=e=>{let t=k.observers.get(e)?.getCurrentQuery();_e.get(e)?.(),_e.delete(e),on(e),jt(e),tt.delete(e),yt(e);let n=Be(e),r=B.get(e),i=()=>{B.get(e)===r&&B.delete(e)},a=[];n.forEach((e,t)=>{let n=R._state.getAcceptedSyncedRow(t);e.size===0&&n&&a.push(n)});let o=V!==void 0&&n.size>0,s=`${lv}${e}`,c=V?.collection.get(s)!==void 0,l=o||a.length>0||c;l&&g(),n.forEach((e,t)=>{o&&Ot(t,e)}),a.length>0&&a.forEach(e=>{y({type:`delete`,value:e})}),c&&V.collection.delete(s);let u=!l||b(),d=()=>{a.forEach(e=>{let t=v(e);R._state.getAcceptedSyncedRow(t)===void 0&&xe.delete(t)})},f=md(u);f===!0?d():f.then(d,()=>void 0),u===!0?i():u.then(i,()=>void 0),k.observers.delete(e),ut(e),t?.state.fetchStatus!==`fetching`&&Te.delete(e),z.delete(e),rt.delete(e),W.delete(e),gt.delete(e)},cn=e=>{let t=W.get(e)||0,n=k.observers.get(e),r=gt.get(e);t<=0&&(_e.get(e)?.(),_e.delete(e),on(e)),!(t>0)&&(n?.hasListeners()??!1?W.set(e,0):r!==void 0&&V&&Ze?.scanPersistedRows?(yt(e),g(),V.collection.set(`${lv}${e}`,{queryHash:e,mode:r===1/0?`until-revalidated`:`ttl`,...r===1/0?{}:{expiresAt:Date.now()+r}}),b(),r!==1/0&&Ft({queryHash:e,mode:`ttl`,expiresAt:Date.now()+r}),_e.get(e)?.(),_e.delete(e),k.observers.delete(e),ut(e),n?.getCurrentQuery().state.fetchStatus!==`fetching`&&Te.delete(e),z.delete(e),rt.delete(e),W.set(e,0)):sn(e))},ln=e=>{sn(e)},un=i.getQueryCache().subscribe(e=>{if(e.type===`added`&&ee(e.query.queryKey,E)&&oe(e.query),!ie.has(e.query))return;if(e.type===`updated`){if(e.action.type===`fetch`){let t=dv.get(e.action);t===void 0&&(t=++uv,dv.set(e.action,t)),Te.set(M(e.query.queryKey),t),k.observers.forEach((n,r)=>{n.getCurrentQuery()===e.query&&Te.set(r,t)}),fv.set(e.query,t);let n=[...ne.get(e.query)?.keys()??[]].filter(e=>e!==t);n.length>0&&queueMicrotask(()=>me(e.query,n)),fe(e.query,t)}else if(e.action.type===`success`&&!e.action.manual){e.query.state.data===e.action.data&&_v.delete(e.query),mv.set(e.query,e.action.data),hv.set(e.query,e.query.state.dataUpdateCount);let t=fv.get(e.query);t!==void 0&&(pv.set(e.query,t),fe(e.query,t),queueMicrotask(()=>{pe(e.query,t),me(e.query,[t])}))}else if(e.action.type===`error`){let t=fv.get(e.query);t!==void 0&&(fe(e.query,t),queueMicrotask(()=>me(e.query,[t])))}else if(e.action.type===`setState`&&e.action.state.fetchStatus===`idle`){let t=fv.get(e.query);t!==void 0&&queueMicrotask(()=>me(e.query,[t]))}}let t=M(e.query.queryKey);if(k.observers.has(t)||e.type!==`removed`&&e.query.state.fetchStatus===`fetching`||Te.delete(t),e.type===`removed`&&(ie.delete(e.query),z.has(t))){if(w===`eager`){_e.get(t)?.(),_e.delete(t),on(t),R.subscriberCount>0&&Ne();return}cn(t)}});return{loadSubset:w===`eager`?void 0:Wt,unloadSubset:w===`eager`?void 0:e=>{let t=et.get(e);if(t){t.delete(t.values().next().value),t.size===0&&et.delete(e);return}let n=M(Lt(e)),r=e.refetch?void 0:Me.get(n);r!==void 0&&(r===1?Me.delete(n):Me.set(n,r-1));let i=r===void 0?n:te,a=(W.get(i)||0)-1;a<=0?(W.set(i,0),cn(i)):W.set(i,a)},restartAfterScopedRecovery:w===`on-demand`?async e=>{let t=++I;L=!0,rn();for(let e of k.observers.keys())on(e),yt(e);if(await e,Ie!==h)throw new P;t===I&&(B.clear(),H.clear(),tt.clear(),De.clear(),be.clear(),xe.clear(),Se=0,_t.forEach(e=>clearTimeout(e)),_t.clear(),F=uv,L=!1,k.observers.forEach((e,t)=>{(W.get(t)??0)>0&&tn(e,t)}))}:void 0,cleanup:()=>{Ie===h&&(Ie=void 0),clearTimeout(Ye),Ye=void 0,et.clear(),Me.clear(),Ne=()=>{},Pe=()=>!1,an(),rn(),_t.forEach(e=>{clearTimeout(e)}),_t.clear(),ft.forEach(e=>{e.reject(new P)}),ft.clear(),pt.clear(),Fe===G&&(Fe=()=>void 0);let e=new Set([...k.observers.keys(),...B.keys()]);for(let t of e)ln(t);Te.clear(),be.clear(),xe.clear(),Se=0,un();for(let t of[...ie])[...ce(t)].some(t=>e.has(t))&&(w===`eager`||N.has(t)&&t.getObserversCount()===0)&&i.getQueryCache().remove(t);for(let e of ie)gv.get(e)?.delete(re);ie.clear(),N=new WeakSet}}},He=async(e,t)=>{let n=[...z.values()];Ne();let r=Ie,i=I,a=n.map(async n=>{if(L)throw new P;let a=M(n),o=k.observers.get(a);if(!o)return;let s=Fe,c=o.getCurrentQuery(),l,u,d;try{Ee(c,a);let t=o.refetch({throwOnError:e?.throwOnError});c=o.getCurrentQuery(),l=o.getCurrentResult();let n=fv.get(c);if(n!==void 0&&(u=R(c,n,a)),d=await t,L||i!==I)throw new P}catch(e){if(L||i!==I)throw new P;let t=o.getCurrentResult(),n=Pe(a,t)?t:u?.result??t;throw u&&(u.result=n,u.settlement??=ue(a,n)),e}let f=Pe(a,d)?d:u?.result??d;u&&(u.result=f,u.settlement??=ue(a,f)),await new Promise(e=>queueMicrotask(e));let p=s(f)??s(d),m=u?.settlement??ue(a,d)??ue(a,l);if(Ie!==r&&p===void 0&&m===void 0)throw new P;if(t){if(p?.type===`rejected`)throw p.error;if(p?.type===`pending`){let t=await p.promise;if(i!==I)throw new P;if(!t.isSuccess&&e?.throwOnError)throw t.error;return t}}if(t&&!Ue()&&m&&(e?.throwOnError?await m:await m.catch(()=>void 0)),i!==I)throw new P;return f});return await Promise.all(a)},Ue=()=>{if(A>0)return!0;for(let e of Qe?.collection._state.transactions.values()??[])if(e.state===`persisting`)return!0;return!1},We=e=>He(e,!Ue()),Ge=e=>{for(let t of gv.get(e)??[])if(t!==re)return!0;return!1},Ke=(e,t,n)=>{let a=i.getQueryCache().find({queryKey:e,exact:!0}),o=()=>{a&&Ae.set(a,a.state.dataUpdateCount)};if(w===`on-demand`&&a&&Ge(a)||a?.state.status===`pending`&&a.state.fetchStatus!==`idle`)return o(),!1;let s=t=>{if(a)_v.set(a,{owner:re,session:Ie}),a.setState(a.state.status===`pending`?{data:t,status:`success`}:{data:t}),Ae.delete(a);else{i.setQueryData(e,t);let n=i.getQueryCache().find({queryKey:e,exact:!0});n&&_v.set(n,{owner:re,session:Ie})}};if(r){let e=a?.state.data;if(!e||typeof e!=`object`)return o(),!1;if(Array.isArray(e))return s(t),!0;let i=n??r(e);if(!Array.isArray(i))return o(),!1;let c=Object.keys(e).find(t=>e[t]===i);return c===void 0?(o(),!1):(s({...e,[c]:t}),!0)}{let e=a?.state.data;return e===void 0||Array.isArray(e)?(s(t),!0):!1}},qe=()=>{ye=++uv;for(let[e,t]of k.observers)t.getCurrentQuery().state.fetchStatus!==`fetching`&&!U.has(e)&&Te.set(e,ye);return ye},Je=(e,t)=>{let n=je>0||Oe!==void 0||U.size>0;if(!n){for(let e of ie)if(e.state.fetchStatus===`fetching`){n=!0;break}}if(!n)De.clear();else for(let n of e)De.set(n,t)},Ye=e=>{let t=Promise.all([Oe,e]).then(()=>{Oe===t&&(Oe=void 0)},()=>{Oe===t&&(Oe=void 0)});Oe=t},Xe=(e,t,n)=>{ke=!0;try{let r=e(t),i=new Map(r.map(e=>[v(e),e]));Ze(e,t,i);for(let e of t)if(i.has(e))xe.set(e,n),Se=Math.max(Se,n),(H.get(e)?.size??0)===0?be.set(e,n):be.delete(e);else{be.delete(e),xe.delete(e);for(let t of[...H.get(e)??[]])ze(e,t)}}finally{ke=!1}},Ze=(e,t,n)=>{let a=new Set(t),o=e=>{let t=new Set,r=!1;return{patched:e.flatMap(e=>{let i=v(e);if(t.add(i),!a.has(i))return[e];r=!0;let o=n.get(i);return o===void 0?[]:[o]}),present:t,touched:r}};if(w===`on-demand`){let e=new Set(t.flatMap(e=>[...H.get(e)??[]])),n=new Set;for(let[t,i]of k.observers){let a=i.getCurrentQuery();if(n.has(a)||!e.has(t)&&ge(t)&&a.state.fetchStatus!==`fetching`&&!U.has(t))continue;n.add(a);let s=a.state.data,c=r&&s!==void 0?r(s):s;if(!Array.isArray(c))continue;let{patched:l,touched:u}=o(c);u&&Ke(a.queryKey,l,c)}for(let e of[...ie])n.has(e)||Ge(e)||e.getObserversCount()>0||i.getQueryCache().remove(e);return}let s=[...ie];if(s.length>0)for(let i of s){let a=i.state.data,s=r&&a!==void 0?r(a):a;if(!Array.isArray(s)){Ke(i.queryKey,e());continue}let{patched:c,present:l}=o(s);for(let e of t){let t=n.get(e);!l.has(e)&&t!==void 0&&c.push(t)}Ke(i.queryKey,c,s)}else Ke(E,e())},Qe=null,$e=e=>{let n,r=t=>{let r=e.commit(t),i=md(r);if(i!==!0){let e=i.then(()=>{n===e&&(n=void 0)},()=>{n===e&&(n=void 0)});n=e}return r},a={...e,commit:r},{begin:o,write:s,collection:c}=a,l=!1,u=()=>{l||=(i.mount(),!0)},d=()=>{l&&=(i.unmount(),!1)};u();let f=typeof t==`function`?t({}):t,p={collection:c,queryClient:i,queryKey:f,getKey:v,begin:o,write:s,commit:r,updateCacheData:Xe,reserveDirectWrite:qe,claimDirectWriteKeys:Je,noteWaitingDirectWrite:Ye,earlierCommits:()=>n};Qe=p;let m=Ve(a),h=typeof m==`function`?{cleanup:m}:typeof m==`object`?m:{};return{...h,cleanup:()=>(Qe===p&&(Qe=null),rv(h.cleanup,d))}},et=nv(()=>Qe),tt=e=>e&&(async t=>{A++;try{await e(t)}finally{A--}}),nt=new vv(k,We,et),rt=bf({sync:$e},(e,t,n)=>{let r=t;for(let e of Object.keys(et)){let t=r[e];r[e]=(...e)=>(n(),t(...e))}return e}),it={...C,getKey:v,syncMode:w,sync:rt,onInsert:tt(y),onUpdate:tt(b),onDelete:tt(x),utils:nt};return Ug(it,t=>yv({...e,queryClient:t.getDependency(`queryClient`)??e.queryClient,id:it.id}))}var bv=(e,t)=>e.metadata[t];function xv(e,t,n){let r={...e};return n===void 0?delete r[t]:r[t]=n,r}var Sv=`new:`,Cv=0,wv=()=>`${Sv}${String(++Cv).padStart(8,`0`)}`,Tv=e=>e.startsWith(Sv),Ev=e=>e.type!==`update`||!Bs(e.modified.record,e.original.record),Dv=e=>new Set(e.flatMap(e=>[...(e.cells??[]).map(e=>e.key),...e.deletes??[]])),Ov=(e,t)=>e.flatMap(e=>{let n={...e,adds:e.adds?.filter(e=>!t(e)),cells:e.cells?.filter(e=>!t(e.key,e.field)),deletes:e.deletes?.filter(e=>!t(e))};return n.adds?.length||n.cells?.length||n.deletes?.length?[n]:[]});function kv(e,{query:t,key:n,calls:r,held:i,history:a}){let o=()=>new Map((e.getQueryData(t.queryKey)??[]).map(e=>[e.key,e])),s=async({transaction:t})=>{let n=o();for(let o of t.mutations)try{if(o.type===`delete`){await r.delete({key:o.key}),await c.utils.writeDelete(o.key),t.metadata[o.key]=null,e.invalidateQueries({queryKey:a(o.key)});continue}let{record:i}=o.modified,s=await r.save(o.type===`insert`?{record:i,ifAbsent:!0}:{record:i,ifRecord:n.get(o.key)?.record??o.original.record});await c.utils.writeUpsert(s),t.metadata[s.key]=s,e.invalidateQueries({queryKey:a(s.key)})}catch(t){if(!i(t,e))throw t}},c=Cf({...yv({queryKey:t.queryKey,queryFn:t.queryFn,staleTime:t.staleTime,queryClient:e,getKey:e=>e.key,startSync:!0,onInsert:s,onUpdate:s,onDelete:s}),gcTime:1e4}),l=new Map,u=e=>{let t=l.get(e.key);return t||(t=n_({onMutate:({key:e,record:t})=>{c.update(e,e=>{e.record=t})},mutationFn:s,strategy:a_({wait:0})}),l.set(e.key,t)),t(e)},f,p=new Set,m=e=>{f=e;for(let e of p)e()},h=new Map,g=!1,_=()=>{let e=tf({autoCommit:!1,mutationFn:y});return e.when(`settled`).catch(()=>{!g&&f?.tx===e&&b(f.steps)}),e},v=(e,t)=>{let n=new Set(e.mutations.flatMap(e=>e.type===`delete`?[e.key]:[]));for(let e of t.adds??[])c.insert({key:e,record:{},updatedAt:``,updatedBy:``});for(let{key:e,field:r,value:i}of t.cells??[])c.has(e)&&!n.has(e)&&c.update(e,e=>{e.record=xv(e.record,r,i)});for(let e of t.deletes??[])c.has(e)&&c.delete(e,{optimistic:!1})},y=async({transaction:t})=>{let n=t.metadata.only,o=t.mutations.filter(e=>(!n||n.has(e.key))&&Ev(e)),s=e=>(h.get(e.key)??e.original).record,l=o.flatMap(e=>e.type===`insert`?[{record:e.modified.record,ifAbsent:!0}]:e.type===`update`?[{record:e.modified.record,ifRecord:s(e)}]:[]),u=o.flatMap(e=>e.type===`delete`?[{key:e.key,ifRecord:s(e)}]:[]);if(l.length!==0||u.length!==0)try{let t=await r.saveMany({records:l,...u.length>0&&{deletes:u}});await c.utils.writeUpsert(t.filter(e=>`record`in e)),await c.utils.writeDelete(t.flatMap(e=>`record`in e?[]:[e.key]));for(let{key:n}of t)e.invalidateQueries({queryKey:a(n)})}catch(n){if(!i(n,e))throw n;t.metadata.held=d(n)?.runId??null}},b=e=>{f?.tx.state===`pending`&&f.tx.rollback();let t=Dv(e);for(let e of h.keys())t.has(e)||h.delete(e);if(e.length===0)return m(void 0);let n=_();n.mutate(()=>{for(let t of e)v(n,t)}),m({tx:n,steps:e})},x=()=>!f?.saving,S={current:()=>f,subscribe:e=>(p.add(e),()=>void p.delete(e)),add(e){if(!x()||!e.adds?.length&&!e.cells?.length&&!e.deletes?.length)return!1;let t=[...f?.steps??[],e];if(new Set([...Dv(t),...t.flatMap(e=>e.adds??[])]).size>1e3)throw Error(`One change saves at most ${O} records: save some first`);let n=f?.tx??_(),r=o();for(let t of Dv([e])){let e=r.get(t);e&&!h.has(t)&&h.set(t,e)}return n.mutate(()=>v(n,e)),m({tx:n,steps:t}),!0},undo:()=>f&&x()&&b(f.steps.slice(0,-1)),discard:()=>x()&&b([]),drop:(e,t)=>f&&x()&&b(Ov(f.steps,(n,r)=>n===e&&(t===void 0||r===t))),rebase(e,t){if(!t)return S.drop(e);f&&x()&&Dv(f.steps).has(e)&&(h.set(e,t),b(f.steps))},async save(e){let t=f;if(!t||t.saving)return{saved:0};m({...t,saving:!0});try{let r=t=>!e||e.has(t);await c.utils.refetch({throwOnError:!0});let i=o(),a=t.tx.mutations.flatMap(e=>{let t=h.get(e.key),n=i.get(e.key);return t&&n&&r(e.key)&&Ev(e)&&n.updatedAt!==t.updatedAt?[{key:e.key,current:n}]:[]});if(a.length)return{conflicts:a};let s=t.tx.mutations.filter(e=>r(e.key)&&Ev(e)).length;if(t.tx.state!==`pending`)throw Error(`An edit before it was not saved: save again`);t.tx.metadata.only=e,g=!0;try{await t.tx.commit()}catch(e){let r=d(e);if(r?.code===`record_changed`&&r.conflicts){let e=r.conflicts.flatMap(({key:e,current:t})=>t||!c.has(e)?[]:[e]);await c.utils.writeUpsert(r.conflicts.flatMap(({current:e})=>e?[e]:[])),await c.utils.writeDelete(e),b(Ov(t.steps,t=>e.includes(t)));let i=new Set(t.tx.mutations.flatMap(e=>e.type===`insert`?[String(e.modified.record[n])]:[]));return{conflicts:r.conflicts.filter(({key:e})=>!i.has(e))}}if(r?.code===`policy_denied`){let i=new Set(r.denied),a=new Set(t.tx.mutations.flatMap(e=>i.has(e.type===`insert`?String(e.modified.record[n]):e.key)?[e.key]:[]));return b(Ov(t.steps,e=>a.has(e))),{denied:[...i],error:e}}throw b(t.steps),e}finally{g=!1}return b(Ov(t.steps,r)),`held`in t.tx.metadata?{held:s,runId:t.tx.metadata.held??void 0}:{saved:s}}finally{f?.saving&&m({tx:f.tx,steps:f.steps})}}};return{collection:c,edit:u,stage:S}}var Av=new WeakMap;function jv(e,t){let n=Av.get(e);n||Av.set(e,n=new Map);let r=M(t.query.queryKey),i=n.get(r);if(i)return i;let a=kv(e,t);return n.set(r,a),a.collection.on(`status:cleaned-up`,()=>{n.get(r)===a&&n.delete(r)}),a}function Mv(e){return Nv(e)||typeof e==`function`||Pv(e)}function Nv(e){return typeof e==`function`&&(()=>{let t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function Pv(e){return typeof e==`object`&&typeof e.$$typeof==`symbol`&&[`react.memo`,`react.forward_ref`].includes(e.$$typeof.description)}function Fv(e,t){return e==null?null:Mv(e)?K.createElement(e,t):e}function Iv(e){if(`cell`in e&&e.cell){let t=e.cell,n=t.column.columnDef,r=t,i=n;return r.getIsAggregated?.()?Fv(i.aggregatedCell??n.cell,t.getContext()):r.getIsPlaceholder?.()?null:Fv(n.cell,t.getContext())}return`header`in e&&e.header?Fv(e.header.column.columnDef.header,e.header.getContext()):`footer`in e&&e.footer?Fv(e.footer.column.columnDef.footer,e.footer.getContext()):null}function Lv(e){let t=ae(e.source,e.selector,{compare:Tn});return typeof e.children==`function`?e.children(t):e.children}function Rv(e){let t=e;return Object.defineProperty(e,"state",{get(){return e.get()}}),`set`in e&&(t.setState=e.set.bind(e)),t}function zv(e){let{createAtom:t,batch:n}=e,r=t(0);return{createOptionsStore:!1,wrapExternalAtoms:!1,addSubscription:()=>{throw Error(`Feature not supported in current reactivity implementation`)},unmount:()=>{throw Error(`Feature not supported in current reactivity implementation`)},schedule:e.schedule??(e=>queueMicrotask(e)),batch:n,untrack:e=>e(),createReadonlyAtom:(e,n)=>{let i=n?.compare??Object.is,a=!1,o,s=()=>{let t=e();return a&&i(o,t)||(o=t,a=!0),o},c=t(()=>(r.get(),s()),{compare:i});return{get:s,subscribe:c.subscribe.bind(c)}},createWritableAtom:(e,n)=>t(e,{compare:n?.compare}),commit:()=>{r.set(e=>e+1)}}}function Bv(e,t=Object.is){let n=!1,r;return{get:e.get,markCommitted:e=>{r=e,n=!0},subscribe:i=>e.subscribe(e=>{n&&t(r,e)||i(e)})}}function Vv(){return zv({createAtom:ze,batch:Re})}function Hv(e,t){return typeof e==`function`?e(t):e}function Uv(e){if(Array.isArray(e))return e.map(Uv);if(e&&typeof e==`object`){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n=t===null?Wv():{},r=Object.keys(e);for(let t=0;t<r.length;t++){let i=r[t];Object.defineProperty(n,i,{configurable:!0,enumerable:!0,value:Uv(e[i]),writable:!0})}return n}return e}function Wv(){return Object.create(null)}function Gv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Kv(e,t){return n=>{(t.options.atoms?.[e]??t.baseAtoms[e]).set(e=>Hv(n,e))}}function qv(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Jv(e){return Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}var Yv=3;function Xv(e,t){return Zv(e,t,Yv)}function Zv(e,t,n){if(Object.is(e,t))return!0;if(n<=0||!qv(e)||!qv(t)||(Array.isArray(e)||Array.isArray(t))&&(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length))return!1;let r=Jv(e),i=Jv(t);if(r.length!==i.length)return!1;let a=e,o=t;for(let e=0;e<r.length;e++){let i=r[e];if(!Object.prototype.propertyIsEnumerable.call(t,i)||!Zv(a[i],o[i],n-1))return!1}return!0}function Qv(e,t,n,r=Xv){let i=`on${t.charAt(0).toUpperCase()}${t.slice(1)}Change`,a=e.options[i];a&&a(e=>{let t=Hv(n,e);return r(e,t)?e:t})}function $v(e,t){let n=[],r=e=>{e.forEach(e=>{n.push(e);let i=t(e);i.length&&r(i)})};return r(e),n}var ey=({fn:e,memoDeps:t,onAfterCompare:n,onAfterUpdate:r,onBeforeCompare:i,onBeforeUpdate:a})=>{let o=[],s;return c=>{i?.();let l=t?.(c),u=!l||l.length!==o?.length;if(!u&&l){for(let e=0;e<l.length;e++)if(l[e]!==o[e]){u=!0;break}}return n?.(u),u&&(o=l,a?.(),s=e(...l??[]),r?.(s)),s}};function ty(e){let t=!1;return()=>{t?e():t=!0}}function ny({feature:e,fnName:t,objectId:n,onAfterUpdate:r,table:i,...a}){let o={onAfterUpdate:r?()=>{let{schedule:e,untrack:t}=i._reactivity;e(()=>t(()=>r()))}:void 0};return ey({...a,...o})}function ry(e,t=`_`){let[n,r]=e.replace(t,` `).split(` `);return{fnKey:r,fnName:`${n}.${r}`,parentName:n}}function iy(e,t,n){for(let[r,{fn:i,memoDeps:a}]of Object.entries(n)){let{fnKey:n,fnName:o}=ry(r);t[n]=a?ny({memoDeps:a,fn:i,fnName:o,table:t,feature:e}):i}}function ay(e,t,n,r){for(let[i,{fn:a,memoDeps:o}]of Object.entries(r)){let{fnKey:r,fnName:s}=ry(i);if(o){let i=`_memo_${r}`;t[r]=function(...t){if(!this[i]){let t=this;this[i]=ny({memoDeps:e=>o(t,e),fn:(...e)=>a(t,...e),fnName:s,objectId:t.id,table:n,feature:e})}return this[i](...t)}}else t[r]=function(...e){return a(this,...e)}}}function $(e,t,n,...r){return e[t]?.(...r)??n(e,...r)}function oy(e){return e.row.getValue(e.column.id)}function sy(e){return e.getValue()??e.table.options.renderFallbackValue}function cy(e){return{table:e.table,column:e.column,row:e.row,cell:e,getValue:()=>e.getValue(),renderValue:()=>e.renderValue()}}var ly={assignCellPrototype:(e,t)=>{ay(`coreCellsFeature`,e,t,{cell_getValue:{fn:e=>oy(e)},cell_renderValue:{fn:e=>sy(e)},cell_getContext:{fn:e=>cy(e),memoDeps:e=>[e]}})}};function uy(e){if(!e._columnPrototype){e._columnPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignColumnPrototype?.(e._columnPrototype,e)}return e._columnPrototype}function dy(e,t,n,r){let i={...e.getDefaultColumnDef(),...t},a=i.accessorKey,o=a===void 0?void 0:String(a),s=i.id??o?.replaceAll(`.`,`_`)??(typeof i.header==`string`?i.header:void 0),c;if(i.accessorFn)c=i.accessorFn;else if(a!==void 0){if(typeof a==`string`&&a.includes(`.`)){let e=a.split(`.`);c=t=>{let n=t;for(let t=0;t<e.length;t++){let r=e[t];n=n?.[r]}return n}}else c=e=>e[i.accessorKey]}if(!s)throw Error();let l=uy(e),u=Object.create(l);u.accessorFn=c,u.columnDef=i,u.columns=[],u.depth=n,u.id=`${String(s)}`,u.parent=r;let d=e._columnInstanceInitFns;for(let e=0;e<d.length;e++)d[e](u);return u}function fy(e){return e.getIsVisible?.()??!0}function py(e){return e.getVisibleLeafColumns?.()??e.getAllLeafColumns()}function my(e,t){let n=e,r=t;return n.getOrderColumnsFn?.()(r)??n._orderGroupedColumns?.(r)??t}function hy(e,t,n,r){return e._orderByColumnPinning?.(t,n,r)??t}function gy(e,t){return e.getPinnedVisibleLeafColumns?.(t)??(t&&t!==`center`?[]:py(e))}function _y(e,t){return e._expandRows?.(t)??t}function vy(e){e.autoResetExpanded?.()}function yy(e){e.autoResetPageIndex?.()}function by(e){e.autoResetSorting?.()}function xy(e){e.autoResetCellSelection?.()}function Sy(e){return[e,...e.columns.flatMap(e=>e.getFlatColumns())]}function Cy(e){if(e.columns.length){let t=e.columns.flatMap(e=>e.getLeafColumns());return my(e.table,t)}return[e]}function wy(e){return{header:e=>{let t=e.header.column.columnDef;return t.accessorKey?t.accessorKey:t.accessorFn?t.id:null},cell:e=>e.renderValue()?.toString?.()??null,...Object.values(e._features).reduce((e,t)=>Object.assign(e,t.getDefaultColumnDef?.()),{}),...e.options.defaultColumn}}function Ty(e,t,n,r=0){let i=Array(t.length);for(let a=0;a<t.length;a++){if(!(a in t))continue;let o=t[a],s=dy(e,o,r,n),c=o;s.columns=c.columns?Ty(e,c.columns,s,r+1):[],i[a]=s}return i}function Ey(e){return Ty(e,e.options.columns)}function Dy(e){return e.getAllColumns().flatMap(e=>e.getFlatColumns())}function Oy(e){let t=Wv(),n=e.getAllFlatColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function ky(e){return my(e,e.getAllColumns().flatMap(e=>e.getLeafColumns()))}function Ay(e){let t=Wv(),n=e.getAllLeafColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function jy(e,t){return e.getAllFlatColumnsById()[t]}var My={assignColumnPrototype:(e,t)=>{ay(`coreColumnsFeature`,e,t,{column_getFlatColumns:{fn:e=>Sy(e),memoDeps:e=>[e.table.options.columns]},column_getLeafColumns:{fn:e=>Cy(e),memoDeps:e=>[e.table.atoms.columnOrder?.get(),e.table.atoms.grouping?.get(),e.table.options.columns,e.table.options.groupedColumnMode]}})},constructTableAPIs:e=>{iy(`coreColumnsFeature`,e,{table_getDefaultColumnDef:{fn:()=>wy(e),memoDeps:()=>[e.options.defaultColumn]},table_getAllColumns:{fn:()=>Ey(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumns:{fn:()=>Dy(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumnsById:{fn:()=>Oy(e),memoDeps:()=>[e.options.columns]},table_getAllLeafColumns:{fn:()=>ky(e),memoDeps:()=>[e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getAllLeafColumnsById:{fn:()=>Ay(e),memoDeps:()=>[e.getAllLeafColumns()]},table_getColumn:{fn:t=>jy(e,t)}})}};function Ny(e){if(!e._headerPrototype){e._headerPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignHeaderPrototype?.(e._headerPrototype,e)}return e._headerPrototype}function Py(e,t,n){let r=Ny(e),i=Object.create(r);i.colSpan=0,i.column=t,i.depth=n.depth,i.headerGroup=null,i.id=n.id??t.id,i.index=n.index,i.isPlaceholder=!!n.isPlaceholder,i.placeholderId=n.placeholderId,i.rowSpan=0,i.subHeaders=[];let a=e._headerInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function Fy(e,t=1){let n=t;for(let r=0;r<e.length;r++){let i=e[r];fy(i)&&i.columns.length&&(n=Math.max(n,Fy(i.columns,t+1)))}return n}function Iy(e,t){return e?`${e}_${t}`:String(t)}function Ly(e,t,n,r){let i=e??``;return t&&(i=i?`${i}_${t}`:String(t)),n&&(i=i?`${i}_${n}`:n),r&&(i=i?`${i}_${r}`:r),i}function Ry(e,t){let n=0;for(let r=0;r<e.length;r++)e[r].column===t&&n++;return n}function zy(e,t,n,r,i,a){let o={depth:t,id:Iy(r,t),headers:[]},s=[];for(let i=0;i<e.length;i++){if(!(i in e))continue;let a=e[i],c=s[s.length-1],l=a.column.depth===o.depth,u,d=!1;if(l&&a.column.parent?u=a.column.parent:(u=a.column,d=!0),c&&c.column===u)c.subHeaders.push(a);else{let e=Py(n,u,{id:Ly(r,t,u.id,a.id),isPlaceholder:d,placeholderId:d?String(Ry(s,u)):void 0,depth:t,index:s.length});e.subHeaders.push(a),s.push(e)}o.headers.push(a),a.headerGroup=o}for(let e=0;e<a.length;e++)a[e](o);i.push(o),t>0&&zy(s,t-1,n,r,i,a)}function By(e){for(let t=0;t<e.length;t++){let n=e[t];if(!fy(n.column))continue;let r=0;if(n.subHeaders.length){By(n.subHeaders);for(let e=0;e<n.subHeaders.length;e++){let t=n.subHeaders[e];fy(t.column)&&(r+=t.colSpan)}}else r=1;if(n.colSpan=r,n.isPlaceholder&&n.subHeaders.length===1&&n.subHeaders[0].column===n.column){let e=1,t=n.subHeaders[0];for(;t;)t.rowSpan=0,e++,t=t.subHeaders.length===1&&t.subHeaders[0].column===n.column?t.subHeaders[0]:void 0;n.rowSpan=e}else n.rowSpan=1}}function Vy(e,t,n,r){let i=Fy(e),a=[],o=n._headerGroupInstanceInitFns,s=Array(t.length);for(let e=0;e<t.length;e++)e in t&&(s[e]=Py(n,t[e],{depth:i,index:e}));return zy(s,i-1,n,r,a,o),a.reverse(),By(a[0]?.headers??[]),a}function Hy(e,t){for(let n=0;n<e.subHeaders.length;n++)Hy(e.subHeaders[n],t);t.push(e)}function Uy(e){let t=[];return Hy(e,t),t}function Wy(e){return{column:e.column,header:e,table:e.column.table}}function Gy(e){return Vy(e.getAllColumns(),hy(e,py(e),e=>e.id),e)}function Ky(e){return[...e.getHeaderGroups()].reverse()}function qy(e){let t=e.getHeaderGroups(),n=[];for(let e=0;e<t.length;e++){let r=t[e].headers;for(let e=0;e<r.length;e++)n.push(r[e])}return n}function Jy(e){let t=e.getHeaderGroups()[0]?.headers??[],n=[];for(let e=0;e<t.length;e++){let r=t[e].getLeafHeaders();for(let e=0;e<r.length;e++)n.push(r[e])}return n}var Yy={assignHeaderPrototype:(e,t)=>{ay(`coreHeadersFeature`,e,t,{header_getLeafHeaders:{fn:e=>Uy(e),memoDeps:e=>[e.column.table.options.columns]},header_getContext:{fn:e=>Wy(e),memoDeps:e=>[e.column.table.options.columns]}})},constructTableAPIs:e=>{iy(`coreHeadersFeature`,e,{table_getHeaderGroups:{fn:()=>Gy(e),memoDeps:()=>[e.options.columns,e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.atoms.columnPinning?.get(),e.atoms.columnVisibility?.get(),e.options.groupedColumnMode]},table_getFooterGroups:{fn:()=>Ky(e),memoDeps:()=>[e.getHeaderGroups()]},table_getFlatHeaders:{fn:()=>qy(e),memoDeps:()=>[e.getHeaderGroups()]},table_getLeafHeaders:{fn:()=>Jy(e),memoDeps:()=>[e.getHeaderGroups()]}})}};function Xy(e){if(!e._rowPrototype){e._rowPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignRowPrototype?.(e._rowPrototype,e)}return e._rowPrototype}var Zy=(e,t,n,r,i,a,o)=>{let s=Xy(e),c=Object.create(s);c._displayIndexCache=-1,c._uniqueValuesCache=Wv(),c._valuesCache=Wv(),c.depth=i,c.id=t,c.index=r,c.original=n,c.parentId=o,c.subRows=a??[];let l=e._rowInstanceInitFns;for(let e=0;e<l.length;e++)l[e](c);return c};function Qy(){return e=>ny({feature:`coreRowModelsFeature`,table:e,fnName:`table.getCoreRowModel`,memoDeps:()=>[e.options.data],fn:()=>eb(e,e.options.data),onAfterUpdate:ty(()=>{vy(e),yy(e),by(e),xy(e)})})}function $y(e,t,n,r=0,i){let a=[];for(let o=0;o<n.length;o++){let s=n[o],c=Zy(e,e.getRowId(s,o,i),s,o,r,void 0,i?.id);t.flatRows.push(c),t.rowsById[c.id]=c,a.push(c),e.options.getSubRows&&(c.originalSubRows=e.options.getSubRows(s,o),c.originalSubRows?.length&&(c.subRows=$y(e,t,c.originalSubRows,r+1,c)))}return a}function eb(e,t){let n={rows:[],flatRows:[],rowsById:Wv()};return n.rows=$y(e,n,t),n}function tb(e){return e._rowModels.coreRowModel||(e._rowModels.coreRowModel=e.options.features.coreRowModel?.(e)??Qy()(e)),e._rowModels.coreRowModel()}function nb(e){return e.getCoreRowModel()}function rb(e){return e._rowModels.filteredRowModel||(e._rowModels.filteredRowModel=e.options.features.filteredRowModel?.(e)),e.options.manualFiltering||!e._rowModels.filteredRowModel?e.getPreFilteredRowModel():e._rowModels.filteredRowModel()}function ib(e){return e.getFilteredRowModel()}function ab(e){return e._rowModels.groupedRowModel||(e._rowModels.groupedRowModel=e.options.features.groupedRowModel?.(e)),e.options.manualGrouping||!e._rowModels.groupedRowModel?e.getPreGroupedRowModel():e._rowModels.groupedRowModel()}function ob(e){return e.getGroupedRowModel()}function sb(e){return e._rowModels.sortedRowModel||(e._rowModels.sortedRowModel=e.options.features.sortedRowModel?.(e)),e.options.manualSorting||!e._rowModels.sortedRowModel?e.getPreSortedRowModel():e._rowModels.sortedRowModel()}function cb(e){return e.getSortedRowModel()}function lb(e){return e._rowModels.expandedRowModel||(e._rowModels.expandedRowModel=e.options.features.expandedRowModel?.(e)),e.options.manualExpanding||!e._rowModels.expandedRowModel?e.getPreExpandedRowModel():e._rowModels.expandedRowModel()}function ub(e){return e.getExpandedRowModel()}function db(e){return e._rowModels.paginatedRowModel||(e._rowModels.paginatedRowModel=e.options.features.paginatedRowModel?.(e)),e.options.manualPagination||!e._rowModels.paginatedRowModel?e.getPrePaginatedRowModel():e._rowModels.paginatedRowModel()}function fb(e){return e.getPaginatedRowModel()}var pb={constructTableAPIs:e=>{iy(`coreRowModelsFeature`,e,{table_getCoreRowModel:{fn:()=>tb(e)},table_getPreFilteredRowModel:{fn:()=>nb(e)},table_getFilteredRowModel:{fn:()=>rb(e)},table_getPreGroupedRowModel:{fn:()=>ib(e)},table_getGroupedRowModel:{fn:()=>ab(e)},table_getPreSortedRowModel:{fn:()=>ob(e)},table_getSortedRowModel:{fn:()=>sb(e)},table_getPreExpandedRowModel:{fn:()=>cb(e)},table_getExpandedRowModel:{fn:()=>lb(e)},table_getPrePaginatedRowModel:{fn:()=>ub(e)},table_getPaginatedRowModel:{fn:()=>db(e)},table_getRowModel:{fn:()=>fb(e)}})}};function mb(e){if(!e._cellPrototype){e._cellPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignCellPrototype?.(e._cellPrototype,e)}return e._cellPrototype}function hb(e,t,n){let r=mb(n),i=Object.create(r);i.column=e,i.id=`${t.id}_${e.id}`,i.row=t;let a=n._cellInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function gb(e){let t=e.table.getRowsInDisplayOrder(),n=e._displayIndexCache;return t[n]===e?n:-1}function _b(e){let t=e.getPrePaginatedRowModel(),n=e.options.paginateExpandedRows===!1?_y(e,t).rows:t.rows;for(let e=0;e<n.length;e++)n[e]._displayIndexCache=e;return n}function vb(e,t){if(Gv(e._valuesCache,t))return e._valuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return e._valuesCache[t]=n.accessorFn(e.original,e.index),e._valuesCache[t]}function yb(e,t){if(Gv(e._uniqueValuesCache,t))return e._uniqueValuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return n.columnDef.getUniqueValues?(e._uniqueValuesCache[t]=n.columnDef.getUniqueValues(e.original,e.index),e._uniqueValuesCache[t]):(e._uniqueValuesCache[t]=[e.getValue(t)],e._uniqueValuesCache[t])}function bb(e,t){return e.getValue(t)??e.table.options.renderFallbackValue}function xb(e){return $v(e.subRows,e=>e.subRows)}function Sb(e){let t=e.getCoreRowModel().flatRows,n=0;for(let e=0;e<t.length;e++)n=Math.max(n,t[e].depth);return n}function Cb(e){if(e.parentId)return e.table.getCoreRowModel().rowsById[e.parentId]??e.table.getRow(e.parentId,!0)}function wb(e){let t=[],n=e;for(;;){let e=n.getParentRow();if(!e)break;t.push(e),n=e}return t.reverse()}function Tb(e){let t=e.table.getAllLeafColumns(),n=e._cellsCache;n||=e._cellsCache=new WeakMap;let r=Array(t.length);for(let i=0;i<t.length;i++){let a=t[i],o=n.get(a);o||(o=hb(a,e,e.table),n.set(a,o)),r[i]=o}return r}function Eb(e){let t=Wv(),n=e.getAllCells();for(let e=0;e<n.length;e++){let r=n[e];t[r.column.id]=r}return t}function Db(e,t,n,r){return t.options.getRowId?.(e,n,r)??(r?`${r.id}.${n}`:String(n))}function Ob(e,t,n){let r=(n?e.getPrePaginatedRowModel():e.getRowModel()).rowsById[t];if(!r&&(r=e.getCoreRowModel().rowsById[t],!r))throw Error();return r}var kb={assignRowPrototype:(e,t)=>{ay(`coreRowsFeature`,e,t,{row_getDisplayIndex:{fn:e=>gb(e)},row_getAllCellsByColumnId:{fn:e=>Eb(e),memoDeps:e=>[e.getAllCells()]},row_getAllCells:{fn:e=>Tb(e),memoDeps:e=>[e.table.getAllLeafColumns()]},row_getLeafRows:{fn:e=>xb(e),memoDeps:e=>[e.subRows]},row_getParentRow:{fn:e=>Cb(e)},row_getParentRows:{fn:e=>wb(e)},row_getUniqueValues:{fn:(e,t)=>yb(e,t)},row_getValue:{fn:(e,t)=>vb(e,t)},row_renderValue:{fn:(e,t)=>bb(e,t)}})},constructTableAPIs:e=>{iy(`coreRowsFeature`,e,{table_getRowsInDisplayOrder:{fn:()=>_b(e),memoDeps:()=>[e.getPrePaginatedRowModel().rows,e.options.paginateExpandedRows,e.options.paginateExpandedRows===!1?e.atoms.expanded?.get():void 0]},table_getRowId:{fn:(t,n,r)=>Db(t,e,n,r)},table_getRow:{fn:(t,n)=>Ob(e,t,n)},table_getMaxSubRowDepth:{fn:()=>Sb(e),memoDeps:()=>[e.getCoreRowModel()]}})}};function Ab(e,t,n=(e,t)=>e===t){let r=t===void 0?e.options.state:t;e._reactivity.batch(()=>{if(r)for(let t in r){let i=e.baseAtoms[t];if(!i)continue;let a=r[t],o=a===void 0?e.initialState[t]:a;n(e._reactivity.untrack(()=>i.get()),o)||i.set(()=>o)}})}function jb(e,t,n=(e,t)=>e===t){e._reactivity.batch(()=>{Ab(e,t,n),e._reactivity.commit?.()})}function Mb(e){let t=Uv(e.initialState);e._reactivity.batch(()=>{let n=Object.keys(t);for(let r=0;r<n.length;r++){let i=n[r];e.baseAtoms[i].set(t[i])}});let n=Object.values(e._features);for(let t=0;t<n.length;t++)n[t].resetTableInstanceData?.(e)}function Nb(e,t){let{features:n,atoms:r,initialState:i}=e.options;if(!e.options.mergeOptions)return{...e.options,...t,features:n,atoms:r,initialState:i};let a=e.options.mergeOptions(e.options,t),o={...Object.getOwnPropertyDescriptors(a)};return Object.defineProperties(Object.create(Object.getPrototypeOf(a)),{...o,features:{value:n,enumerable:!0,configurable:!0,writable:!0},atoms:{value:r,enumerable:!0,configurable:!0,writable:!0},initialState:{value:i,enumerable:!0,configurable:!0,writable:!0}})}function Pb(e,t,n){let r=Nb(e,Hv(t,e.options));e.optionsStore?e.optionsStore.set(()=>r):e.options=r,n?.syncExternalState!==!1&&jb(e,r.state??null)}var Fb={coreCellsFeature:ly,coreColumnsFeature:My,coreHeadersFeature:Yy,coreRowModelsFeature:pb,coreRowsFeature:kb,coreTablesFeature:{constructTableAPIs:e=>{iy(`coreTablesFeature`,e,{table_reset:{fn:()=>Mb(e)},table_setOptions:{fn:t=>Pb(e,t)}})}}};function Ib(){return{accessor:(e,t)=>typeof e==`function`?{...t,accessorFn:e}:{...t,accessorKey:e},columns:e=>e,display:e=>e,group:e=>e}}function Lb(e){return e}function Rb(e,t={}){return Object.values(e).forEach(e=>{t=e.getInitialState?.(t)??t}),Uv(t)}function zb(e){let t=e.features.coreReactivityFeature,{aggregationFns:n,columnMeta:r,coreRowModel:i,expandedRowModel:a,facetedMinMaxValues:o,facetedRowModel:s,facetedUniqueValues:c,filterFns:l,filterMeta:u,filteredRowModel:d,groupedRowModel:f,paginatedRowModel:p,sortFns:m,sortedRowModel:h,tableMeta:g,..._}=e.features,v={_cellInstanceInitFns:[],_columnInstanceInitFns:[],_features:{...Fb,..._},_headerGroupInstanceInitFns:[],_headerInstanceInitFns:[],_reactivity:t,_rowInstanceInitFns:[],_rowModelFns:{aggregationFns:n,filterFns:l,sortFns:m},_rowModels:{},atoms:{},baseAtoms:{}},y=Object.values(v._features),b={...y.reduce((e,t)=>Object.assign(e,t.getDefaultTableOptions?.(v)),{}),...e};if(t.wrapExternalAtoms&&b.atoms)for(let[e,n]of Object.entries(b.atoms)){let r=n,i=t.createWritableAtom(r.get(),{debugName:`externalAtom/${e}`});b.atoms[e]=i;let a=!1,o=r.subscribe(e=>{a||i.set(e)}),s=i.subscribe(e=>{a=!0,r.set(e),a=!1});t.addSubscription(o),t.addSubscription(s)}t.createOptionsStore?(v.optionsStore=t.createWritableAtom(b,{debugName:`table/optionsStore`}),Object.defineProperty(v,"options",{configurable:!0,enumerable:!0,get(){return v.optionsStore.get()},set(e){v.optionsStore.set(()=>e)}})):v.options=b,v.initialState=Rb(v._features,v.options.initialState);let x=Object.keys(v.initialState);for(let e=0;e<x.length;e++){let n=x[e];v.baseAtoms[n]=t.createWritableAtom(v.initialState[n],{debugName:`table/baseAtoms/${n}`}),v.atoms[n]=t.createReadonlyAtom(()=>{let e=v.options,t=e.atoms?.[n],r=t?t.get():v.baseAtoms[n].get();if(t)return r;let i=e.state;if(i&&Gv(i,n)){let e=i[n];return e===void 0?v.initialState[n]:e}return r},{debugName:`table/atoms/${n}`})}Ab(v),v.store=Rv(t.createReadonlyAtom(()=>{let e={};for(let t=0;t<x.length;t++){let n=x[t];e[n]=v.atoms[n].get()}return e},{compare:Tn,debugName:`table/store`}));for(let e=0;e<y.length;e++){let t=y[e];t.initTableInstanceData?.(v),t.initCellInstanceData&&v._cellInstanceInitFns.push(t.initCellInstanceData.bind(t)),t.initColumnInstanceData&&v._columnInstanceInitFns.push(t.initColumnInstanceData.bind(t)),t.initHeaderGroupInstanceData&&v._headerGroupInstanceInitFns.push(t.initHeaderGroupInstanceData.bind(t)),t.initHeaderInstanceData&&v._headerInstanceInitFns.push(t.initHeaderInstanceData.bind(t)),t.initRowInstanceData&&v._rowInstanceInitFns.push(t.initRowInstanceData.bind(t)),t.constructTableAPIs?.(v)}return v}function Bb(e,t){return e.minRowIndex-t.minRowIndex||e.minColumnIndex-t.minColumnIndex||e.maxRowIndex-t.maxRowIndex||e.maxColumnIndex-t.maxColumnIndex}function Vb(e,t){let n={minRowIndex:Math.max(e.minRowIndex,t.minRowIndex),maxRowIndex:Math.min(e.maxRowIndex,t.maxRowIndex),minColumnIndex:Math.max(e.minColumnIndex,t.minColumnIndex),maxColumnIndex:Math.min(e.maxColumnIndex,t.maxColumnIndex)};return n.minRowIndex<=n.maxRowIndex&&n.minColumnIndex<=n.maxColumnIndex?n:void 0}function Hb(e,t){let n=Vb(e,t);if(!n)return[e];let r=[];return e.minRowIndex<n.minRowIndex&&r.push({...e,maxRowIndex:n.minRowIndex-1}),n.maxRowIndex<e.maxRowIndex&&r.push({...e,minRowIndex:n.maxRowIndex+1}),e.minColumnIndex<n.minColumnIndex&&r.push({minRowIndex:n.minRowIndex,maxRowIndex:n.maxRowIndex,minColumnIndex:e.minColumnIndex,maxColumnIndex:n.minColumnIndex-1}),n.maxColumnIndex<e.maxColumnIndex&&r.push({minRowIndex:n.minRowIndex,maxRowIndex:n.maxRowIndex,minColumnIndex:n.maxColumnIndex+1,maxColumnIndex:e.maxColumnIndex}),r}function Ub(e,t){if(e.minRowIndex===t.minRowIndex&&e.maxRowIndex===t.maxRowIndex&&(e.maxColumnIndex+1===t.minColumnIndex||t.maxColumnIndex+1===e.minColumnIndex))return{minRowIndex:e.minRowIndex,maxRowIndex:e.maxRowIndex,minColumnIndex:Math.min(e.minColumnIndex,t.minColumnIndex),maxColumnIndex:Math.max(e.maxColumnIndex,t.maxColumnIndex)};if(e.minColumnIndex===t.minColumnIndex&&e.maxColumnIndex===t.maxColumnIndex&&(e.maxRowIndex+1===t.minRowIndex||t.maxRowIndex+1===e.minRowIndex))return{minRowIndex:Math.min(e.minRowIndex,t.minRowIndex),maxRowIndex:Math.max(e.maxRowIndex,t.maxRowIndex),minColumnIndex:e.minColumnIndex,maxColumnIndex:e.maxColumnIndex}}function Wb(e){let t=e.slice();for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let r=Ub(t[e],t[n]);if(r){t.splice(n,1),t[e]=r,e=-1;break}}return t.sort(Bb)}function Gb(e,t){let n=[t];for(let t of e)if(n=n.flatMap(e=>Hb(e,t)),!n.length)return e.slice();return Wb([...e,...n])}function Kb(e,t){let n=e,r=!0;for(;r;){r=!1;for(let e of t){if(!Vb(n,e))continue;let t={minRowIndex:Math.min(n.minRowIndex,e.minRowIndex),maxRowIndex:Math.max(n.maxRowIndex,e.maxRowIndex),minColumnIndex:Math.min(n.minColumnIndex,e.minColumnIndex),maxColumnIndex:Math.max(n.maxColumnIndex,e.maxColumnIndex)};(t.minRowIndex!==n.minRowIndex||t.maxRowIndex!==n.maxRowIndex||t.minColumnIndex!==n.minColumnIndex||t.maxColumnIndex!==n.maxColumnIndex)&&(n=t,r=!0)}}return n}function qb(e){let t=[];for(let n of e){let e={minRowIndex:n.minRowIndex,maxRowIndex:n.maxRowIndex,minColumnIndex:n.minColumnIndex,maxColumnIndex:n.maxColumnIndex};t=n.operation===`exclude`?Wb(t.flatMap(t=>Hb(t,e))):Gb(t,e)}return t.sort(Bb)}function Jb(){return[]}function Yb(e,t){e.options.onCellSelectionChange?.(t)}function Xb(e,t){Qv(e,`cellSelection`,t?Jb():Uv(e.initialState.cellSelection)??Jb())}function Zb(e){e.atoms.cellSelection&&(e.options.autoResetAll??e.options.autoResetCellSelection??!0)&&e._reactivity.schedule(()=>Xb(e))}function Qb(e){return hy(e,py(e),e=>e.id)}function $b(e){let t=Qb(e),n=Wv();for(let e=0;e<t.length;e++)n[t[e].id]=e;return n}var ex=[];function tx(e){return e.getCellSpanIndex?.()}function nx(e){let t=tx(e);if(!t)return ex;let n=$(e,`getCellSelectionColumnIndexes`,$b),r=[];for(let e in t.rowSpans){let i=n[e];if(i===void 0)continue;let a=t.rowSpans[e],o=t.columnIndexes[e];for(let e=0;e<a.length;e++){let n=a[e];if(n<=1)continue;let s=t.rows[e].getDisplayIndex(),c=t.rows[e+n-1].getDisplayIndex();if(s<0||c-s!==n-1)continue;let l=o===void 0?1:Math.max(t.colSpans[e]?.[o]??1,1);r.push({minRowIndex:s,maxRowIndex:c,minColumnIndex:i,maxColumnIndex:i+l-1})}}if(t.colSpans.length){let e=[];for(let n in t.columnIndexes)e[t.columnIndexes[n]]=n;for(let i=0;i<t.colSpans.length;i++){let a=t.colSpans[i];if(!a)continue;let o=t.rows[i]?.getDisplayIndex()??-1;if(!(o<0))for(let s=0;s<a.length;s++){let c=a[s];if(c<=1)continue;let l=e[s];if(l===void 0)continue;let u=t.rowSpans[l];if(u&&u[i]!==1)continue;let d=n[l];d!==void 0&&r.push({minRowIndex:o,maxRowIndex:o,minColumnIndex:d,maxColumnIndex:d+c-1})}}}return r}function rx(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];if(t>=i.minRowIndex&&t<=i.maxRowIndex&&n>=i.minColumnIndex&&n<=i.maxColumnIndex)return i}}function ix(e,t,n){let r=e.getPrePaginatedRowModel().rowsById[n]??e.getCoreRowModel().rowsById[n];if(!r)return-1;let i=r.getDisplayIndex();return i<0||i>=t.length||t[i]?.id!==n?-1:i}function ax(e){let t=e.atoms.cellSelection?.get();if(!t?.length)return[];let n=e.getRowsInDisplayOrder(),r=$(e,`getCellSelectionColumnIndexes`,$b),i=[];for(let a=0;a<t.length;a++){let o=t[a],s=ix(e,n,o.anchorRowId),c=ix(e,n,o.focusRowId),l=r[o.anchorColumnId]??-1,u=r[o.focusColumnId]??-1;s<0||c<0||l<0||u<0||i.push({minRowIndex:Math.min(s,c),maxRowIndex:Math.max(s,c),minColumnIndex:Math.min(l,u),maxColumnIndex:Math.max(l,u),operation:o.operation??`include`})}let a=$(e,`getCellSelectionMergeBounds`,nx);if(a.length)for(let e=0;e<i.length;e++){let t=i[e],n=Kb(t,a);t.minRowIndex=n.minRowIndex,t.maxRowIndex=n.maxRowIndex,t.minColumnIndex=n.minColumnIndex,t.maxColumnIndex=n.maxColumnIndex}return qb(i)}function ox(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];if(t>=i.minRowIndex&&t<=i.maxRowIndex&&n>=i.minColumnIndex&&n<=i.maxColumnIndex)return!0}return!1}function sx(e){if(e.column.columnDef.enableCellSelection===!1)return!1;let t=e.table.options.enableCellSelection;return typeof t==`function`?t(e):t??!0}function cx(e){let t=e.table,n=$(t,`getCellSelectionBounds`,ax);if(!n.length||!$(e,`getCanSelect`,sx))return null;let r=e.row.getDisplayIndex();if(r<0)return null;let i=$(t,`getCellSelectionColumnIndexes`,$b)[e.column.id]??-1;return i<0?null:{bounds:n,rowIndex:r,columnIndex:i}}function lx(e){let t=cx(e);return t?ox(t.bounds,t.rowIndex,t.columnIndex):!1}function ux(e){let t=e.table.atoms.cellSelection?.get(),n=t?.[t.length-1];return n?n.anchorRowId===e.row.id&&n.anchorColumnId===e.column.id:!1}function dx(e){return $(e,`getIsFocused`,ux)?0:-1}function fx(e){let t={top:!1,right:!1,bottom:!1,left:!1},n=cx(e);if(!n)return t;let{bounds:r,rowIndex:i,columnIndex:a}=n;if(!ox(r,i,a))return t;let o=$(e.table,`getCellSelectionMergeBounds`,nx),s=o.length?rx(o,i,a):void 0;return s?{top:px(r,s.minRowIndex-1,s.minColumnIndex,s.maxColumnIndex,!0),right:px(r,s.maxColumnIndex+1,s.minRowIndex,s.maxRowIndex,!1),bottom:px(r,s.maxRowIndex+1,s.minColumnIndex,s.maxColumnIndex,!0),left:px(r,s.minColumnIndex-1,s.minRowIndex,s.maxRowIndex,!1)}:{top:!ox(r,i-1,a),right:!ox(r,i,a+1),bottom:!ox(r,i+1,a),left:!ox(r,i,a-1)}}function px(e,t,n,r,i){for(let a=n;a<=r;a++)if(!ox(e,i?t:a,i?a:t))return!0;return!1}function mx(e){let t=e.atoms.cellSelection?.get(),n=t?.[t.length-1];if(n)return(e.getPrePaginatedRowModel().rowsById[n.anchorRowId]??e.getCoreRowModel().rowsById[n.anchorRowId])?.getAllCellsByColumnId()[n.anchorColumnId]}function hx(e,t,n){gx(e,{anchorRowId:t,anchorColumnId:n,focusRowId:t,focusColumnId:n})}function gx(e,t,n){let r=n?.mode??(n?.additive?`include`:`replace`),{operation:i,...a}=t,o=r===`exclude`?{...a,operation:`exclude`}:a;Yb(e,e=>r===`replace`?[o]:[...e,o])}function _x(e){let t=Qb(e);return e.options.enableCellSelection===!1?[]:t.filter(e=>e.columnDef.enableCellSelection!==!1)}function vx(e){let t=e.getRowsInDisplayOrder(),n=_x(e);t.length&&n.length&&gx(e,{anchorRowId:t[0].id,anchorColumnId:n[0].id,focusRowId:t[t.length-1].id,focusColumnId:n[n.length-1].id})}function yx(e){switch(e){case`up`:return{rowDelta:-1,columnDelta:0};case`down`:return{rowDelta:1,columnDelta:0};case`left`:return{rowDelta:0,columnDelta:-1};default:return{rowDelta:0,columnDelta:1}}}function bx(e,t,n,r){let i=e.getRowModel().rows,a=Qb(e);if(!i.length||!a.length)return null;let{rowDelta:o,columnDelta:s}=yx(r),c=i.findIndex(e=>e.id===t),l=a.findIndex(e=>e.id===n);if(c<0||l<0)return null;let u=$(e,`getCellSelectionMergeBounds`,nx),d=i[c].getDisplayIndex(),f=l;if(u.length){let e=rx(u,c,l);e&&(o>0&&(d=e.maxRowIndex),o<0&&(d=e.minRowIndex),s>0&&(f=e.maxColumnIndex),s<0&&(f=e.minColumnIndex))}let p=c+o;if(o&&d!==i[c].getDisplayIndex()){let e=i.findIndex(e=>e.getDisplayIndex()===d);if(e<0)return null;p=e+o}if(p<0||p>=i.length)return null;let m=new Set(_x(e).map(e=>e.id));if(!m.size)return null;let h=f;if(s)do h+=s;while(h>=0&&h<a.length&&!m.has(a[h].id));else if(!m.has(n))for(let e=1;e<a.length;e++){let t=a[l-e],n=a[l+e];if(t&&m.has(t.id)){h=l-e;break}if(n&&m.has(n.id)){h=l+e;break}}if(h<0||h>=a.length||!m.has(a[h].id))return null;let g=p,_=h;if(u.length){let e=rx(u,i[p].getDisplayIndex(),h);if(e){if(g=i.findIndex(t=>t.getDisplayIndex()===e.minRowIndex),g<0)return null;_=e.minColumnIndex}}let v=i[g],y=a[_];return!v||!y?null:{rowId:v.id,columnId:y.id}}function xx(e,t){let n=e.atoms.cellSelection?.get(),r=n?.[n.length-1];if(!r){let t=e.getRowModel().rows,n=_x(e);if(!t.length||!n.length)return;hx(e,t[0].id,n[0].id);return}let i=bx(e,r.anchorRowId,r.anchorColumnId,t);i&&hx(e,i.rowId,i.columnId)}function Sx(e,t){let n=e.atoms.cellSelection?.get(),r=n?.[n.length-1];if(!r){xx(e,t);return}let i=bx(e,r.focusRowId,r.focusColumnId,t);i&&Yb(e,e=>{if(!e.length)return e;let t=e.slice(0,-1);return t.push({...e[e.length-1],focusRowId:i.rowId,focusColumnId:i.columnId}),t})}function Cx(e,t,n=!1){let r=$(e,`getCellSelectionBounds`,ax);if(!r.length)return;let i=e.getRowsInDisplayOrder(),a=Qb(e);for(let e=0;e<r.length;e++){let o=r[e];for(let r=o.minRowIndex;r<=o.maxRowIndex;r++){let s=i[r];if(!s)continue;let c=s.getAllCellsByColumnId();for(let i=o.minColumnIndex;i<=o.maxColumnIndex;i++){let s=a[i];if(!s)continue;let l=c[s.id];l&&$(l,`getCanSelect`,sx)&&(n&&l.getIsCovered?.()||t(l,e,r-o.minRowIndex,i-o.minColumnIndex))}}}}function wx(e){let t=[],n=new Set;return Cx(e,e=>{n.has(e.id)||(n.add(e.id),t.push(e.id))},!0),t}function Tx(e){let t=[];return Cx(e,(e,n,r)=>{let i=t[n]??=[];(i[r]??=[]).push(e.getValue())}),t}function Ex(e){if(e.options.enableCellSelection===!1)return 0;let t=$(e,`getCellSelectionBounds`,ax);if(!t.length)return 0;let n=$(e,`getCellSelectionMergeBounds`,nx);if(typeof e.options.enableCellSelection==`function`||n.length){let t=new Set;return Cx(e,e=>t.add(e.id),!0),t.size}let r=Qb(e),i=0;for(let e of t){let t=0;for(let n=e.minColumnIndex;n<=e.maxColumnIndex;n++){let e=r[n];e&&e.columnDef.enableCellSelection!==!1&&t++}i+=(e.maxRowIndex-e.minRowIndex+1)*t}return i}function Dx(e){let t=$(e,`getCellSelectionBounds`,ax);if(!t.length)return[];let n=e.getRowsInDisplayOrder(),r=new Set,i=[];for(let e=0;e<t.length;e++){let a=t[e];for(let e=a.minRowIndex;e<=a.maxRowIndex;e++){let t=n[e];t&&!r.has(t.id)&&(r.add(t.id),i.push(t.id))}}return i}function Ox(e){let t=$(e,`getCellSelectionBounds`,ax);if(!t.length)return[];let n=Qb(e),r=new Set,i=[];for(let e=0;e<t.length;e++){let a=t[e];for(let e=a.minColumnIndex;e<=a.maxColumnIndex;e++){let t=n[e];t&&!r.has(t.id)&&t.columnDef.enableCellSelection!==!1&&(r.add(t.id),i.push(t.id))}}return i}function kx(e,t){let n=sx(e);return r=>{if(!n)return;let i=e.table,a=i.options,o=t??(typeof document<`u`?document:null),s=a.enableCellRangeSelection!==!1&&(a.isCellRangeSelectionEvent?.(r)??!1),c=a.enableMultiCellRangeSelection!==!1&&(a.isMultiCellRangeSelectionEvent?.(r)??!1);if(a.enableCellSelectionDrag!==!1&&a.enableCellRangeSelection!==!1&&o){i._isSelectingCells=!0;let e=()=>{o.removeEventListener(`mouseup`,e),i._isSelectingCells=!1};o.addEventListener(`mouseup`,e)}let l=e.row.id,u=e.column.id,d=c&&$(e,`getIsSelected`,lx);Yb(i,e=>{let t=e[e.length-1];if(s&&t){let n=e.slice(0,-1);return n.push({...t,focusRowId:l,focusColumnId:u}),n}let n={anchorRowId:l,anchorColumnId:u,focusRowId:l,focusColumnId:u,...d?{operation:`exclude`}:{}};return c?[...e,n]:[n]})}}function Ax(e){let t=sx(e);return n=>{if(!t)return;let r=e.table;if(!r._isSelectingCells)return;let i=r.atoms.cellSelection?.get(),a=i?.[i.length-1];if(!a)return;let o=e.row.id,s=e.column.id;(a.focusRowId!==o||a.focusColumnId!==s)&&Yb(r,e=>{if(!e.length)return e;let t=e.slice(0,-1);return t.push({...e[e.length-1],focusRowId:o,focusColumnId:s}),t})}}var jx={initTableInstanceData:e=>{e._isSelectingCells=!1},resetTableInstanceData:e=>{e._isSelectingCells=!1},getInitialState:e=>({cellSelection:Jb(),...e}),getDefaultTableOptions:e=>({onCellSelectionChange:Kv(`cellSelection`,e),autoResetCellSelection:!0,enableCellSelection:!0,enableCellRangeSelection:!0,enableMultiCellRangeSelection:!0,enableCellSelectionDrag:!0,isCellRangeSelectionEvent:e=>{let t=e;return!!(t.shiftKey||t.nativeEvent?.shiftKey)},isMultiCellRangeSelectionEvent:e=>{let t=e;return!!(t.ctrlKey||t.metaKey||t.nativeEvent?.ctrlKey||t.nativeEvent?.metaKey)}}),assignCellPrototype:(e,t)=>{ay(`cellSelectionFeature`,e,t,{cell_getCanSelect:{fn:e=>sx(e)},cell_getIsSelected:{fn:e=>lx(e)},cell_getIsFocused:{fn:e=>ux(e)},cell_getTabIndex:{fn:e=>dx(e)},cell_getSelectionEdges:{fn:e=>fx(e)},cell_getSelectionStartHandler:{fn:(e,t)=>kx(e,t)},cell_getSelectionExtendHandler:{fn:e=>Ax(e)}})},constructTableAPIs:e=>{iy(`cellSelectionFeature`,e,{table_setCellSelection:{fn:t=>Yb(e,t)},table_resetCellSelection:{fn:t=>Xb(e,t)},table_autoResetCellSelection:{fn:()=>Zb(e)},table_getCellSelectionColumnIndexes:{fn:()=>$b(e),memoDeps:()=>[e.atoms.columnVisibility?.get(),e.atoms.columnOrder?.get(),e.atoms.columnPinning?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getCellSelectionMergeBounds:{fn:()=>nx(e),memoDeps:()=>[e.getCellSpanIndex?.(),e.getRowsInDisplayOrder(),$(e,`getCellSelectionColumnIndexes`,$b)]},table_getCellSelectionBounds:{fn:()=>ax(e),memoDeps:()=>[e.atoms.cellSelection?.get(),e.getRowsInDisplayOrder(),$(e,`getCellSelectionColumnIndexes`,$b),$(e,`getCellSelectionMergeBounds`,nx)]},table_selectCellRange:{fn:(t,n)=>gx(e,t,n)},table_selectAllCells:{fn:()=>vx(e)},table_setFocusedCell:{fn:(t,n)=>hx(e,t,n)},table_getFocusedCell:{fn:()=>mx(e)},table_moveCellSelection:{fn:t=>xx(e,t)},table_extendCellSelection:{fn:t=>Sx(e,t)},table_getSelectedCellIds:{fn:()=>wx(e),memoDeps:()=>[$(e,`getCellSelectionBounds`,ax),$(e,`getCellSelectionMergeBounds`,nx),e.getRowsInDisplayOrder(),e.options.enableCellSelection]},table_getSelectedCellRangesData:{fn:()=>Tx(e),memoDeps:()=>[$(e,`getCellSelectionBounds`,ax),e.getRowsInDisplayOrder(),e.options.enableCellSelection]},table_getSelectedCellCount:{fn:()=>Ex(e),memoDeps:()=>[$(e,`getCellSelectionBounds`,ax),$(e,`getCellSelectionMergeBounds`,nx),e.getRowsInDisplayOrder(),e.options.enableCellSelection]},table_getCellSelectionRowIds:{fn:()=>Dx(e),memoDeps:()=>[$(e,`getCellSelectionBounds`,ax),e.getRowsInDisplayOrder()]},table_getCellSelectionColumnIds:{fn:()=>Ox(e),memoDeps:()=>[$(e,`getCellSelectionBounds`,ax)]}})}};function Mx(){return Wv()}function Nx(){return{size:150,minSize:20,maxSize:2**53-1}}function Px(e){let t=Nx(),n=e.table.atoms.columnSizing?.get(),r=n&&Gv(n,e.id)?n[e.id]:void 0;return Math.min(Math.max(e.columnDef.minSize??t.minSize,r??e.columnDef.size??t.size),e.columnDef.maxSize??t.maxSize)}function Fx(e){let t=Wv(),n=Wv(),r=Array(e.length),i=0;for(let n=0;n<e.length;n++){let a=e[n],o=$(a,`getSize`,Px);r[n]=o,t[a.id]=i,i+=o}let a=0;for(let t=e.length-1;t>=0;t--)n[e[t].id]=a,a+=r[t];return{starts:t,afters:n}}function Ix(e){return{all:Fx(gy(e)),center:Fx(gy(e,`center`)),start:Fx(gy(e,`start`)),end:Fx(gy(e,`end`))}}function Lx(e){return e===`start`?`start`:e===`end`?`end`:e===`center`?`center`:`all`}function Rx(e,t){return $(e.table,`getColumnOffsets`,Ix)[Lx(t)].starts[e.id]??0}function zx(e,t){return $(e.table,`getColumnOffsets`,Ix)[Lx(t)].afters[e.id]??0}function Bx(e){Wx(e.table,t=>{let n=Wv(),r=Object.keys(t);for(let i=0;i<r.length;i++){let a=r[i];a!==e.id&&(n[a]=t[a])}return n})}function Vx(e){if(!e.subHeaders.length)return Px(e.column);let t=0;for(let n=0;n<e.subHeaders.length;n++)t+=Vx(e.subHeaders[n]);return t}function Hx(e){return Vx(e)}function Ux(e){if(e.index>0){let t=e.headerGroup?.headers[e.index-1];if(t)return $(t,`getStart`,Ux)+$(t,`getSize`,Hx)}return 0}function Wx(e,t){e.options.onColumnSizingChange?.(t)}function Gx(e,t){Wx(e,t?Wv():Object.assign(Wv(),Uv(e.initialState.columnSizing??{})))}function Kx(e){let t=0;for(let n=0;n<e.length;n++)t+=$(e[n],`getSize`,Px);return t}function qx(e){return e.getHeaderGroups()[0]?.headers.reduce((e,t)=>e+Hx(t),0)??0}function Jx(e){return Kx(gy(e,`start`))}function Yx(e){return Kx(gy(e,`center`))}function Xx(e){return Kx(gy(e,`end`))}function Zx(){return{startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}}function Qx(e){return(e.columnDef.enableResizing??!0)&&(e.table.options.enableColumnResizing??!0)}function $x(e){return e.table.atoms.columnResizing?.get()?.isResizingColumn===e.id}function eS(e,t){let n=e.table.getColumn(e.column.id),r=Qx(n);return i=>{if(!r||aS(i)&&i.touches.length>1)return;let a=Hx(e),o=e.getLeafHeaders().map(e=>[e.column.id,Px(e.column)]),s=aS(i)?Math.round(i.touches[0].clientX):i.clientX,c=Wv(),l=(e,t)=>{if(typeof t!=`number`)return;let r=n.table,i=r.options.columnResizeMode===`onChange`||e===`end`;r._reactivity.batch(()=>{tS(r,e=>{let n=r.options.columnResizeDirection===`rtl`?-1:1,a=(t-(e.startOffset??0))*n,o=e.startSize??0,s=Math.max(o>0?a/o:0,-.999999);if(i){let t=e.columnSizingStart;for(let e=0;e<t.length;e++){let n=t[e],r=n[1];c[n[0]]=Math.round(Math.max(r>0?r+r*s:a/t.length,0)*100)/100}}return{...e,deltaOffset:a,deltaPercentage:s}}),i&&Wx(r,e=>Object.assign(Wv(),e,c))})},u=null,d=!1,f,p=()=>{d?(d=!1,l(`move`,f),u=requestAnimationFrame(p)):u=null},m=e=>{f=e,typeof requestAnimationFrame==`function`?u===null?(l(`move`,e),u=requestAnimationFrame(p)):d=!0:l(`move`,e)},h=e=>{u!==null&&(cancelAnimationFrame(u),u=null,d=!1),n.table._reactivity.batch(()=>{l(`end`,e??f),tS(n.table,e=>({...e,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))})},g=t||(typeof document<`u`?document:null),_={moveHandler:e=>m(e.clientX),upHandler:e=>{g?.removeEventListener(`mousemove`,_.moveHandler),g?.removeEventListener(`mouseup`,_.upHandler),h(e.clientX)}},v={moveHandler:e=>(e.cancelable&&(e.preventDefault(),e.stopPropagation()),m(e.touches[0].clientX),!1),upHandler:e=>{y(),e.cancelable&&(e.preventDefault(),e.stopPropagation()),h(e.touches[0]?.clientX)},cancelHandler:()=>{y(),h()}},y=()=>{g?.removeEventListener(`touchmove`,v.moveHandler),g?.removeEventListener(`touchend`,v.upHandler),g?.removeEventListener(`touchcancel`,v.cancelHandler)},b=iS()?{passive:!1}:!1;aS(i)?(g?.addEventListener(`touchmove`,v.moveHandler,b),g?.addEventListener(`touchend`,v.upHandler,b),g?.addEventListener(`touchcancel`,v.cancelHandler,b)):(g?.addEventListener(`mousemove`,_.moveHandler,b),g?.addEventListener(`mouseup`,_.upHandler,b)),tS(n.table,e=>({...e,startOffset:s,startSize:a,deltaOffset:0,deltaPercentage:0,columnSizingStart:o,isResizingColumn:n.id}))}}function tS(e,t){e.options.onColumnResizingChange?.(t)}function nS(e,t){tS(e,t?Zx():Uv(e.initialState.columnResizing??Zx()))}var rS=null;function iS(){if(typeof rS==`boolean`)return rS;let e=!1;try{let t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener(`test`,n,t),window.removeEventListener(`test`,n)}catch{e=!1}return rS=e,rS}function aS(e){return e.type===`touchstart`}var oS={getInitialState:e=>({columnResizing:Zx(),...e}),getDefaultTableOptions:e=>({columnResizeMode:`onEnd`,columnResizeDirection:`ltr`,onColumnResizingChange:Kv(`columnResizing`,e)}),assignColumnPrototype:(e,t)=>{ay(`columnResizingFeature`,e,t,{column_getCanResize:{fn:e=>Qx(e)},column_getIsResizing:{fn:e=>$x(e)}})},assignHeaderPrototype:(e,t)=>{ay(`columnResizingFeature`,e,t,{header_getResizeHandler:{fn:(e,t)=>eS(e,t)}})},constructTableAPIs:e=>{iy(`columnResizingFeature`,e,{table_setColumnResizing:{fn:t=>tS(e,t)},table_resetHeaderSizeInfo:{fn:t=>nS(e,t)}})}},sS={getInitialState:e=>({columnSizing:Mx(),...e}),getDefaultColumnDef:()=>Nx(),getDefaultTableOptions:e=>({onColumnSizingChange:Kv(`columnSizing`,e)}),assignColumnPrototype:(e,t)=>{ay(`columnSizingFeature`,e,t,{column_getSize:{fn:e=>Px(e),memoDeps:e=>[t.options.columns,t.atoms.columnSizing?.get()?.[e.id]]},column_getStart:{fn:(e,t)=>Rx(e,t)},column_getAfter:{fn:(e,t)=>zx(e,t)},column_resetSize:{fn:e=>Bx(e)}})},assignHeaderPrototype:(e,t)=>{ay(`columnSizingFeature`,e,t,{header_getSize:{fn:e=>Hx(e),memoDeps:e=>[t.options.columns,e.column.columns.length>0?t.atoms.columnSizing?.get():t.atoms.columnSizing?.get()?.[e.column.id]]},header_getStart:{fn:e=>Ux(e),memoDeps:()=>[t.options.columns,t.atoms.columnSizing?.get(),t.atoms.columnOrder?.get(),t.atoms.columnPinning?.get(),t.atoms.columnVisibility?.get(),t.atoms.grouping?.get(),t.options.groupedColumnMode]}})},constructTableAPIs:e=>{iy(`columnSizingFeature`,e,{table_getColumnOffsets:{fn:()=>Ix(e),memoDeps:()=>[e.options.columns,e.atoms.columnSizing?.get(),e.atoms.columnOrder?.get(),e.atoms.columnPinning?.get(),e.atoms.columnVisibility?.get(),e.atoms.grouping?.get(),e.options.groupedColumnMode]},table_setColumnSizing:{fn:t=>Wx(e,t)},table_resetColumnSizing:{fn:t=>Gx(e,t)},table_getTotalSize:{fn:()=>qx(e),memoDeps:()=>[e.atoms.columnSizing?.get(),e.getHeaderGroups()]},table_getStartTotalSize:{fn:()=>Jx(e),memoDeps:()=>[e.atoms.columnSizing?.get(),e.getHeaderGroups()]},table_getCenterTotalSize:{fn:()=>Yx(e),memoDeps:()=>[e.atoms.columnSizing?.get(),e.getHeaderGroups()]},table_getEndTotalSize:{fn:()=>Xx(e),memoDeps:()=>[e.atoms.columnSizing?.get(),e.getHeaderGroups()]}})}};function cS(){return Wv()}function lS(e,t){dS(e)&&_S(e.table,n=>{let r=Object.assign(Wv(),n),i=t??!$(e,`getIsVisible`,uS),a=e.getLeafColumns();for(let e=0;e<a.length;e++){let t=a[e];dS(t)&&(r[t.id]=i)}return r})}function uS(e){let t=e.table.atoms.columnVisibility?.get();if(!t)return!0;let n=e.columns;return n.length?n.some(e=>$(e,`getIsVisible`,uS)):(Gv(t,e.id)?t[e.id]:void 0)??!0}function dS(e){return(e.columnDef.enableHiding??!0)&&(e.table.options.enableHiding??!0)}function fS(e){return t=>{lS(e,t.target.checked)}}function pS(e){let t=e.getAllCells(),n=[];for(let e=0;e<t.length;e++){let r=t[e];$(r.column,`getIsVisible`,uS)&&n.push(r)}return hy(e.table,n,e=>e.column.id,()=>$(e,`getVisibleCellsByColumnId`,mS))}function mS(e){let t=Wv(),n=e.getAllCells();for(let e=0;e<n.length;e++){let r=n[e];$(r.column,`getIsVisible`,uS)&&(t[r.column.id]=r)}return t}function hS(e){return e.getAllFlatColumns().filter(e=>$(e,`getIsVisible`,uS))}function gS(e){return e.getAllLeafColumns().filter(e=>$(e,`getIsVisible`,uS))}function _S(e,t){Qv(e,`columnVisibility`,t)}function vS(e,t){_S(e,t?Wv():Object.assign(Wv(),Uv(e.initialState.columnVisibility??{})))}function yS(e,t){t??=!bS(e);let n=Wv(),r=e.getAllLeafColumns();for(let e=0;e<r.length;e++){let i=r[e];n[i.id]=t||!dS(i)}_S(e,n)}function bS(e){return!e.getAllLeafColumns().some(e=>!$(e,`getIsVisible`,uS))}function xS(e){return e.getAllLeafColumns().some(e=>$(e,`getIsVisible`,uS))}function SS(e){return t=>{yS(e,t.target.checked)}}var CS={getInitialState:e=>({columnVisibility:cS(),...e}),getDefaultTableOptions:e=>({onColumnVisibilityChange:Kv(`columnVisibility`,e)}),assignColumnPrototype:(e,t)=>{ay(`columnVisibilityFeature`,e,t,{column_getIsVisible:{fn:e=>uS(e),memoDeps:e=>[t.options.columns,t.atoms.columnVisibility?.get(),e.columns]},column_getCanHide:{fn:e=>dS(e)},column_getToggleVisibilityHandler:{fn:e=>fS(e)},column_toggleVisibility:{fn:(e,t)=>lS(e,t)}})},assignRowPrototype:(e,t)=>{ay(`columnVisibilityFeature`,e,t,{row_getVisibleCells:{fn:e=>pS(e),memoDeps:e=>[e.getAllCells(),t.atoms.columnPinning?.get(),t.atoms.columnVisibility?.get()]},row_getVisibleCellsByColumnId:{fn:e=>mS(e),memoDeps:e=>[e.getAllCells(),t.atoms.columnVisibility?.get()]}})},constructTableAPIs:e=>{iy(`columnVisibilityFeature`,e,{table_getVisibleFlatColumns:{fn:()=>hS(e),memoDeps:()=>[e.atoms.columnVisibility?.get(),e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getVisibleLeafColumns:{fn:()=>gS(e),memoDeps:()=>[e.atoms.columnVisibility?.get(),e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_setColumnVisibility:{fn:t=>_S(e,t)},table_resetColumnVisibility:{fn:t=>vS(e,t)},table_toggleAllColumnsVisible:{fn:t=>yS(e,t)},table_getIsAllColumnsVisible:{fn:()=>bS(e)},table_getIsSomeColumnsVisible:{fn:()=>xS(e)},table_getToggleAllColumnsVisibilityHandler:{fn:()=>SS(e)}})}},wS=typeof window>`u`?K.useEffect:K.useLayoutEffect;function TS(e,t){let[{table:n,rootSource:r}]=(0,K.useState)(()=>{let t=zb({...e,features:{coreReactivityFeature:Vv(),...e.features}});return t.Subscribe=(e=>Lv({...e,source:e.source??t.store})),t.FlexRender=Iv,{table:t,rootSource:Bv(t.store,Tn)}}),i=n;Pb(i,t=>({...t,...e}),{syncExternalState:!1});let a=i.options.state,o=r.get(),s=ae(r,t,{compare:Tn});return wS(()=>{r.markCommitted(o),jb(i,a??null,Tn)}),(0,K.useMemo)(()=>({...n,options:e,state:s}),[n,e,s])}var ES=`data-checked`,DS=`data-unchecked`,OS={checked(e){return e?{[ES]:``}:{[DS]:``}},...nt,...Ot},kS=K.createContext(void 0);function AS(){return K.useContext(kS)}var jS=K.createContext(void 0);function MS(){let e=K.useContext(jS);if(e===void 0)throw Error(ct(52));return e}var NS=K.forwardRef(function(e,t){let{render:n,className:r,disabled:i=!1,readOnly:a=!1,required:o=!1,"aria-labelledby":s,value:c,inputRef:l,nativeButton:u=!1,id:d,style:f,...p}=e,m=AS(),{disabled:h,readOnly:g,required:_,form:v,checkedValue:y,touched:b=!1,validation:x,name:S,setCheckedValue:C=at,setTouched:w=at,registerInputRef:T=at}=m??{},{setTouched:E,setFilled:D,state:ee,disabled:te}=jt(),O=Ve(),{labelId:k,getDescriptionProps:A}=kt(),j=te||O.disabled||h||i,M=g||a,ne=_||o,N=v,re=m?y===c:c===``,P=K.useRef(null),ie=At(j,P),ae=K.useRef(null),F=x?.registerInput,I=K.useCallback(e=>F?.(e,{controlRef:P,value:void 0}),[F]),L=ft(l,ae,T,I);it(()=>{ae.current?.checked&&D(!0)},[D]),it(()=>{ae.current&&T(j&&re?null:ae.current)},[re,j,T]);let oe=et(),se=Mt({id:d}),ce=u?void 0:se,R={role:`radio`,"aria-checked":re,"aria-labelledby":Ue(s,k,ae,!u,ce,p[`aria-label`]),[Ce]:re?``:void 0,id:u?se:oe,onKeyDown(e){e.key===`Enter`&&e.preventDefault()},onClick(e){if(e.defaultPrevented||j||M)return;e.preventDefault();let t=ae.current;t&&st(t,e)},onFocus(e){ie(!0),!(e.defaultPrevented||j||M||!b)&&(ae.current?.click(),w(!1))},onBlur(){m||ie(!1)}},{getButtonProps:le,buttonRef:ue}=ot({disabled:j,native:u,composite:!1}),de={type:`radio`,ref:L,form:N,id:ce,name:S,tabIndex:-1,style:S?Ye:Qe,"aria-hidden":!0,...c===void 0?ut:{value:Mn(c)},disabled:j,checked:re,required:ne,readOnly:M,onChange(e){if(e.nativeEvent.defaultPrevented||j||M||c===void 0)return;let t=tt($e,e.nativeEvent);C(c,t),!t.isCanceled&&E(!0)},onClick(e){e.stopPropagation()},onFocus(){P.current?.focus()}},fe=K.useMemo(()=>({...ee,required:ne,disabled:j,readOnly:M,checked:re}),[ee,j,M,re,ne]),pe=fe,me=m!==void 0,he=[t,P,ue],z=[R,p,le,A,x?e=>x.getValidationProps(j,e):ut],B=lt(`span`,e,{enabled:!me,state:fe,ref:he,props:z,stateAttributesMapping:OS});return(0,Q.jsxs)(jS.Provider,{value:pe,children:[me?(0,Q.jsx)(Ct,{tag:`span`,render:n,className:r,style:f,state:fe,refs:he,props:z,stateAttributesMapping:OS}):B,(0,Q.jsx)(`input`,{...de,suppressHydrationWarning:!0})]})}),PS=K.forwardRef(function(e,t){let{render:n,className:r,style:i,keepMounted:a=!1,...o}=e,s=MS(),c=s.checked,{mounted:l,transitionStatus:u,setMounted:d}=Xe(c),f={...s,transitionStatus:u},p=K.useRef(null),m=a||l,h=lt(`span`,e,{ref:[t,p],state:f,props:o,stateAttributesMapping:OS});return Ze({batch:!0,enabled:!c,open:c,ref:p,onComplete(){c||d(!1)}}),m?h:null}),FS=[ht],IS=K.forwardRef(function(e,t){let{render:n,className:r,disabled:i,readOnly:a,required:o,onValueChange:s,value:c,defaultValue:l,form:u,name:d,inputRef:f,id:p,style:m,...h}=e,{setTouched:g,setFocused:_,validationMode:v,name:y,disabled:b,state:x,validation:S,setDirty:C,setFilled:w,validityData:T}=jt(),{labelId:E}=kt(),{clearErrors:D,elementRef:ee}=Dt(),te=An(!0),O=b||i,k=y??d,A=et(p),[j,M]=V({controlled:c,default:l,name:`RadioGroup`,state:`value`}),[ne,N]=K.useState(!1),re=pt((e,t)=>{s?.(e,t),!t.isCanceled&&M(e)}),P=S.getInputControl,ie=K.useMemo(()=>({get current(){return P()}}),[P]),ae=K.useRef(null),F=K.useRef(null),I=ft(ae,f),L=K.useRef(I),oe=pt(e=>{(ae.current!==e||L.current!==I)&&(L.current=I,I?.(e))});it(()=>{oe(ae.current)},[I,oe]);let se=pt(e=>{if(e){if(!e.disabled){F.current||=e;let t=ae.current;(e.checked||t==null||t.disabled)&&oe(e)}return()=>{F.current===e&&(F.current=null),ae.current===e&&oe(null)}}}),ce=pt(()=>{let e=ee.current;if(!e)return j??null;for(let t of S.registeredInputs.keys())if(t.checked&&jn(t,e))return j??null;return null});Pt(ie,A,j??null,ce,!O,d),Ft(j,()=>{D(k),C(j!==T.initialValue),w(j!=null),S.change(j);let e=F.current;j==null&&e&&!e.disabled&&oe(e)});let R=E??te?.legendId,le={...x,disabled:O??!1,required:o??!1,readOnly:a??!1},ue=K.useMemo(()=>({checkedValue:j,disabled:O,form:u,validation:S,name:k,readOnly:a,registerInputRef:se,required:o,setCheckedValue:re,setTouched:N,touched:ne}),[j,O,u,S,k,a,se,o,re,N,ne]),de={id:p,role:`radiogroup`,"aria-required":o||void 0,"aria-disabled":O||void 0,"aria-readonly":a||void 0,"aria-labelledby":R,onBlur(e){Je(e.currentTarget,e.relatedTarget)||(N(!1),g(!0),_(!1),v===`onBlur`&&S.commit(j))},onKeyDownCapture(e){e.key.startsWith(`Arrow`)&&N(!0)}};return(0,Q.jsx)(kS.Provider,{value:ue,children:(0,Q.jsx)(ye,{render:n,className:r,style:m,state:le,props:[de,h,e=>S.getValidationProps(O??!1,e)],refs:[t],stateAttributesMapping:Ot,enableHomeAndEndKeys:!1,modifierKeys:FS})})});function LS({className:e,...t}){return(0,Q.jsx)(IS,{"data-slot":`radio-group`,className:mt(`grid w-full gap-2`,e),...t})}function RS({className:e,...t}){return(0,Q.jsx)(NS,{"data-slot":`radio-group-item`,className:mt(`group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary`,e),...t,children:(0,Q.jsx)(PS,{"data-slot":`radio-group-indicator`,className:`flex size-4 items-center justify-center`,children:(0,Q.jsx)(`span`,{className:`absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground`})})})}var zS=`@updated`,BS={[zS]:`Updated`,"@by":`By`},VS=e=>`sanoma.grid.${e}.widths`;function HS(e){try{let t=JSON.parse(localStorage.getItem(VS(e))??`{}`);return typeof t==`object`&&t?t:{}}catch{return{}}}function US(e,t){try{localStorage.setItem(VS(e),JSON.stringify(t))}catch{}}var WS=`absolute top-1/2 right-2 -translate-y-1/2`;function GS({collection:e,field:t,rows:n,hide:r=[]}){let i=L({from:M_}),a=e=>void i({search:E(e),resetScroll:!1}),o=e.fields[t];return t===e.key||o===void 0?null:(0,Q.jsxs)(wt,{children:[(0,Q.jsx)(yt,{render:(0,Q.jsx)(dt,{variant:`ghost`,size:`icon-xs`,className:WS,"aria-label":`Change the column ${t}`}),children:(0,Q.jsx)(It,{"aria-hidden":`true`})}),(0,Q.jsxs)(gt,{className:`w-64`,children:[(0,Q.jsx)(Tt,{onClick:()=>a({change:`rename`,field:t}),children:`Rename`}),(0,Q.jsx)(Tt,{onClick:()=>a({change:`retype`,field:t}),children:`Change type`}),(0,Q.jsx)(Tt,{onClick:()=>void i({search:e=>({...e,hide:[...r,t]}),replace:!0,resetScroll:!1}),children:(0,Q.jsx)(KS,{title:`Hide for me`,detail:`Only in your view. Fields shows it again.`})}),ce(o)===`json`&&(0,Q.jsx)(qS,{field:t,rows:n,open:a}),(0,Q.jsx)(vt,{}),(0,Q.jsx)(Tt,{variant:`destructive`,onClick:()=>a({change:`hide`,field:t}),children:(0,Q.jsx)(KS,{title:`Remove for everyone…`,detail:`Leaves the grid and the forms. Its values are kept.`})})]})]})}function KS({title:e,detail:t}){return(0,Q.jsxs)(`span`,{className:`flex flex-col`,children:[e,(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t})]})}function qS({field:e,rows:t,open:n}){let r=C(t,e);return r.length===0?null:(0,Q.jsxs)(St,{children:[(0,Q.jsx)(vt,{}),(0,Q.jsx)(_t,{children:`Convert to column: found in this free-form column`}),r.map(({key:t,count:r})=>(0,Q.jsxs)(Tt,{onClick:()=>n({change:`convert`,field:e,key:t}),children:[(0,Q.jsx)(`code`,{className:`text-xs`,children:t}),(0,Q.jsxs)(`span`,{className:`ml-auto text-xs text-muted-foreground`,children:[`in `,r]})]},t))]})}function JS(){return(0,Q.jsx)(Le,{variant:`ghost`,size:`icon-xs`,className:WS,children:(0,Q.jsxs)(A,{from:M_,search:E({change:`add`}),resetScroll:!1,preload:!1,children:[(0,Q.jsx)(rn,{"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`New column`})]})})}var YS=`choice`,XS=[{label:`Text`,type:`text`},{label:`Number`,type:`number`},{label:`Yes / no`,type:`boolean`},{label:`Date`,type:`date`},{label:`A person`,type:`person`},{label:`A choice`,type:YS},{label:`Link to another table`,type:{link:``}},{label:`Free-form`,type:`json`}],ZS=e=>typeof e==`object`&&`enum`in e,QS=(e,t)=>e===YS?ZS(t):Bs(e,t);function $S(e,{change:t,field:n,key:r}){switch(t){case`add`:return`New column in ${e.name}`;case`rename`:return`Rename ${n}`;case`retype`:return`Change the type of ${n}`;case`convert`:return`Make ${r} of ${n} a column`;case`hide`:return`Remove ${n} for everyone`}}var eC=400;function tC({collection:e,column:t}){let n=L({from:M_}),r=he(),i=ge(ie()).data,o=t.field===void 0?void 0:e.fields[t.field],[c,d]=(0,K.useState)(t.change===`rename`?t.field??``:``),[f,m]=(0,K.useState)(o&&t.change===`retype`?ce(o):`text`),[h,g]=(0,K.useState)(ZS(f)?f.enum.join(`
|
|
3
|
+
`):``),[v,b]=(0,K.useState)(!0),[S,C]=(0,K.useState)(),[w,T]=(0,K.useState)(!1),[E,D]=(0,K.useState)(!1),[ee,te]=(0,K.useState)(),O=t.field??``,j=ZS(f)?{enum:h.split(`
|
|
4
|
+
`).flatMap(e=>e.trim()?[e.trim()]:[])}:f,M={add:{kind:`add`,field:c,type:j,required:!v},rename:{kind:`rename`,from:O,to:c},retype:{kind:`retype`,field:O,to:j},convert:{kind:`convert`,field:O,key:t.key??``,type:j},hide:{kind:`hide`,field:O}}[t.change],N=l.safeParse(M),P=N.success?_(e,N.data):N.error.issues[0]?.message,ae=t.change===`rename`&&c===O||t.change===`retype`&&o!==void 0&&Bs(j,ce(o)),I=N.success&&!P&&!ae?N.data:void 0,se=JSON.stringify(I??null),[R,le]=(0,K.useState)(se);(0,K.useEffect)(()=>{let e=setTimeout(()=>le(se),eC);return()=>clearTimeout(e)},[se]);let de=R===se?I:void 0,fe=ge(re(e.name,de)),pe=de?fe.data:void 0,[me]=pe?.changes??[],z=me&&`wontConvert`in me?me.wontConvert:void 0,B=z!==void 0&&z.count>0,V=B&&S?.of===z.count?S.choice:void 0,H=pe&&V?{...pe,changes:pe.changes.map(e=>`wontConvert`in e?{...e,decision:V}:e)}:pe,_e=e=>{C(e&&z?{choice:e,of:z.count}:void 0),T(!1)};async function ve(){if(de){D(!0),te(void 0);try{let t=V?{...de,decision:V}:de,i=V===`clear`?z?.count:void 0,o=await oe({data:{collection:e.name,change:t,clears:i}});if(`recounted`in o){r.setQueryData(re(e.name,de).queryKey,o.recounted),T(!0);return}if(`change`in o){await n({to:`/changes/$id`,params:{id:a(o.change)??o.change}});return}nC(o,pe),ue(r,{file:o.file,name:e.name,before:e.fields,running:o.running===!0}),await n({search:s,resetScroll:!1})}catch(e){te(p(e))}finally{D(!1)}}}return(0,Q.jsxs)(we,{"aria-label":$S(e,t),role:`region`,className:`lg:sticky lg:top-4`,children:[(0,Q.jsxs)(Fe,{children:[(0,Q.jsx)(Me,{className:`self-center`,children:$S(e,t)}),(0,Q.jsx)(U,{children:(0,Q.jsx)(Le,{variant:`ghost`,size:`icon-sm`,children:(0,Q.jsxs)(A,{from:M_,search:s,resetScroll:!1,children:[(0,Q.jsx)(nn,{"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})})]}),(0,Q.jsx)(De,{children:(0,Q.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),ve()},children:[(t.change===`add`||t.change===`rename`)&&(0,Q.jsxs)(en,{children:[(0,Q.jsx)($t,{htmlFor:`column-name`,children:`Name`}),(0,Q.jsx)(Wt,{id:`column-name`,autoComplete:`off`,value:c,onChange:e=>d(e.target.value)}),(0,Q.jsx)(Gt,{children:`Letters and numbers, no spaces. You can rename it later.`})]}),(t.change===`add`||t.change===`retype`||t.change===`convert`)&&(0,Q.jsxs)(Qt,{children:[(0,Q.jsx)(Ut,{variant:`label`,children:`Type`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:XS.map(e=>{let t=QS(e.type,f),n=e.type===YS||F(e.type);return(0,Q.jsx)(dt,{type:`button`,size:`sm`,variant:t?`default`:`outline`,"aria-pressed":t,disabled:!n,title:n?void 0:`Links and free-form columns aren't available yet`,onClick:()=>{m(e.type===YS?{enum:[]}:e.type),_e()},children:e.label},e.label)})})]}),ZS(f)&&(0,Q.jsxs)(en,{children:[(0,Q.jsxs)($t,{htmlFor:`column-choices`,children:[`Choices `,(0,Q.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`· one per line`})]}),(0,Q.jsx)(an,{id:`column-choices`,rows:3,value:h,onChange:e=>{g(e.target.value),_e()}})]}),t.change===`add`&&(0,Q.jsxs)(en,{orientation:`horizontal`,children:[(0,Q.jsx)(Ke,{id:`column-optional`,checked:v,onCheckedChange:b}),(0,Q.jsxs)($t,{htmlFor:`column-optional`,className:`font-normal`,children:[`Optional `,(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`· existing records stay valid with it empty`})]})]}),t.change===`retype`&&o!==void 0&&!k(o)&&(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`It stays optional.`}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1 rounded-lg border bg-muted/40 px-3 py-2.5`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`What will happen`}),(0,Q.jsx)(`span`,{className:`text-sm`,children:ae?`Nothing changes.`:P??(H?u(H):fe.isError?p(fe.error):`Counting the records…`)})]}),B&&(0,Q.jsxs)(Qt,{children:[(0,Q.jsxs)(Ut,{variant:`label`,children:[z.count===1?`This value can't`:`These ${z.count} values can't`,` convert to`,` `,ne(j)]}),(0,Q.jsx)(pn,{keyField:e.key,field:t.key??O,wontConvert:z}),(0,Q.jsx)(LS,{value:V??null,onValueChange:e=>_e(e),children:[`clear`,`keep`].map(e=>(0,Q.jsxs)(en,{orientation:`horizontal`,children:[(0,Q.jsx)(RS,{value:e,id:`column-decision-${e}`}),(0,Q.jsxs)(Yt,{children:[(0,Q.jsx)($t,{htmlFor:`column-decision-${e}`,children:y[e](z.count)}),(0,Q.jsx)(Gt,{children:x[e]})]})]},e))})]}),w&&B&&!V&&(0,Q.jsxs)(Ie,{children:[`The records changed since you chose: `,z.count===1?`1 value`:`${z.count} values`,` can't convert now. Choose again.`]}),ee&&(0,Q.jsx)(Ie,{variant:`destructive`,children:ee}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[i&&(0,Q.jsx)(W,{tone:`waiting`,children:`Waits for admin`}),(0,Q.jsx)(dt,{type:`submit`,className:`ml-auto`,disabled:!pe||ae||B&&!V||E,children:E?`Opening the change…`:`Review the change`})]})]})})]})}function nC({file:e,reshaped:t,running:n},r){let a=n===!1?[`It shows here once Sanoma starts again.`]:[];if(t&&`error`in t){i.error(`Saved in ${e}, but its records weren't brought along: ${t.error}`,{description:[`They hold what they held before.`,...a].join(` `),duration:1/0});return}let o=t&&r?[D(r,t)]:[];i.success(`Saved in ${e}.`,{description:[...o,...a].join(` `)||void 0})}var rC=n(r(),1);function iC(e){return typeof e==`object`?e.key:e}function aC(e,t){let n=e.length;return new Proxy(e,{get(e,r,i){if(typeof r==`string`){let i=r.charCodeAt(0);if(i>=48&&i<=57){let i=+r;if(Number.isInteger(i)&&i>=0&&i<n){let n=e[i];if(typeof n!=`object`){let r=t[i*2];n=e[i]={index:i,key:n,start:r,size:t[i*2+1],end:r+t[i*2+1],lane:0}}return n}}if(r===`length`)return n}return Reflect.get(e,r,i)}})}function oC(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return(o.length!==r.length||o.some((e,t)=>r[t]!==e))&&(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1),i}return o.updateDeps=e=>{r=e},o}function sC(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var cC=(e,t)=>Math.abs(e-t)<1.01,lC=(e,t,n)=>{let r;return Object.assign(function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)},{cancel:()=>{e.clearTimeout(r)}})};function uC({offset:e,isScrolling:t,elementMax:n,holdOffset:r,scrollOffset:i,pendingWrite:a,clampedMaxAtWrite:o}){return t&&a===null&&e===i?`spurious`:a!==null&&Math.abs(e-a.target)<1.5?`readBack`:a!==null&&!a.smooth&&n!==null&&a.target>n+r+.5&&Math.abs(e-(n+r))<1.5||a!==null&&!a.smooth&&a.lowMaxes?.some(t=>Math.abs(e-t)<1.5)?`clampedReadBack`:o!==null&&Math.abs(e-o)<1.5?`clampedEcho`:`external`}var dC=e=>e===`smooth`||e===`smoothFinishing`;function fC({kind:e,offset:t,command:n,target:r}){return e!==`spurious`&&e!==`readBack`&&e!==`clampedReadBack`&&n?.index!=null&&n.phase!==`queued`&&!dC(n.phase)&&!cC(t,n.lastTargetOffset)&&!cC(t,r())&&e!==`clampedEcho`}var pC=40;function mC(e){let t=e[e.length-1];if(t===void 0)return!1;let n=e.length-2;for(;n>=0&&t.t-e[n].t<pC;)n--;if(n<0)return!1;let r=e[n],i=n-1;for(;i>=0&&r.t-e[i].t<pC;)i--;if(i<0)return!1;let a=e[i],o=(t.offset-r.offset)/(t.t-r.t),s=(r.offset-a.offset)/(r.t-a.t);return o*s>=0&&Math.abs(o)>=2*Math.abs(s)&&Math.abs(o)-Math.abs(s)>=.8}function hC(e){let t=e[e.length-1];if(t===void 0)return!1;let n=e.length-2;for(;n>=0&&t.t-e[n].t<pC;)n--;if(n<0)return!1;let r=e[n];return Math.abs(t.offset-r.offset)/(t.t-r.t)>=.05}var gC,_C=()=>{if(gC!==void 0)return gC;if(typeof navigator>`u`)return gC=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return gC=!0;let e=navigator.maxTouchPoints;return gC=navigator.platform===`MacIntel`&&e!==void 0&&e>0},vC,yC=()=>vC===void 0?vC=_C()&&typeof CSS<`u`&&typeof CSS.supports==`function`&&CSS.supports(`overflow-anchor: auto`):vC,bC=()=>!_C()||yC(),xC={capture:!0,passive:!0},SC=class{constructor(e){this.host=e,this._touch=null,this.inMotion=()=>this._touch!==null&&this._touch.phase!==`lateFling`,this.dragging=()=>this._touch?.phase===`down`&&this._touch.moved,this.tail=()=>this._touch?.phase===`tail`?this._touch.moved?`fling`:`tap`:null,this.onScroll=({isScrolling:e,ownReadBack:t,moved:n,external:r})=>(e&&this._touch?.phase===`tail`?this._openTail(this._touch.moved||!t,!1):this._touch?.phase===`lateFling`&&(this.host.now()>this._touch.until?this._touch=null:r&&e&&n&&this._openTail(!0,!1)),!t&&e&&n&&this._touch?.phase===`down`?(this._touch.moved=!0,!0):!1),this.touchStart=()=>{this.end(),this._touch={phase:`down`,moved:!1}},this.touchEnd=()=>{let e=this._touch?.phase===`down`&&this._touch.moved;this.end(),this._openTail(e,e)},this.end=()=>{let e=this.host.getWindow();this._touch?.phase===`tail`&&e!=null&&e.clearTimeout(this._touch.timerId),this._touch=null},this.listen=e=>{let t=()=>this.touchStart(),n=()=>this.touchEnd();return e.addEventListener(`touchstart`,t,xC),e.addEventListener(`touchend`,n,xC),e.addEventListener(`touchcancel`,n,xC),()=>{e.removeEventListener(`touchstart`,t,xC),e.removeEventListener(`touchend`,n,xC),e.removeEventListener(`touchcancel`,n,xC),this.end()}},this._openTail=(e,t)=>{let n=this.host.getWindow();if(n==null)return;this.end();let r={phase:`tail`,moved:e,awaitingFling:t,timerId:n.setTimeout(()=>{this.host.tailStillMoving()?this._openTail(r.moved,r.awaitingFling):(this._touch=r.awaitingFling?{phase:`lateFling`,until:this.host.now()+1e3}:null,this.host.onTailClosed())},150)};this._touch=r}}get touch(){return this._touch}},CC=e=>{let{clientWidth:t,clientHeight:n}=e;return{width:t,height:n}},wC=e=>{let t=new Set;return{schedule:n=>{let r=e.requestAnimationFrame(()=>{t.delete(r),n()});t.add(r)},cancel:()=>{t.forEach(t=>e.cancelAnimationFrame(t)),t.clear()}}},TC=e=>e,EC=e=>{let t=e.overscan*Math.max(e.lanes??1,1),n=Math.max(e.startIndex-t,0),r=Math.min(e.endIndex+t,e.count-1)-n+1,i=Array(r);for(let e=0;e<r;e++)i[e]=n+e;return i},DC=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(CC(n)),!r.ResizeObserver)return()=>{};let a=wC(r),o=new r.ResizeObserver(()=>{let t=()=>{i(CC(n))};e.options.useAnimationFrameWithResizeObserver?a.schedule(t):t()});return o.observe(n,{box:`content-box`}),()=>{o.unobserve(n),a.cancel()}},OC={passive:!0},kC=typeof window>`u`||`onscrollend`in window,AC=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&kC,o=0,s=a?null:lC(i,()=>t(n(r),!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,OC),a&&r.addEventListener(`scrollend`,u,OC),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u),s?.cancel()}},jC=(e,t)=>AC(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),MC=(e,t,n)=>{if(n.options.useCachedMeasurements){let t=n.indexFromElement(e),r=n.options.getItemKey(t);return n.itemSizeCache.get(r)??n.options.estimateSize(t)}if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}if(!t){let t=n.indexFromElement(e),r=n.options.getItemKey(t),i=n.itemSizeCache.get(r);if(i!==void 0)return i}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},NC=(e,{adjustments:t=0,behavior:n},r)=>{var i;let{scrollElement:a,options:o}=r,s=e+t,c=o.horizontal&&o.isRtl&&a!==null&&`ownerDocument`in a;(i=a?.scrollTo)==null||i.call(a,{[o.horizontal?`left`:`top`]:c?-s:s,behavior:n})},PC=(e,t)=>e===`smooth`?t?`smoothLanded`:`smooth`:`instant`,FC=e=>e?.phase===`smooth`||e?.phase===`smoothLanded`;function IC(e,t,n,r){if(t===0)return!1;let i=r(0),a=new Set,o=0;for(;o<e;){let e=n(o);if(e===i)break;a.add(e),o++}let s=e-o;if(s===0||s>=t)return!1;for(let e=0;e<s;e++)if(r(e)!==n(o+e))return!1;for(let e=s;e<t;e++)if(a.has(r(e)))return!1;return!0}var LC=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this._holdOffset=0,this._reportedOverscroll=!1,this._iosGesture=new SC({getWindow:()=>this.targetWindow,now:()=>this.now(),tailStillMoving:()=>{let e=this.scrollState;if(e?.phase!==`queued`||this.pendingWrite!==null)return!1;let t=this._readElementOffset();return t===null||this._lastElementOffset===null||Math.abs(t-this._lastElementOffset)<1?!1:(this._lastElementOffset=t,e.samples=[...e.samples??[],{t:this.now(),offset:t}],!0)},onTailClosed:()=>{let e=this.scrollState;e?.phase===`queued`&&hC(e.samples??[])&&(this.scrollState=null),this._flushHoldIfReady(!0),this._writeAwaitingCommand(),this._retryClampedAdjustment()}}),this._lastElementOffset=null,this.pendingWrite=null,this._clampedAdjustment=null,this.elementsCache=new Map,this._resizeBatch=null,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=null,n=!1,r=!1,i=new Set,a=()=>{if(e)return e;let r=this.targetWindow;if(!r||!r.ResizeObserver)return null;let i=t=wC(r);return e=new r.ResizeObserver(e=>{let t=()=>{let t={sync:!1};this._resizeBatch=t;try{e.forEach(o)}finally{this._resizeBatch=null,t.notify&&(this.notify(t.sync),this._noteClampMax(),this._flushHoldIfReady(!0),this._retryClampedAdjustment(),this.measureElement(null))}};if(this.options.useAnimationFrameWithResizeObserver)i.schedule(t);else{n=!0;try{t()}finally{n=!1}}})},o=e=>{let t=e.target,n=this.indexFromElement(t);if(t.isConnected)this.isIndexInRange(n)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this));else{this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}}};return{disconnect:()=>{var n;(n=a())==null||n.disconnect(),t?.cancel(),i.clear(),r=!1,e=null,t=null},observe:o=>{let s=a();s&&(n?(i.add(o),r||(r=!0,t?.schedule(()=>{r=!1,i.forEach(t=>{t.isConnected&&e?.observe(t,{box:`border-box`})}),i.clear()}))):s.observe(o,{box:`border-box`}))},unobserve:e=>{var t;i.delete(e),(t=a())==null||t.unobserve(e)}}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:TC,rangeExtractor:EC,onChange:()=>{},measureElement:MC,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,anchorTo:`start`,followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,useCachedMeasurements:!1};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}let n=this.options,r=null,i=null,a=!1;if(n!==void 0&&n.enabled&&t.enabled&&t.anchorTo===`end`&&this.scrollElement!==null){let e=n.count,o=t.count,s=this.getMeasurements(),c=this._singleLaneMeasurements?.items??s,l=e=>iC(c[e]),u=e>0?l(0):null,d=e>0?l(e-1):null;if(o!==e||e>0&&o>0&&(t.getItemKey(0)!==u||t.getItemKey(o-1)!==d)){a=!0;let c=e>0?this.getVirtualItemForOffset(this.getScrollOffset())??s[0]:null;c&&(r=[c.key,this.getScrollOffset()-c.start]);let u=t.followOnAppend===!0?`auto`:t.followOnAppend||null;u&&o>0&&this.isAtEnd(n.scrollEndThreshold)&&(e===0||t.getItemKey(o-1)!==d)&&(o>e||IC(e,o,l,t.getItemKey))&&(i=u)}}this.options=t,a&&(this.pendingMin=0,this.itemSizeCacheVersion++);let o=null;if(r&&this.scrollOffset!==null&&!this._awaitingCommandReadBack()){let[e,t]=r,n=this.getMeasurements(),{count:a,getItemKey:s}=this.options,c=0;for(;c<a&&s(c)!==e;)c++;if(c<a){let e=n[c];if(e){let n=Math.max(0,e.start+t);!i&&n!==this.scrollOffset&&(o=n-this.scrollOffset,this.scrollOffset=n)}}}i?this.pendingScrollAnchor={kind:`follow`,behavior:i}:o!==null&&(this._canWriteScroll()?this.pendingScrollAnchor={kind:`anchor`,delta:o}:(this._holdOffset+=o,this._followOffsetTarget(o)))},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=oC(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{var e;this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,(e=this._momentumStop)==null||e.restore(),this._momentumStop=null,this.isScrolling=!1,this.scrollDirection=null,this._holdOffset=0,this._reportedOverscroll=!1,this._clampedAdjustment=null,this.pendingWrite=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}this.scrollElement=e,this.targetWindow=this.scrollElement&&`ownerDocument`in this.scrollElement?this.scrollElement.ownerDocument.defaultView:this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{let n=t?this._elementMaxScrollOffset():null,r=this._reportedOverscroll;this._reportedOverscroll=e<0||n!==null&&e>n+1;let i=e;this._lastElementOffset=i,e=this._toLayoutOffset(e);let a=this._classifyScrollEvent(e,t,n);if(a===`spurious`)return;a===`readBack`?e=this.pendingWrite.target:a===`clampedReadBack`&&this.scrollState?.index!=null&&e<this.getMaxScrollOffset()-1.5?this.scrollState.lastTargetOffset=e:fC({kind:a,offset:e,command:this.scrollState,target:()=>this.getScrollStateTarget(this.scrollState)})&&(this.scrollState=null),this.pendingWrite=null,this._clampedAdjustment!==null&&Math.abs(e-this._clampedAdjustment.maxAtWrite)>=1.5&&(this._clampedAdjustment=null);let o=this.getScrollOffset(),s=this.scrollDirection;this.scrollDirection=t?o===e?this.scrollDirection:o<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t;let c=this.scrollState;if(c?.phase===`queued`&&a===`external`&&t){if(r||this._reportedOverscroll)c.samples=[];else{let e=this.now();c.samples=[...(c.samples??[]).filter(t=>e-t.t<=200),{t:e,offset:i}],(s!==null&&this.scrollDirection!==s||mC(c.samples))&&(this.scrollState=null)}}this._iosGesture.onScroll({isScrolling:t,ownReadBack:a===`readBack`,moved:e!==o,external:a===`external`&&this.scrollState?.phase!==`smooth`&&this.scrollState?.phase!==`smoothFinishing`})&&this.scrollState?.phase===`queued`&&(this.scrollState=null),this._flushHoldIfReady(!0),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement&&this.unsubs.push(this._iosGesture.listen(this.scrollElement)),this._scrollToOffset(this.getScrollOffset())}this._noteClampMax();let t=this.pendingScrollAnchor;this.pendingScrollAnchor=null,t&&this.scrollElement&&this.options.enabled&&(t.kind===`anchor`?this._canWriteScroll()?FC(this.scrollState)&&!cC(this.getScrollOffset()-t.delta,this.scrollState.lastTargetOffset)||(this._followOffsetTarget(t.delta),this._scrollToOffset(this.getScrollOffset())):(this._holdOffset+=t.delta,this._followOffsetTarget(t.delta),this.notify(!1)):this.scrollToEnd({behavior:t.behavior})),this._flushHoldIfReady(!1),this._retryClampedAdjustment()},this._classifyScrollEvent=(e,t,n)=>uC({offset:e,isScrolling:t,elementMax:n,holdOffset:this._holdOffset,scrollOffset:this.scrollOffset,pendingWrite:this.pendingWrite,clampedMaxAtWrite:this._clampedAdjustment?.maxAtWrite??null}),this._retryClampedAdjustment=()=>{if(this._clampedAdjustment===null||!this.scrollElement||!this.options.enabled||!this._canWriteScroll())return;let{target:e,maxAtWrite:t}=this._clampedAdjustment,n=this.getMaxScrollOffset();n>t+.5&&(this._clampedAdjustment=e>n+.5?{target:e,maxAtWrite:n}:null,this._scrollToOffset(e))},this._writeAwaitingCommand=()=>{let e=this.scrollState;if(e===null||e.phase!==`queued`)return;let{behavior:t}=e;this.getMeasurements();let n=this.getScrollStateTarget(e);e.lastTargetOffset=n,this._clampedAdjustment=null,e.phase=PC(t,e.index!=null&&cC(n,this.getScrollOffset())),this._scrollToOffset(n,{behavior:t}),this.scheduleScrollReconcile()},this._readElementOffset=()=>{let e=this.scrollElement;if(e==null)return null;let{horizontal:t,isRtl:n}=this.options;return typeof e.scrollTop==`number`?t?e.scrollLeft*(n&&-1||1):e.scrollTop:typeof e.scrollY==`number`?t?e.scrollX:e.scrollY:null},this._canWriteScroll=()=>!(_C()&&this._iosGesture.inMotion())&&!this._reportedOverscroll,this._flushHoldIfReady=e=>{if(this._holdOffset===0||!this.scrollElement||!this.options.enabled||!this._canWriteScroll()||this.scrollState?.phase===`smooth`)return;this._holdOffset=0,this.scrollOffset!==null&&this.scrollOffset<0&&(this.scrollOffset=0),this.notify(e);let t=this.getCommandWrittenOffset()??this.getScrollOffset();this._clampedAdjustment=this._clampedBy(t),this._scrollToOffset(t)},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=oC(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(e,t,n,r,i,a,o,s)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s}),{key:!1}),this.isIndexInRange=e=>e>=0&&e<this.options.count,this.getMeasurements=oC(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s},c)=>{let l=this.itemSizeCache;if(!i)return this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let u=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=e*2,a=this._singleLaneMeasurements?.flat;if(!a||a.length<i){let e=new Float64Array(i);a&&u>0&&e.set(a.subarray(0,u*2)),a=e}let o=u===0?Array(e):this._singleLaneMeasurements.items.slice(),c;if(u===0)c=t+n;else{let e=u-1;c=a[e*2]+a[e*2+1]+s}for(let t=u;t<e;t++){let e=r(t);o[t]=e;let n=l.get(e),i=typeof n==`number`?n:this.options.estimateSize(t);a[t*2]=c,a[t*2+1]=i,c+=i+s}this._singleLaneMeasurements={flat:a,items:o};let d=aC(o,a);return this.measurementsCache=d,d}let d=this.measurementsCache.slice(0,u),f=Array(a).fill(void 0),p=new Float64Array(a),m=0;for(let e=0;e<u;e++){let t=d[e];t&&(f[t.lane]===void 0&&m++,f[t.lane]=e,p[t.lane]=t.end)}for(let i=u;i<e;i++){let e=r(i),c=this.laneAssignments.get(i),u,h,g=o===`estimate`||l.has(e);if(c!==void 0&&this.options.lanes>1){u=c;let e=f[u],r=e===void 0?void 0:d[e];h=r?r.end+s:t+n}else if(m===a){let e=0,t=p[0],n=f[0];for(let r=1;r<a;r++){let i=p[r];(i<t||i===t&&f[r]<n)&&(e=r,t=i,n=f[r])}u=e,h=t+s,g&&this.laneAssignments.set(i,u)}else u=i%this.options.lanes,h=t+n,g&&this.laneAssignments.set(i,u);let _=l.get(e),v=typeof _==`number`?_:this.options.estimateSize(i),y=h+v;d[i]={index:i,start:h,size:v,end:y,key:e,lane:u},f[u]===void 0&&m++,f[u]=i,p[u]=y}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=oC(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes,this._getLayoutTotalSize()+this.options.scrollMargin],(e,t,n,r,i)=>{if(e.length===0||t===0)return this.range=null,null;let a=Math.max(i-t,0);return this.range=BC(e,t,Math.min(n,a),r,r===1&&this._singleLaneMeasurements!==null?this._singleLaneMeasurements.flat:null),this.range},{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=oC(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t,this.options.lanes]},(e,t,n,r,i,a)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n,lanes:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!FC(this.scrollState))return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e);if(!this.isIndexInRange(t))return;let n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),e.isConnected&&(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{var n;if(!this.isIndexInRange(e))return;this._resizeBatch?.sync&&this.getMeasurements();let r,i,a,o=this._singleLaneMeasurements?.flat;if(this.options.lanes===1&&o!=null)a=this.options.getItemKey(e),i=o[e*2],r=o[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;a=t.key,i=t.start,r=t.size}let s=this.itemSizeCache.get(a)??r,c=t-s;if(c!==0){let o=this.options.anchorTo===`end`&&!FC(this.scrollState)&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,l=o?this._getLayoutTotalSize():0,u=this.getScrollOffset(),d=this.itemSizeCache.has(a)?i+s<=u&&this.scrollDirection!==`backward`:i<u,f=!FC(this.scrollState)&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?d:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:a,start:i,size:r,end:i+r,lane:0},c,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(a,t),this.itemSizeCacheVersion++;let p=!1;if(this._awaitingCommandReadBack()||(o?p=this.applyScrollAdjustment(this._getLayoutTotalSize()-l):f&&(p=this.applyScrollAdjustment(c))),this._resizeBatch){this._resizeBatch.notify=!0,(n=this._resizeBatch).sync||(n.sync=p);return}this.notify(p),this._noteClampMax(),this._flushHoldIfReady(!0),this._retryClampedAdjustment()}},this.getVirtualItems=oC(()=>[this.getVirtualIndexes(),this.getMeasurements(),this._holdOffset],(e,t,n)=>{let r=[];for(let i=0,a=e.length;i<a;i++){let a=t[e[i]];r.push(n===0?a:{...a,start:a.start-n,end:a.end-n})}return r},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._singleLaneMeasurements?.flat,r=this.options.lanes===1&&n!=null;return sC(t[RC(0,t.length-1,r?e=>n[e*2]:e=>sC(t[e]).start,e)])},this._noteClampMax=()=>{if(!this._awaitingCommandReadBack())return;let e=this._elementMaxScrollOffset();if(e===null)return;let t=this.pendingWrite,n=Math.max(e,0)+this._holdOffset;if(n>=t.target)return;let r=t.lowMaxes??=[];r[r.length-1]!==n&&r.push(n)},this.getMaxScrollOffset=()=>(this._elementMaxScrollOffset()??0)+this._holdOffset,this._toLayoutOffset=e=>{let t=e+this._holdOffset;return this.pendingScrollAnchor?.kind===`anchor`&&(t+=this.pendingScrollAnchor.delta),t},this._elementMaxScrollOffset=()=>{let e=this.scrollElement;if(e===null)return null;if(`scrollHeight`in e)return this.options.horizontal?e.scrollWidth-e.clientWidth:e.scrollHeight-e.clientHeight;if(`document`in e){let t=e.document.documentElement;return this.options.horizontal?t.scrollWidth-e.innerWidth:t.scrollHeight-e.innerHeight}return null},this._momentumStop=null,this._stopMomentum=e=>{let t=this.scrollElement,n=this.targetWindow;if(t===null||n===null)return;let r=`document`in t?t.document.scrollingElement:t;if(!r?.style)return;if(this._momentumStop){this._momentumStop.done=e;return}let{style:i}=r,a=this.options.horizontal?`overflow-x`:`overflow-y`,o=i.getPropertyValue(a),s=i.getPropertyPriority(a),c=()=>this.options.horizontal?r.clientHeight:r.clientWidth,l=c();if(i.setProperty(a,`hidden`,`important`),c()!==l){i.setProperty(a,o,s);return}let u={restore:()=>i.getPropertyValue(a)!==`hidden`||i.getPropertyPriority(a)!==`important`?!1:(i.setProperty(a,o,s),!0),done:e};this._momentumStop=u,n.requestAnimationFrame(()=>n.requestAnimationFrame(()=>{this._momentumStop===u&&(this._momentumStop=null,u.restore()&&u.done())}))},this._clampedBy=e=>{let t=this._elementMaxScrollOffset();if(t===null)return null;let n=t+this._holdOffset;return e>n+.5?{target:e,maxAtWrite:n}:null},this.getVirtualDistanceFromEnd=()=>Math.max(this._getLayoutTotalSize()+this.options.scrollMargin-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(e=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=e,this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.getMeasurements()[e];if(!i)return;if(t===`auto`){if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t]}if(t===`end`&&e===this.options.count-1){let e=this.getMaxScrollOffset(),n=e-this.options.paddingEnd+this.options.scrollPaddingEnd;return[Math.max(Math.min(n,e),0),t]}let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{this._startScroll({index:null,align:t},this.getOffsetForAlignment(e,t),n,`absolute`)},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r;this._startScroll({index:e,align:a},i,n,`absolute`)},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getOffsetForAlignment((this.getCommandWrittenOffset()??this.getScrollOffset())+e,`start`);this._startScroll({index:null,align:`start`},n,t,`relative`)},this.scrollToEnd=({behavior:e=`auto`}={})=>{this.options.count>0?this._startScroll({index:this.options.count-1,align:`end`,toEnd:!0},Math.max(this.getMaxScrollOffset(),0),e,`absolute`):this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:e})},this.cancelScroll=()=>{this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null},this.getTotalSize=()=>Math.max(this._getLayoutTotalSize()-this._holdOffset,0),this._getLayoutTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._singleLaneMeasurements?.flat;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n}={})=>{let r={target:e+(t??0),smooth:n===`smooth`};return this.pendingWrite=r,this.options.scrollToFn(e-this._holdOffset,{behavior:n,adjustments:t},this),r},this.getCommandWrittenOffset=()=>this.scrollState!==null&&this.pendingWrite!==null&&!this.pendingWrite.smooth?this.pendingWrite.target:null,this._awaitingCommandReadBack=()=>{let e=this.getCommandWrittenOffset();return!(_C()&&this._iosGesture.dragging())&&e!==null&&!cC(e,this.getScrollOffset())},this._followOffsetTarget=e=>{this.scrollState!==null&&this.scrollState.index==null&&(this.scrollState.lastTargetOffset+=e)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}get scrollAdjustments(){return 0}applyScrollAdjustment(e,t){if(e===0)return!1;if(this._followOffsetTarget(e),this._canWriteScroll()){let n=this.getScrollOffset();this._clampedAdjustment=this._clampedBy(n+e);let r=this._scrollToOffset(n,{adjustments:e,behavior:t});return this.scrollOffset!==null&&(this.pendingWrite===r&&(this.scrollOffset+=e),this.scrollOffset<0&&(this.scrollOffset=0)),!0}return this._holdOffset+=e,this.scrollOffset!==null&&(this.scrollOffset+=e),!0}scheduleScrollReconcile(){this.targetWindow?this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}):this.scrollState=null}getScrollStateTarget(e){let t=e.toEnd?[Math.max(this.getMaxScrollOffset(),0)]:e.index==null?void 0:this.getOffsetForIndex(e.index,e.align);return t?t[0]:e.lastTargetOffset}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}if(this.scrollState.phase===`queued`){this.scheduleScrollReconcile();return}this.getMeasurements();let e=this.getScrollStateTarget(this.scrollState),t=this.scrollState.index==null?1:this.options.useAnimationFrameWithResizeObserver?3:2,n=e!==this.scrollState.lastTargetOffset;if(!n&&cC(e,this.getScrollOffset())){if(this.scrollState.phase===`smooth`?this.scrollState.phase=`smoothLanded`:this.scrollState.phase===`smoothFinishing`&&(this.scrollState.phase=`instant`),this.scrollState.stableFrames++,this.scrollState.stableFrames>=t){this.getScrollOffset()!==e&&this._scrollToOffset(e,{behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let t=this.getSize()||600,n=Math.abs(e-this.getScrollOffset()),r=FC(this.scrollState)&&n>t;this.scrollState.lastTargetOffset=e,r?this.scrollState.phase=`smooth`:this.scrollState.phase===`smooth`?this.scrollState.phase=`smoothFinishing`:this.scrollState.phase===`smoothLanded`&&(this.scrollState.phase=`instant`),this._scrollToOffset(e,{behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}_startScroll(e,t,n,r){this.pendingScrollAnchor=null,this._clampedAdjustment=null;let i=this._iosGesture.tail();if(r===`absolute`&&i!==null){if(i===`fling`&&bC()){this._stopMomentum(()=>{this.scrollState?.phase!==`queued`||this._iosGesture.tail()!==`fling`||this._reportedOverscroll||(this._iosGesture.end(),this._flushHoldIfReady(!0),this._writeAwaitingCommand())}),this.scrollState={...e,startedAt:this.now(),lastTargetOffset:t,stableFrames:0,phase:`queued`,behavior:n,samples:[]},this.scheduleScrollReconcile();return}this._iosGesture.end()}this.scrollState={...e,startedAt:this.now(),lastTargetOffset:t,stableFrames:0,behavior:n,phase:PC(n,e.index!=null&&cC(t,this.getScrollOffset()))},this._scrollToOffset(t,{behavior:n}),this.scheduleScrollReconcile()}},RC=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function zC(e,t,n){let r=0;for(;r<=t;){let i=(r+t)/2|0,a=e[i*2];if(a<n)r=i+1;else if(a>n)t=i-1;else return i}return r>0?r-1:0}function BC(e,t,n,r,i){let a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&i!==null){let e=zC(i,a,n),r=e,o=n+t;for(;r<a&&i[r*2]+i[r*2+1]<o;)r++;return{startIndex:e,endIndex:r}}let o=RC(0,a,t=>e[t].start,n),s=o;if(r===1)for(;s<a&&e[s].end<n+t;)s++;else if(r>1){let i=Array(r).fill(0);for(;s<a&&i.some(e=>e<n+t);){let t=e[s];i[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(a,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var VC=typeof document<`u`?K.useLayoutEffect:K.useEffect;function HC({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=K.useReducer(e=>e+1,0)[1],a=K.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;let o=K.useRef(!1),s=e=>{let t=a.current;if(!t.enabled||!t.container)return;let n=e.getTotalSize();if(n!==t.lastSize){t.lastSize=n;let r=e.options.horizontal?`width`:`height`;t.container.style[r]=`${n}px`}},c=(e,t,n)=>{let r=a.current,i=!!e.options.horizontal,o=t.start-e.options.scrollMargin;r.lastPositions.get(n)!==o&&(r.lastPositions.set(n,o),r.mode===`transform`?n.style.transform=i?`translate3d(${o}px, 0, 0)`:`translate3d(0, ${o}px, 0)`:n.style[i?`left`:`top`]=`${o}px`)},l=e=>{let t=a.current;if(t.enabled&&t.container){s(e);for(let t of e.getVirtualItems()){let n=e.elementsCache.get(t.key);n&&c(e,t,n)}}},u={...r,onChange:(t,n)=>{var s;let c=a.current,u=!0;if(c.enabled){l(t);let e=t.range,n=c.prevRange;u=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,u&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}u&&(e&&n&&!o.current?(0,rC.flushSync)(i):i()),(s=r.onChange)==null||s.call(r,t,n)}},[d]=K.useState(()=>{let e=new LC(u),t=e.measureElement;return e.measureElement=n=>{o.current=!0;try{t(n)}finally{o.current=!1}let r=a.current;if(n!==null&&r.enabled&&r.container){let t=e.measurementsCache[e.indexFromElement(n)];t&&c(e,t,n)}},Object.assign(e,{containerRef:t=>{let n=a.current;n.container=t,n.lastSize=null,t!==null&&l(e)}})});return d.setOptions(u),VC(()=>d._didMount(),[]),VC(()=>(s(d),d._willUpdate())),VC(()=>{l(d)}),d}function UC(e){return HC({observeElementRect:DC,observeElementOffset:jC,scrollToFn:NC,...e})}var WC=new Map([[`bold`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M228,144v64a12,12,0,0,1-12,12H40a12,12,0,0,1-12-12V144a12,12,0,0,1,24,0v52H204V144a12,12,0,0,1,24,0Zm-108.49,8.49a12,12,0,0,0,17,0l40-40a12,12,0,0,0-17-17L140,115V32a12,12,0,0,0-24,0v83L96.49,95.51a12,12,0,0,0-17,17Z`}))],[`duotone`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M216,48V208H40V48A16,16,0,0,1,56,32H200A16,16,0,0,1,216,48Z`,opacity:`0.2`}),K.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40a8,8,0,0,0-11.32-11.32L136,124.69V32a8,8,0,0,0-16,0v92.69L93.66,98.34a8,8,0,0,0-11.32,11.32Z`}))],[`fill`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40A8,8,0,0,0,168,96H136V32a8,8,0,0,0-16,0V96H88a8,8,0,0,0-5.66,13.66Z`}))],[`light`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M222,144v64a6,6,0,0,1-6,6H40a6,6,0,0,1-6-6V144a6,6,0,0,1,12,0v58H210V144a6,6,0,0,1,12,0Zm-98.24,4.24a6,6,0,0,0,8.48,0l40-40a6,6,0,0,0-8.48-8.48L134,129.51V32a6,6,0,0,0-12,0v97.51L92.24,99.76a6,6,0,0,0-8.48,8.48Z`}))],[`regular`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40a8,8,0,0,0-11.32-11.32L136,124.69V32a8,8,0,0,0-16,0v92.69L93.66,98.34a8,8,0,0,0-11.32,11.32Z`}))],[`thin`,K.createElement(K.Fragment,null,K.createElement(`path`,{d:`M220,144v64a4,4,0,0,1-4,4H40a4,4,0,0,1-4-4V144a4,4,0,0,1,8,0v60H212V144a4,4,0,0,1,8,0Zm-94.83,2.83a4,4,0,0,0,5.66,0l40-40a4,4,0,1,0-5.66-5.66L132,134.34V32a4,4,0,0,0-8,0V134.34L90.83,101.17a4,4,0,0,0-5.66,5.66Z`}))]]),GC=K.forwardRef((e,t)=>K.createElement(rt,{ref:t,...e,weights:WC}));GC.displayName=`DownloadSimpleIcon`;function KC({name:e,recordKey:t}){let{actor:n}=Xt(),r=ge({...b(e,t),enabled:n!==null});return(0,Q.jsxs)(`section`,{"aria-label":`History`,className:`flex flex-col gap-2 border-t pt-4 text-sm`,children:[(0,Q.jsx)(`h3`,{className:`text-xs font-medium text-muted-foreground`,children:`History · from the ledger`}),r.data?(0,Q.jsxs)(Q.Fragment,{children:[r.data.writes.length>0&&(0,Q.jsx)(`ul`,{className:`flex flex-col gap-1.5`,children:r.data.writes.map((e,t)=>(0,Q.jsx)(qC,{entry:e,you:n},t))}),r.data.more?(0,Q.jsx)(ve,{children:`Older changes are not shown.`}):!r.data.writes.length&&(0,Q.jsx)(ve,{children:`No changes yet.`})]}):r.isError?(0,Q.jsx)(Ie,{variant:`destructive`,children:p(r.error)}):(0,Q.jsx)(H,{role:`status`,"aria-label":`Loading the history`,className:`h-12 w-full`})]})}function qC({entry:e,you:t}){let n=e.workflow===`call`?e.by===t?`you`:e.by:e.workflow;return(0,Q.jsxs)(`li`,{"data-slot":`history-line`,children:[(0,Q.jsxs)(`span`,{className:`text-muted-foreground`,children:[(0,Q.jsx)(je,{at:e.at}),` · `,n]}),` `,`· `,(0,Q.jsx)(JC,{change:e.change}),!e.runId.startsWith(`direct:`)&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,(0,Q.jsx)(A,{...pe(e),className:`text-muted-foreground underline-offset-4 hover:underline`,children:`run`})]})]})}function JC({change:e}){return e===`created`?(0,Q.jsx)(W,{tone:Ee.added,children:`created`}):e===`deleted`?(0,Q.jsx)(W,{tone:Ee.removed,children:`deleted`}):e.length?e.map((e,t)=>(0,Q.jsxs)(`span`,{children:[t>0&&`, `,(0,Q.jsx)(YC,{change:e})]},e.field)):(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`saved as it was`})}function YC({change:{field:e,before:t,after:n}}){return[t,n].some(e=>typeof e==`string`&&e.length>40)?(0,Q.jsxs)(Q.Fragment,{children:[e,` rewritten`]}):(0,Q.jsxs)(Q.Fragment,{children:[e,` `,(0,Q.jsxs)(`span`,{className:`text-muted-foreground`,children:[(0,Q.jsx)(L_,{value:t}),` →`]}),` `,(0,Q.jsx)(L_,{value:n})]})}function XC({name:e,recordKey:t}){return(0,Q.jsx)(A,{to:`/data/$name`,params:{name:e},search:g(t),title:`Its history, from the ledger`,className:`underline underline-offset-4`,children:t})}var ZC=new Set([`string`,`number`,`integer`,`json`]),QC=/^\d{4}-\d{2}-\d{2}$/;function $C(e,t,n,r){let i=ZC.has(e.kind)||e.kind===`person`&&r.length===0;return n!==void 0&&i?n:bn(e,t)}function ew(e,t,n){let{input:r,errors:i}=Cn([e],{[e.key]:n}),a=i[e.key];return a?{error:a}:{record:xv(t,e.key,r[e.key])}}var tw=/^(true|yes)$/i,nw=/^(false|no)$/i;function rw(e,t){let n=t.trim();if(n===``)return e.required?{error:`Needs a value`}:{value:void 0};let r=t;if(e.kind===`boolean`){if(!tw.test(n)&&!nw.test(n))return{error:`Not yes or no`};r=tw.test(n)}else if(e.kind===`enum`){let t=e.options?.findIndex(e=>String(e)===n)??-1;if(t===-1)return{error:`Not one of its choices`};r=String(t)}let{input:i,errors:a}=Cn([e],{[e.key]:r}),o=a[e.key];return o?{error:o}:{value:i[e.key]}}function iw(e){e?.focus(),e instanceof HTMLInputElement&&e.type===`text`&&e.setSelectionRange(e.value.length,e.value.length)}function aw({field:e,draft:t,people:n,label:r,onDraft:i,onBlur:a}){let o=typeof t==`string`?t:``,s={ref:iw,"aria-label":r,onBlur:a},c=e=>i(e.target.value);switch(e.kind){case`boolean`:return(0,Q.jsx)(Ke,{...s,checked:t===!0,onCheckedChange:e=>i(e===!0)});case`enum`:case`person`:{if(e.kind===`person`&&n.length===0)break;let t=e.kind===`enum`?e.options??[]:n.includes(o)||o===``?n:[o,...n];return(0,Q.jsxs)(tn,{...s,size:`sm`,className:`w-full`,value:o,onChange:c,children:[(0,Q.jsx)(Jt,{value:``,disabled:e.required,children:e.required?`Choose…`:`(none)`}),t.map((t,n)=>(0,Q.jsx)(Jt,{value:e.kind===`enum`?String(n):String(t),children:String(t)},String(t)))]})}case`date`:if(o===``||QC.test(o))return(0,Q.jsx)(Wt,{...s,type:`date`,className:`h-7`,value:o,onChange:c})}return(0,Q.jsx)(Wt,{...s,type:`text`,autoComplete:`off`,inputMode:e.kind===`number`||e.kind===`integer`?`decimal`:void 0,className:`h-7`,value:o,onChange:c})}var ow=(e,t)=>Array.from({length:Math.max(0,t-e+1)},(t,n)=>e+n);function sw({table:e,fields:t,keyField:n,changeOfKey:r,stage:i}){let a=e.getRowModel().rows,o=e.getVisibleLeafColumns(),s=e.getFocusedCell(),c=(e,i)=>t.has(i)&&(i!==n||Tv(e.key))&&r.get(e.key)?.type!==`delete`,l=(e,n,r)=>{let i=t.get(n);if(!i||!c(e,n))return[];let a=rw(i,r);return`error`in a?[{key:e.key,field:n,value:r,error:a.error}]:a.value===e.record[n]?[]:[{key:e.key,field:n,value:a.value}]},u=()=>e.getCellSelectionBounds().flatMap(e=>ow(e.minRowIndex,e.maxRowIndex).flatMap(t=>ow(e.minColumnIndex,e.maxColumnIndex).flatMap(e=>{let n=a[t]?.original,r=o[e]?.id;return n&&r?[{saved:n,id:r}]:[]}))),d=t=>{let n=hn(t,` `);if(!s||n.length===0)return;let[r]=n.length===1&&n[0].length===1?n[0]:[];if(r!==void 0&&e.getSelectedCellCount()>1){let e=u().flatMap(({saved:e,id:t})=>l(e,t,r));return i({what:`paste`,said:`Pasted into ${G(e.length,`cell`)}`,cells:e})}let c=s.row.getDisplayIndex(),d=o.findIndex(e=>e.id===s.column.id),f=Math.min(Math.max(...n.map(e=>e.length)),o.length-d),p=n.map((e,t)=>{let n=a[c+t]?.original;return{line:e,added:!n,saved:n??{key:wv(),record:{},updatedAt:``,updatedBy:``}}}),m=p.flatMap(({added:e,saved:t})=>e?[t.key]:[]);!i({what:`paste`,said:`Pasted ${G(n.length,`row`)} × ${G(f,`column`)} at row ${c+1}, ${s.column.id}`,adds:m,cells:p.flatMap(({line:e,saved:t})=>e.slice(0,f).flatMap((e,n)=>l(t,o[d+n].id,e)))})&&m.length>0||e.selectCellRange({anchorRowId:s.row.id,anchorColumnId:s.column.id,focusRowId:p.at(-1).saved.key,focusColumnId:o[d+f-1].id})},f=e.getCellSelectionBounds(),p=f.length===1?f[0]:void 0,[m,h]=(0,K.useState)(),g=t=>{if(!p||t<=p.maxRowIndex)return;let n=p.maxRowIndex-p.minRowIndex+1,r=ow(p.maxRowIndex+1,t).flatMap(e=>ow(p.minColumnIndex,p.maxColumnIndex).flatMap(t=>{let r=o[t].id,i=a[p.minRowIndex+(e-p.maxRowIndex-1)%n].original;return l(a[e].original,r,_n(i.record[r]))}));i({what:`fill`,said:`Filled ${G(t-p.maxRowIndex,`row`)} down from row ${p.maxRowIndex+1}`,cells:r}),e.selectCellRange({anchorRowId:a[p.minRowIndex].id,anchorColumnId:o[p.minColumnIndex].id,focusRowId:a[t].id,focusColumnId:o[p.maxColumnIndex].id})};return(0,K.useEffect)(()=>{if(m===void 0)return;let e=()=>{h(void 0),g(m)};return document.addEventListener(`mouseup`,e,{once:!0}),()=>document.removeEventListener(`mouseup`,e)}),{changeable:c,changeOf:l,selectedCells:u,paste:d,fillFrom:p,fillTo:m,setFillTo:h,clear:()=>{let e=u(),t=new Set(e.flatMap(({saved:e,id:t})=>t===n&&r.get(e.key)?.type!==`delete`?[e.key]:[])),a=e.flatMap(({saved:e,id:n})=>t.has(e.key)?[]:l(e,n,``));i({what:`delete`,said:t.size?`Deleted ${G(t.size,`record`)}`:`Cleared ${G(a.length,`cell`)}`,cells:a,deletes:[...t]})},addRecord:()=>{let t=wv();i({what:`new record`,said:`Added a record`,adds:[t]})&&e.setFocusedCell(t,n)}}}var cw=[`Control`,`Alt`,`Shift`,`Meta`],lw={Control:`Control`,Ctrl:`Control`,control:`Control`,ctrl:`Control`,Shift:`Shift`,shift:`Shift`,Alt:`Alt`,Option:`Alt`,alt:`Alt`,option:`Alt`,Command:`Meta`,Cmd:`Meta`,Meta:`Meta`,command:`Meta`,cmd:`Meta`,meta:`Meta`,OS:`Meta`,os:`Meta`,Win:`Meta`,win:`Meta`,CommandOrControl:`Mod`,Mod:`Mod`,commandorcontrol:`Mod`,mod:`Mod`};Array.from({length:24},(e,t)=>`F${t+1}`);var uw={Backquote:"`",Backslash:`\\`,BracketLeft:`[`,BracketRight:`]`,Comma:`,`,Equal:`=`,Minus:`-`,Period:`.`,Quote:`'`,Semicolon:`;`,Slash:`/`};function dw(e){return/^\p{Letter}$/u.test(e)}function fw(e){if(!e)return``;if(dw(e)){let t=e.toUpperCase();return t.length===1?t:e}return e===` `?`Space`:e}var pw=/^(?:Node\.js\/|Deno\/|Bun\/|Cloudflare-Workers)/;function mw(){return typeof navigator>`u`||pw.test(String(navigator.userAgent))}function hw(e){let t=``,n=e;if(n==null){if(mw())return`linux`;t=navigator.platform?.toLowerCase()??``,n=navigator.userAgent??``}return n=n.toLowerCase(),t.includes(`mac`)||n.includes(`mac`)?`mac`:t.includes(`win`)||n.includes(`win`)?`windows`:`linux`}function gw(e,t=hw()){return e===`Mod`?t===`mac`?`Meta`:`Control`:e}function _w(e,t){let n=!1;try{n=t!==`mac`&&typeof e.getModifierState==`function`&&e.getModifierState(`AltGraph`)}catch{}let r=(e.key||``).normalize(`NFC`),i=fw(r),a=t===`windows`&&n&&!yw({key:i,altGraph:n});return{key:i,code:e.code||``,ctrl:a||!!e.ctrlKey,shift:!!e.shiftKey,alt:a||!!e.altKey,meta:!!e.metaKey,altGraph:n&&!a,location:e.location,isComposing:!!e.isComposing||e.keyCode===229||r===`Process`||r===`Unidentified`}}function vw(e){if(/^Key[A-Z]$/i.test(e))return e.slice(3).toUpperCase();if(/^Digit[0-9]$/i.test(e))return e.slice(5);if(/^Numpad[0-9]$/i.test(e))return e.slice(6);if(Object.hasOwn(uw,e))return uw[e];let t={NumpadAdd:`+`,NumpadSubtract:`-`,NumpadMultiply:`*`,NumpadDivide:`/`,NumpadDecimal:`.`,NumpadEnter:`Enter`,Space:`Space`};return Object.hasOwn(t,e)?t[e]:void 0}function yw(e){return e.altGraph?e.key===`Dead`||bw(e.key)&&!/^[A-Za-z0-9]$/.test(e.key):!1}function bw(e){return e!==``&&Array.from(e).length===1}function xw(e){let t=e.toLowerCase();return Object.hasOwn(lw,t)?lw[t]:void 0}function Sw(e){return/^[A-Za-z][A-Za-z0-9]*$/.test(e)}function Cw(e){return e.startsWith(`[`)&&e.endsWith(`]`)&&Sw(e.slice(1,-1))?e.slice(1,-1):void 0}function ww(e){if(!e.endsWith(`+`))return e.split(`+`);let t=e.slice(0,-1).split(`+`);return t.at(-1)===``&&t.pop(),t.push(`+`),t}function Tw(e){return/^[A-Za-z]$/.test(e)}function Ew(e){return/^\p{Script_Extensions=Latin}$/u.test(e)}var Dw;function Ow(e,t){return e===t?!0:/^\p{Letter}$/u.test(e)&&/^\p{Letter}$/u.test(t)?(Dw??=new Intl.Collator(void 0,{sensitivity:`accent`}),Dw.compare(e,t)===0):!1}function kw(e){if(/^\[.*\]$/s.test(e.trim()))throw Error(`Logical key must not contain a bracketed physical code. Use the code field instead.`)}function Aw(e,t,n,r,i){let a={Control:t,Alt:r,Shift:n,Meta:i};return{...e,ctrl:t,shift:n,alt:r,meta:i,modifiers:cw.filter(e=>a[e])}}function jw(e){return Array.isArray(e)}function Mw(e){return jw(e)&&e.length===1?e[0]:e}function Nw(e,t){let n=ww(e),r=new Set,i=``;for(let e=0;e<n.length;e++){let a=n[e].trim();if(e===n.length-1)i=fw(a);else{let e=xw(a);if(e){let n=gw(e,t);r.add(n)}else n.length===1&&(i=fw(a))}}!i&&n.length>0&&(i=fw(n[n.length-1].trim()));let a=Cw(i);return Aw(a===void 0?{key:i}:{code:a},r.has(`Control`),r.has(`Shift`),r.has(`Alt`),r.has(`Meta`))}function Pw(e,t){e.code===void 0&&kw(e.key);let n=e.ctrl??!1,r=e.shift??!1,i=e.alt??!1,a=e.meta??!1;return e.mod&&(gw(`Mod`,t)===`Control`?n=!0:a=!0),Aw(e.code===void 0?{key:fw(e.key)}:{code:e.code},n,r,i,a)}function Fw(e,t){return typeof e==`string`?Nw(e,t):Pw(e,t)}function Iw(e,t){e.code===void 0&&kw(e.key);let n=t===`mac`?e.meta&&!e.ctrl:e.ctrl&&!e.meta,r=[];if(n)r.push(`Mod`),e.alt&&r.push(`Alt`),e.shift&&r.push(`Shift`);else for(let t of cw)e.modifiers.includes(t)&&r.push(t);return r.push(e.code===void 0?fw(e.key):`[${e.code}]`),r.join(`+`)}function Lw(e,t=hw()){return Array.isArray(e)?e.map(e=>Fw(e,t)):Fw(e,t)}function Rw(e,t=hw()){if(Array.isArray(e)){let n=e.map(e=>Iw(Fw(e,t),t));return n.length===1?n[0]:n}return Iw(Fw(e,t),t)}function zw(e){return xw(e)!==void 0}function Bw(e){return Array.isArray(e)?e.map(e=>Vw(e)):Vw(e)}function Vw(e){e.code===void 0&&kw(e.key);let t=[];for(let n of cw)e.modifiers.includes(n)&&t.push(n);return t.push(e.code===void 0?e.key:`[${e.code}]`),t.join(`+`)}function Hw(e,t,n=hw()){let r=typeof t==`string`?Lw(t,n):t,i=_w(e,n),a={matched:!1,score:0};if(i.isComposing||i.altGraph&&(r.ctrl||r.alt)||i.altGraph&&!yw(i))return a;if(r.code!==void 0)return i.altGraph||!Ww(i,r,!1)?a:i.code===r.code?l(`code`,3):a;let o=Ow(i.key,r.key),s=o&&bw(i.key)&&!/^\p{Letter}$/u.test(i.key)&&!r.shift;if(o&&Ww(i,r,s))return l(`key`,s?2:3);if(!Uw(i)||i.altGraph||!Ww(i,r,!1))return a;let c=vw(i.code);return c!==void 0&&Ow(c,r.key)?l(`fallback`,1):a;function l(e,t){return{matched:!0,score:t,source:e,identity:{key:i.key,code:i.code}}}}function Uw({key:e,code:t,ctrl:n,meta:r,shift:i,alt:a}){return e!==`Dead`&&!bw(e)?!1:t.startsWith(`Digit`)?!0:Tw(e)?!1:/^[!-~]$/.test(e)?i:!Ew(e)||a?!0:(n||r)&&!t.startsWith(`Key`)}function Ww(e,t,n){let r=!e.altGraph&&e.ctrl,i=!e.altGraph&&e.alt;return r!==t.ctrl||i!==t.alt||e.meta!==t.meta?!1:e.shift===t.shift||n&&e.shift}function Gw(e,t){return e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift&&e.meta===t.meta&&(e.code!==void 0||t.code!==void 0?e.code===t.code:Ow(e.key,t.key))}var Kw=`global`,qw={capture:!1,preventDefault:!0,stopPropagation:!0,eventType:`keydown`,enabled:!0,ignoreInputs:`auto`,conflictBehavior:`warn`,scope:Kw};function Jw(...e){let t={};for(let n of e)if(n)for(let e of Object.keys(n)){let r=n[e];r!==void 0&&(t[e]=r)}return t}function Yw(e){return!!(e.code||e.key)}function Xw(e){return!(e.ctrl||e.meta||e.key===`Escape`||e.code===`Escape`)}function Zw(e,t,n,r){if(n!==`allow`&&n!==`warn`){if(n===`error`)throw Error(`'${t}' is already registered. Use conflictBehavior: 'replace' to replace the existing handler, or conflictBehavior: 'allow' to allow multiple registrations.`);r(e)}}function Qw(e,t){let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>e===`meta`&&n[e]&&r[e]?Qw(n[e],r[e]):Object.is(n[e],r[e]))}function $w(e,t,n=hw()){let r=jw(e)?e:[e],i=jw(t)?t:[t];return r.length===i.length&&r.every((e,t)=>Gw(Lw(e,n),Lw(i[t],n)))}var eT=1e3;function tT(e){return e?.nodeType===1}function nT(e){return`document`in e||e.nodeType===9}function rT(e){return`document`in e?e.document:e.ownerDocument??e}function iT(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function aT(e){return e.assignedSlot??e.parentNode??(e.host||null)}function oT(e){if(nT(e))return!0;for(let t=iT(e.ownerDocument);t;t=aT(t))if(t===e)return!0;return!1}var sT=[`ArrowUp`,`ArrowDown`],cT=[`ArrowLeft`,`ArrowRight`],lT=[`Enter`],uT=[`Space`],dT=[`Enter`,`Space`],fT=`typeahead`,pT=[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Home`,`End`,`Enter`,`Space`,fT],mT=[`ArrowUp`,`ArrowDown`,`Home`,`End`,`Enter`,`Space`,fT],hT=[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Home`,`End`,`PageUp`,`PageDown`,`Enter`,`Space`],gT=[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Space`],_T=[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Home`,`End`,`PageUp`,`PageDown`],vT=[`ArrowUp`,`ArrowDown`,`Home`,`End`,`PageUp`,`PageDown`],yT=[`ArrowLeft`,`ArrowRight`,`Home`,`End`],bT={button:dT,submit:dT,reset:dT,image:dT,color:dT,file:dT,checkbox:uT,radio:gT,range:_T};function xT(e){return e.getAttribute(`role`)?.trim().split(/\s+/)[0]}function ST(e){if(!tT(e))return!1;switch(e.localName){case`input`:{let t=e;return!bT[t.type]&&!t.readOnly}case`textarea`:return!e.readOnly;case`select`:return!0}let t=xT(e);return t===`textbox`||t===`searchbox`||e.isContentEditable}function CT(e){return e.localName.includes(`-`)?e.constructor.formAssociated===!0?!e.hasAttribute(`role`):!e.hasAttribute(`tabindex`):!1}function wT(e){let t=e.getAttribute(`aria-orientation`);switch(xT(e)){case`button`:case`tab`:case`option`:case`treeitem`:case`menuitem`:case`menuitemcheckbox`:case`menuitemradio`:return dT;case`link`:return lT;case`checkbox`:case`switch`:case`radio`:return uT;case`menu`:case`menubar`:case`tree`:return pT;case`listbox`:return[...t===`horizontal`?cT:sT,`Home`,`End`,`Enter`,`Space`,fT];case`combobox`:return mT;case`tablist`:return[...t===`vertical`?sT:cT,`Home`,`End`,`Enter`,`Space`];case`toolbar`:return[...t===`vertical`?sT:cT,`Home`,`End`];case`grid`:case`treegrid`:return hT;case`radiogroup`:return gT;case`slider`:return _T;case`spinbutton`:return vT}switch(e.localName){case`button`:case`summary`:return dT;case`input`:return bT[e.type]??yT;case`textarea`:return _T;case`a`:case`area`:return e.hasAttribute(`href`)?lT:[]}return[]}function TT(e,t,n){if(t.ctrlKey||t.metaKey||t.altKey)return!1;let r=wT(e);return n===`Enter`||n===`Space`?!t.shiftKey&&r.includes(n):r.includes(n)||r.includes(fT)&&/^.$/u.test(t.key)}function ET(e,t,n){let r=iT(t),i=[];for(let e=r;e;e=aT(e))tT(e)&&i.push(e);let a=e.composedPath()[0];tT(a)&&!i.includes(a)&&(i=e.composedPath().filter(tT));let o=i.findIndex(e=>n(e)||e===r&&CT(e));return{elements:i,index:o}}function DT({elements:e,index:t},n){return t>=0&&(nT(n)||t<e.indexOf(n))}var OT=new WeakMap;function kT(e,t){if(e.type!==`keydown`||e.key!==`Escape`)return!1;let n=OT.get(e);if(!n){let r=[];for(let e of[`dialog:modal`,`:popover-open`])try{r.push(...rT(t).querySelectorAll(e))}catch{}n=r.filter(e=>e.popover!==`manual`),OT.set(e,n)}return n.some(e=>{for(let n=nT(t)?null:t;n;n=aT(n))if(n===e)return!1;return!0})}var AT=new WeakMap;function jT(e,t){let n=AT.get(e);if(!n){let r=fw(e.key);n=ET(e,rT(t),t=>ST(t)||TT(t,e,r)),AT.set(e,n)}return DT(n,t)}var MT=new Set;function NT(e){for(let t of e)MT.add(t);for(let e of MT)MT.delete(e),e()}function PT(e){let t=e,n=new Set;return{get state(){return t},get:()=>t,setState(e){let r=e(t);Object.is(t,r)||(t=r,NT(n))},subscribe(e){let r=()=>{typeof e==`function`?e(t):e.next?.(t)};return n.add(r),{unsubscribe(){n.delete(r),MT.delete(r)}}}}}var FT=class{dispatch;#e=new Map;#t=new WeakMap;constructor(e){this.dispatch=e}add(e,t,n,r=!1){if(typeof document>`u`)return;let i=this.#e.get(e)??new Map,a=i.get(t);if(a&&r)for(let n of[`keydown`,`keyup`])e.removeEventListener(n,a[n],t),e.addEventListener(n,a[n],t);if(!a){let n=new Set,r=r=>i=>{let a=i,o=this.#t.get(a),s=!o||o.groups.has(n);(!o||s)&&(o={ids:new Set,groups:new Set},this.#t.set(a,o)),o.groups.add(n);let c=new Set;for(let e of n)o.ids.has(e)||(o.ids.add(e),c.add(e));this.dispatch(a,e,r,t,c,s)};a={ids:n,keydown:r(`keydown`),keyup:r(`keyup`)},e.addEventListener(`keydown`,a.keydown,t),e.addEventListener(`keyup`,a.keyup,t),i.set(t,a),this.#e.set(e,i)}a.ids.add(n)}remove(e,t,n){let r=this.#e.get(e),i=r?.get(t);i&&(i.ids.delete(n),i.ids.size===0&&(e.removeEventListener(`keydown`,i.keydown,t),e.removeEventListener(`keyup`,i.keyup,t),r.delete(t),r.size===0&&this.#e.delete(e)))}destroy(){for(let[e,t]of this.#e)for(let[n,r]of t)e.removeEventListener(`keydown`,r.keydown,n),e.removeEventListener(`keyup`,r.keyup,n);this.#e.clear(),this.#t=new WeakMap}},IT={current:null},LT=new Set,RT=new WeakSet,zT=new Map,BT=e=>e.code||`key:${e.key}`;function VT(e){return LT.size>0||RT.has(e)||zT.has(BT(e))}function HT(e,t){return e.enabled===!1?`disabled`:t?.isScopeActive(e.scope)===!1?`suspended`:`active`}var UT=0;function WT(e,t){return typeof e==`string`?e:Bw(t)}function GT(){return`hotkey_${++UT}`}function KT(e){let t=e;return{id:GT(),unregister:()=>{},get callback(){return t},set callback(e){t=e},setOptions:()=>{},get isActive(){return!1}}}function qT(e){return{...qw,...e===`sequence`?{timeout:eT}:{requireReset:!1}}}function JT(e,t){if(e===`chord`){let{timeout:e,...n}=t;return n}let{requireReset:n,...r}=t;return r}function YT({target:e,options:t}){if(!t.afterDelegatedHandlers||t.capture||nT(e))return e;let n=e.getRootNode();for(;`host`in n&&n.mode===`open`;)n=n.host.getRootNode();return n}function XT(e){return!!e.afterDelegatedHandlers&&!e.capture}function ZT(e){return e.kind===`chord`?[e.parsedChord]:e.parsedSequence}function QT(e){let{ignoreInputs:t=`auto`}=e.options;return t===`auto`?Xw(ZT(e)[0]):t}function $T(e,t){return e.length===t.length&&e.every((e,n)=>Gw(e,t[n]))}function eE(e){return jw(e)?e.join(` `):e}var tE=class e{registrations=PT(new Map);appHotkeys=PT(null);scopes=PT({active:[],exclusive:null,allowed:[],suspended:[]});#e;#t=new Set;#n=0;#r=[];#i=null;#a=new FT((...e)=>this.#S(...e));#o=new Map;#s=new WeakMap;#c=new Map;#l=new WeakSet;#u=new Set;#d=new Map;constructor(){this.#e=hw()}static getInstance(){return IT.current??=new e}static resetInstance(){IT.current?.destroy(),IT.current=null}activateScope(e,t={}){if(e===`global`)return()=>{};let{exclusive:n}=t,r=n?n===!0?[]:n.allow:null,i={scope:e,parent:t.parent??`global`,allow:r,order:++this.#n};return this.#t.add(i),this.#p(),()=>{this.#t.delete(i)&&this.#p()}}isScopeActive(e=Kw){return this.#i?this.#i.has(e):e===`global`||this.#r.includes(e)}#f(e=Kw){return this.#r.indexOf(e)+1}#p(){let e=new Map,t=new Map;for(let n of this.#t)n.parent!==n.scope&&e.set(n.scope,n.parent),t.set(n.scope,Math.max(t.get(n.scope)??0,n.order));let n=t=>{let n=0,r=new Set;for(let i=e.get(t);i!==void 0&&!r.has(i);i=e.get(i))r.add(i),n++;return n},r=new Map;for(let[n,i]of t){let a=new Set;for(let o=n;o!==void 0&&!a.has(o);o=e.get(o)){a.add(o);let e=t.get(o);e!==void 0&&r.set(o,Math.min(r.get(o)??e,i))}}let i=(e,i)=>r.get(e)-r.get(i)||n(e)-n(i)||t.get(e)-t.get(i);this.#r=[...t.keys()].sort(i);let a=[...this.#t].filter(e=>e.allow).sort((e,t)=>i(e.scope,t.scope)||e.order-t.order).pop(),o=[Kw,...this.#r],s=[];if(this.#i=null,a?.allow){let{allow:t}=a,n=t=>{let n=new Set;for(let r=t;r!==void 0&&!n.has(r);r=e.get(r)){if(r===a.scope)return!0;n.add(r)}return!1};s=o.filter(e=>!n(e)&&t.includes(e)),this.#i=new Set([...o.filter(n),...s])}let c=this.#i;this.scopes.setState(()=>({active:this.#r,exclusive:a?.scope??null,allowed:s,suspended:c?o.filter(e=>!c.has(e)):[]})),this.#g()}#m(e){return HT(e.options,this)===`active`}#h(e,t){let n=e.composedPath();for(let r of this.registrations.state.values())if(!(!this.#m(r)||r.options.eventType!==t||this.#k(r,e)||!n.includes(r.target)||QT(r)&&jT(e,r.target))&&(r.kind===`chord`?[r.parsedChord]:[r.parsedSequence[r.currentIndex],r.parsedSequence[0]]).some(t=>Hw(e,t,r.options.platform).matched))return!0;return!1}#g(){this.registrations.setState(e=>new Map(e))}register(e,t,n={}){let r=Mw(e);if(r==null||jw(r)&&r.length===0||typeof document>`u`&&!n.target)return KT(t);let i=GT(),a=n.platform??this.#e,o=n.target??document,s=jw(r),c=s?`sequence`:`chord`,l={id:i,callback:t,options:{...qT(c),...JT(c,Jw(n)),platform:a},target:o,triggerCount:0,hasFired:!1},u;if(s){let e=Lw(r,a);u={...l,kind:`sequence`,hotkey:r.map((t,n)=>WT(t,e[n])),parsedSequence:e,currentIndex:0,lastKeyTime:0}}else{let e=Lw(r,a);u={...l,kind:`chord`,hotkey:WT(r,e),parsedChord:e}}if(!(u.kind===`sequence`?u.parsedSequence:[u.parsedChord]).every(Yw))return KT(t);let d=this.#N(u);d&&Zw(d.id,eE(u.hotkey),n.conflictBehavior??`warn`,e=>this.#_(e));let f=YT(u);this.#a.add(f,!!u.options.capture,i,XT(u.options)),this.#o.set(i,f),this.registrations.setState(e=>new Map(e).set(i,u));let p=this;return{get id(){return i},unregister:()=>{p.#_(i)},get callback(){return p.registrations.state.get(i)?.callback??t},set callback(e){let t=p.registrations.state.get(i);t&&(t.callback=e)},setOptions:e=>{p.registrations.setState(t=>{let n=t.get(i);if(!n)return t;let r={...qT(n.kind),platform:n.options.platform},a={...n.options},o=Object.entries(JT(n.kind,e));for(let[e,t]of o)t===void 0?e in r?a[e]=r[e]:delete a[e]:a[e]=t;if(Qw(n.options,a))return t;let s=!!n.options.capture,c=p.#o.get(i)??n.target,l=YT({target:n.target,options:a});return s!==!!a.capture||c!==l?(p.#a.remove(c,s,i),p.#a.add(l,!!a.capture,i,XT(a)),p.#o.set(i,l)):XT(a)&&!XT(n.options)&&p.#a.add(l,s,i,!0),new Map(t).set(i,{...n,options:a})})},get isActive(){return p.registrations.state.has(i)}}}#_(e){let t=this.registrations.state.get(e);t&&(this.registrations.setState(t=>{let n=new Map(t);return n.delete(e),n}),this.#a.remove(this.#o.get(e)??t.target,!!t.options.capture,e),this.#o.delete(e),this.#c.delete(e),this.#y(e))}#v(e,t){this.#y(e),this.#d.set(e,setTimeout(()=>{this.#d.delete(e);let t=this.registrations.state.get(e);if(t?.kind!==`sequence`||t.currentIndex===0)return;let n=t.options.timeout??1e3,r=t.lastKeyTime+n-Date.now();r>=0?this.#v(e,r+1):(t.currentIndex=0,t.lastKeyTime=0,this.#g())},t))}#y(e){let t=this.#d.get(e);t!==void 0&&(clearTimeout(t),this.#d.delete(e))}#b(e,t,n){let r=[];for(let i of e){let e=this.registrations.state.get(i);e?.kind===n&&!!e.options.capture===t&&r.push(e)}return r}#x(e,t){let n=this.registrations.state.get(e.id);return n&&!!n.options.capture===t?n:void 0}#S(e,t,n,r,i,a){if(a&&this.#s.set(e,this.#T(e,n)),r){this.#C(e,t,n,r,i);return}let o=new Map;for(let e of i){let t=this.registrations.state.get(e);if(!t)continue;let n=o.get(t.target)??new Set;o.set(t.target,n.add(e))}let s=o.size>1||!o.has(t)?e.composedPath():[],c=[...o.keys()].filter(e=>e===t||s.includes(e)).sort((e,n)=>e===t?1:n===t?-1:s.indexOf(e)-s.indexOf(n)),l=e.cancelBubble;for(let t of c){let i=new Set;for(let n of o.get(t)){let t=this.registrations.state.get(n)?.options.afterDelegatedHandlers;(!e.cancelBubble||!t&&l)&&i.add(n)}this.#C(e,t,n,r,i)}}#C(e,t,n,r,i){this.#w(e,t,n,r,this.#b(i,r,`chord`)),this.#D(e,t,n,r,this.#b(i,r,`sequence`))}#w(e,t,n,r,i){if(n===`keyup`)for(let t of i)t.hasFired&&this.#P(t,e)&&(t.hasFired=!1,t.activeMatch=void 0);if(n===`keydown`&&!e.repeat)for(let{id:e}of i)this.#c.get(e)&&this.#c.set(e,null);if(VT(e)||this.#s.get(e))return;let a=new Map,o=0,s=!1,c=fw(e.key);for(let r of i){let i=this.#m(r),{eventType:l,preventDefault:u}=r.options,d=n===`keydown`&&l===`keyup`,f=this.#k(r,e),{parsedChord:p,id:m}=r,{platform:h}=r.options,g,_;if(n===`keyup`&&l===`keyup`&&this.#c.has(m)&&(g=Hw(e,p,h),(g.matched||p.modifiers.includes(c)&&!e.getModifierState(c))&&(_=this.#c.get(m),this.#c.delete(m))),!(!i&&u!==`always`||l!==n&&!d||QT(r)&&jT(e,t))){if(g??=Hw(e,p,h),d)g.matched&&(f?this.#c.set(m,null):(u&&this.#O(e),i&&this.#c.set(m,g)));else{if(_!==void 0){if(!_||f)continue;g.matched||(g=_)}!f&&g.matched&&(i?(a.set(r.id,g),o=Math.max(o,g.score)):s=!0)}}}s&&a.size===0&&!this.#h(e,n)&&this.#O(e);let l=-1;for(let e of i)a.get(e.id)?.score===o&&(l=Math.max(l,this.#f(e.options.scope)));for(let t of i){let i=a.get(t.id);if(!i?.matched||i.score!==o||this.#f(t.options.scope)!==l)continue;let s=this.#x(t,r);s&&(this.#A(s,e),n===`keyup`?this.#j(s,e):s.options.requireReset&&s.hasFired&&e.repeat||(s.options.requireReset&&(s.hasFired=!0,s.activeMatch=i.identity),this.#j(s,e)))}}#T(e,t){let n=e.code||fw(e.key);if(t===`keyup`){let r=this.#u.delete(n);return this.#E(e,t)||r}if(e.repeat)return this.#u.has(n);let r=this.#E(e,t);return r?this.#u.add(n):this.#u.delete(n),r}#E(e,t){if(VT(e)||_w(e).isComposing||zw(fw(e.key)))return!1;let n=e.composedPath(),r=Date.now();for(let i of this.registrations.state.values()){if(i.kind!==`sequence`||i.currentIndex===0||!this.#m(i)||i.options.eventType!==t||this.#k(i,e)||r-i.lastKeyTime>(i.options.timeout??1e3))continue;let a=i.target;if(n.includes(nT(a)?rT(a):a)&&!(QT(i)&&jT(e,a))&&Hw(e,i.parsedSequence[i.currentIndex],i.options.platform).matched)return!0}return!1}#D(e,t,n,r,i){if(i.length===0)return;if(VT(e)){let e=!1;for(let t of i)t.currentIndex>0&&(t.currentIndex=0,this.#y(t.id),e=!0);e&&this.#g();return}if(e.type===`keydown`&&e.repeat||_w(e).isComposing||zw(fw(e.key)))return;let a=Date.now(),o=!1,s=new Map,c=0;for(let r of i){if(!this.#m(r)||QT(r)&&jT(e,t)||r.options.eventType!==n||this.#k(r,e))continue;let i=r.options.timeout??1e3;r.currentIndex>0&&a-r.lastKeyTime>i&&(r.currentIndex=0,o=!0);let l=r.parsedSequence[r.currentIndex];if(!l)continue;let u=Hw(e,l,r.options.platform),d=r.currentIndex+1;!u.matched&&r.currentIndex>0&&(u=Hw(e,r.parsedSequence[0],r.options.platform),d=1),s.set(r.id,{score:u.score,nextIndex:d}),c=Math.max(c,u.score)}let l=[];for(let t of i){let n=s.get(t.id);n&&(n.score>0&&n.score===c?(t.lastKeyTime=a,t.currentIndex=n.nextIndex,o=!0,t.currentIndex>=t.parsedSequence.length?(this.#A(t,e),t.currentIndex=0,l.push(t)):t.options.preventDefault&&this.#O(e)):t.currentIndex>0&&(t.currentIndex=0,o=!0))}for(let e of i)if(s.has(e.id)){if(e.currentIndex>0){let t=e.options.timeout??1e3;this.#v(e.id,t+1)}else this.#y(e.id)}o&&l.length===0&&this.#g();for(let t of l){let n=this.#x(t,r);n&&this.#j(n,e)}}#O(e){e.defaultPrevented||this.#l.add(e),e.preventDefault()}#k(e,t){return kT(t,e.target)||!!e.options.ignoreDefaultPrevented&&t.defaultPrevented&&!this.#l.has(t)}#A(e,t){e.options.preventDefault&&this.#O(t),e.options.stopPropagation&&t.stopPropagation()}#j(e,t,n=this.#M(e)){e.triggerCount++,e.kind===`sequence`&&(e.hasFired=!0),this.#g();let r=t.defaultPrevented;e.callback(t,n),!r&&t.defaultPrevented&&this.#l.add(t)}#M(e){return e.kind===`chord`?{kind:`chord`,hotkey:e.hotkey,parsedChord:e.parsedChord}:{kind:`sequence`,hotkey:e.hotkey,parsedSequence:e.parsedSequence}}#N(e){let t=ZT(e);for(let n of this.registrations.state.values())if(n.target===e.target&&n.options.scope===e.options.scope&&n.options.eventType===e.options.eventType&&$T(ZT(n),t))return n;return null}#P(e,t){let n=e.parsedChord,r=fw(t.key);return e.activeMatch?.code&&t.code===e.activeMatch.code?!0:(n.code===void 0?Ow(r,n.key):t.code===n.code)||n.modifiers.includes(r)}resetSequenceProgress(){for(let e of this.registrations.state.values())e.kind===`sequence`&&(e.currentIndex=0,e.lastKeyTime=0);for(let e of this.#d.values())clearTimeout(e);this.#d.clear(),this.#g()}getRegistrationCount(){return this.registrations.state.size}isRegistered(e,t){for(let n of this.registrations.state.values())if($w(n.hotkey,e,n.options.platform)&&(t===void 0||n.target===t))return!0;return!1}hasActiveRegistration(e){if(!e)return!1;let t=typeof e==`object`&&`~appHotkey`in e?e.id:void 0;for(let n of this.registrations.state.values())if(this.#m(n)&&oT(n.target)&&(t===void 0?$w(n.hotkey,e,n.options.platform):n.options.appHotkeyId===t))return!0;return!1}destroy(){for(let e of this.#d.values())clearTimeout(e);this.#d.clear(),this.#a.destroy(),this.#o.clear(),this.registrations.setState(()=>new Map),this.appHotkeys.setState(()=>null)}};function nE(){return tE.getInstance()}function rE(e){return typeof e==`object`&&!!e&&e[`~appHotkey`]===!0}function iE(e,t){return t?.get(e.id)??e}function aE(e){return{...e.options,...e.scope!==void 0&&{scope:e.scope},meta:e.meta,appHotkeyId:e.id}}function oE(e={}){let t=new Map;return{update(n,r={}){let i=[];n.forEach((t,n)=>{let a=Jw(r,t.options),o={...qw,...a,...e,target:`target`in a?a.target??null:typeof document>`u`?null:document,platform:a.platform??hw()};if(!o.target||!t.hotkey||jw(t.hotkey)&&t.hotkey.length===0)return;let s=Lw(t.hotkey,o.platform);if(!(Array.isArray(s)?s:[s]).every(Yw))return;let c=Rw(s,o.platform);jw(c)?delete o.requireReset:delete o.timeout,i.push({key:`${n}:${jw(c)?c.join(` `):c}`,callback:t.callback,options:o,register:()=>nE().register(c,t.callback,o)})});let a=new Set(i.map(e=>e.key));for(let[e,n]of t)a.has(e)||(n.handle.unregister(),t.delete(e));for(let e of i){let n=t.get(e.key),{target:r,platform:i}=e.options;if(n?.handle.isActive&&n.target===r&&n.platform===i){n.handle.callback=e.callback;let t=Object.fromEntries(Object.keys(n.options).map(e=>[e,void 0]));n.handle.setOptions({...t,...e.options}),n.options=e.options}else n?.handle.unregister(),t.set(e.key,{handle:e.register(),target:r,platform:i,options:e.options})}},destroy(){for(let{handle:e}of t.values())e.unregister();t.clear()}}}function sE(e,t={}){return e.map(e=>{let n=e.hotkey,r={};if(rE(n)){let e=iE(n,t.appHotkeysStore);r=aE(e),n=e.hotkey??[]}let{target:i,...a}=Jw(t.defaults,r,t.commonOptions,e.options),o=i===void 0?void 0:t.resolveTarget?t.resolveTarget(i):i;return{hotkey:n,callback:e.callback,options:o===void 0?a:{...a,target:o}}})}var cE=(0,K.createContext)(null);function lE(){return(0,K.useContext)(cE)}function uE(e,t){let n=(0,K.useCallback)(t=>e.subscribe(t).unsubscribe,[e]),r=(0,K.useRef)(null),i=()=>{let n=e.get(),i=r.current;return i&&i.selector===t&&Object.is(i.state,n)?i.selected:(r.current={state:n,selector:t,selected:t(n)},r.current.selected)};return(0,K.useSyncExternalStore)(n,i,i)}var dE=PT(null);function fE(){let e=lE()?.appHotkeysStore??null;return uE(e?.store??dE,e=>e),e}function pE(e){return typeof e==`object`&&!!e&&`current`in e}function mE(e){return pE(e)?e.current:e}function hE(e,t={}){let n=lE()?.defaultOptions.hotkey,r=fE(),i=(0,K.useRef)({hotkeys:e,commonOptions:t,defaults:n,appHotkeysStore:r});i.current={hotkeys:e,commonOptions:t,defaults:n,appHotkeysStore:r};let a=(0,K.useRef)(null);(0,K.useEffect)(()=>{a.current??=oE({afterDelegatedHandlers:!0});let{hotkeys:e,...t}=i.current;a.current.update(sE(e,{...t,resolveTarget:mE}))}),(0,K.useEffect)(()=>()=>{a.current?.destroy(),a.current=null},[])}var gE=[[`ArrowUp`,`up`],[`ArrowDown`,`down`],[`ArrowLeft`,`left`],[`ArrowRight`,`right`]],_E=[[`Tab`,`right`],[`Shift+Tab`,`left`]];function vE(e,t){let n={enabled:!t.editing},r={enabled:t.editing,ignoreInputs:!1};hE([...gE.flatMap(([e,r])=>[{hotkey:e,callback:()=>void t.move(r),options:n},{hotkey:`Shift+${e}`,callback:()=>t.extend(r),options:n}]),{hotkey:`Enter`,callback:t.edit,options:n},{hotkey:`F2`,callback:t.edit,options:n},{hotkey:`Space`,callback:t.expand,options:n},{hotkey:`Mod+C`,callback:t.copy,options:n},{hotkey:`Delete`,callback:t.clear,options:n},{hotkey:`Backspace`,callback:t.clear,options:n},{hotkey:`Mod+Z`,callback:t.undo,options:n},{hotkey:`Shift+Enter`,callback:t.add,options:n},{hotkey:`Enter`,callback:()=>t.commit(),options:r},{hotkey:`Escape`,callback:t.cancel,options:r},..._E.flatMap(([e,i])=>[{hotkey:e,callback:e=>{t.move(i)&&e.preventDefault()},options:{...n,preventDefault:!1}},{hotkey:e,callback:()=>t.commit(i),options:r}])],{target:e,conflictBehavior:`allow`})}function yE(e){if(!(e.ctrlKey||e.metaKey||e.altKey))return[...e.key].length===1&&e.key!==` `?e.key:void 0}var bE=Lb({cellSelectionFeature:jx,columnVisibilityFeature:CS,columnSizingFeature:sS,columnResizingFeature:oS}),xE=Ib(),SE=96,CE=37,wE={width:1200,height:592};function TE({collection:e,view:t,order:n,open:r,where:a,limit:o,reading:s,hide:l,people:u}){let{name:m,key:h}=e,{collection:g,edit:_,stage:y}=t,b=n?.replace(/^-/,``),x=g_({query:e=>{let t=e.from({saved:g});return(b?t.orderBy(({saved:e})=>e.record[b],{direction:n?.startsWith(`-`)?`desc`:`asc`,nulls:`last`,stringSort:`lexical`}):t).orderBy(({saved:e})=>e.key,{direction:`asc`,stringSort:`lexical`})}}).data,S=(0,K.useMemo)(()=>[...x.filter(e=>!Tv(e.key)),...x.filter(e=>Tv(e.key)).toSorted((e,t)=>e.key<t.key?-1:1)],[x]),C=L({from:M_}),w=me(),T=(0,K.useMemo)(()=>new Map((xn(e.record)??[]).flatMap(e=>e.kind===`object`||e.kind===`array`?[]:[[e.key,e]])),[e.record]),E=(0,K.useMemo)(()=>[...T.values()].filter(e=>e.required).map(e=>e.key),[T]),[D,ee]=(0,K.useState)(),te=c(m,a),O=x.filter(e=>!Tv(e.key)).length,k=ge({...te,enabled:O>=o}).data,A=he(),j=j_({view:t,keyField:h,required:E,listed:x,reading:s,onSaved:()=>{ee(Date.now()),A.invalidateQueries({queryKey:te.queryKey})}}),{staged:M,saving:ne,changeOfKey:N}=j,re=(0,K.useMemo)(()=>xE.columns([...fe(e.fields).map(e=>xE.accessor(t=>t.record[e],{id:e,header:e,size:e===h?200:160})),xE.accessor(e=>e.updatedAt,{id:zS,header:BS[zS],size:130}),xE.accessor(e=>e.updatedBy,{id:`@by`,header:BS[`@by`],size:110})]),[e.fields,h]),P=(0,K.useMemo)(()=>Object.fromEntries((l??[]).filter(e=>e!==h).map(e=>[e,!1])),[l,h]),[ie,ae]=(0,K.useState)({});(0,K.useEffect)(()=>ae(HS(m)),[m]);let F=TS({features:bE,columns:re,data:S,getRowId:e=>e.key,state:{columnVisibility:P,columnSizing:ie},onColumnSizingChange:ae,columnResizeMode:`onChange`,defaultColumn:{minSize:60,maxSize:800},autoResetCellSelection:!1}),I=F.state.columnResizing.isResizingColumn!==!1;(0,K.useEffect)(()=>{!I&&Object.keys(ie).length&&US(m,ie)},[m,ie,I]);let oe=ge((0,K.useMemo)(()=>v({name:m,key:h}),[m,h])).data,se=(0,K.useRef)(void 0);(0,K.useEffect)(()=>{se.current?.some(e=>!oe?.includes(e))&&g.utils.refetch(),se.current=oe},[oe,g]);let[ce,R]=(0,K.useState)(new Map),le=e=>R(t=>{let n=new Map(t);return n.delete(v_(e)),n});function ue(e,t,n,r=!1){let a=g.get(e)?.record[t],o=_({key:e,record:n});o.mutations.length!==0&&o.when(`settled`).then(()=>{let n=bv(o,e);n&&(ee(Date.parse(n.updatedAt)),r?i.success(`Undid ${t} for ${e}`):y.current()?i.success(`Saved ${t} for ${e}`):i.success((0,Q.jsxs)(Q.Fragment,{children:[`Saved `,t,` for `,(0,Q.jsx)(XC,{name:m,recordKey:e})]}),{action:{label:`Undo`,onClick:()=>{if(y.current())return void i.info(x_);let n=g.get(e);n&&ue(e,t,xv(n.record,t,a),!0)}}}))},r=>{let a=d(r);if(a?.code===`record_changed`){let r={key:e,field:t,mine:n[t],current:a.current};R(e=>new Map(e).set(v_(r),r))}else i.error(`Could not save ${t} for ${e}`,{description:r===void 0?`A change before it was not saved.`:p(r)})})}async function de(e){if(y.current())return void i.info(x_);let t=e.current;if(t===void 0)try{t=await f.data[m].get({key:e.key})}catch(t){i.error(`Could not read ${e.key}`,{description:p(t)});return}if(!t)return i.error(`${e.key} is gone`,{description:`Someone else deleted the record.`}),pe(e);le(e),await g.utils.writeUpsert(t),ue(e.key,e.field,xv(t.record,e.field,e.mine))}let pe=e=>{le(e),g.utils.refetch()},[z,B]=(0,K.useState)(null),V=(0,K.useRef)(null),H=e=>{V.current=e,B(e)},_e=(0,K.useRef)(!1),[ve,ye]=(0,K.useState)(null),[xe,Se]=(0,K.useState)(null),Ce=(0,K.useRef)(null),we=F.getRowModel().rows,Te=F.getTotalSize(),Ee=e=>`${e/Te*100}%`,U=F.getFocusedCell(),De=U&&T.get(U.column.id),Oe=F.getVisibleLeafColumns(),Ae=sw({table:F,fields:T,keyField:h,changeOfKey:N,stage:j.add}),{fillFrom:W,fillTo:Me,setFillTo:Pe}=Ae,Fe=U&&De&&Ae.changeable(U.row.original,De.key)?De:void 0,Ie=e=>{if(!U||!Fe)return;let t=U.row.original,n=t.record[Fe.key],r=$C(Fe,n,void 0,u),i=$C(Fe,n,e,u);(0,rC.flushSync)(()=>H({key:t.key,field:Fe.key,draft:i,start:r}))},Le=(e,t=!0)=>{let n=V.current;if(!n)return;let r=T.get(n.field),a=g.get(n.key),o=Ae.selectedCells();if(_e.current=t,H(null),e&&F.moveCellSelection(e),!a||n.draft===n.start&&o.length<=1)return;let s=ew(r,a.record,n.draft);if(`error`in s)return void i.error(`${n.field}: ${s.error}`);let c=s.record[n.field];if(o.length>1){let e=_n(c),t=o.flatMap(({saved:t,id:n})=>Ae.changeOf(t,n,e));return j.add({what:`edit`,said:`Set ${G(t.length,`cell`)} to ${e||`nothing`}`,cells:t})}if(M){let e=Tv(n.key)?_n(a.record[h])||`the new record`:n.key;return j.add({what:`edit`,said:`Changed ${n.field} of ${e}`,cells:[{key:n.key,field:n.field,value:c}]})}ue(n.key,n.field,s.record)};vE(xe,{editing:z!==null,move:e=>{let t=F.getFocusedCell()?.id;return F.moveCellSelection(e),F.getFocusedCell()?.id!==t},extend:e=>F.extendCellSelection(e),edit:()=>Ie(),commit:Le,cancel:()=>{_e.current=!0,H(null)},expand:()=>{if(M)return void i.info(x_);U&&C({search:e=>({...e,record:U.row.id,new:void 0}),resetScroll:!1})},copy:()=>{let[e]=F.getSelectedCellRangesData();if(!e)return;let t=mn(e,` `);Promise.resolve().then(()=>navigator.clipboard.writeText(t)).catch(()=>i.error(`Could not copy the cells`))},clear:Ae.clear,undo:y.undo,add:()=>{_e.current=!0,Ae.addRecord()}});let Re=UC({count:we.length,getScrollElement:()=>Ce.current,estimateSize:()=>CE,getItemKey:e=>we[e].id,overscan:12,initialRect:wE}),ze=w?Re.getVirtualItems():we.map((e,t)=>({index:t,start:t*CE,end:(t+1)*CE})),Be=ze[0]?.start??0,Ve=w?Re.getTotalSize()-(ze.at(-1)?.end??0):0,He=U?.id,Ue=U?.row.getDisplayIndex(),We=(0,K.useRef)(void 0);(0,K.useEffect)(()=>{if(!ve||!He||z||!_e.current&&(We.current===He||!ve.contains(document.activeElement)))return;let e=ve.querySelector(`[data-cell="${CSS.escape(He)}"]`);if(!e)return void(Ue!==void 0&&Re.scrollToIndex(Ue));_e.current=!1,We.current=He,e.focus()},[ve,He,Ue,z,Be,Re]);let Ge=Map.groupBy([...ce.values(),...j.conflicts],e=>e.key);return x.length===0?(0,Q.jsx)(Ne,{title:a?`No record matches`:`No records yet`,children:a?`Change the filters to see others.`:`Add one, or save one from a workflow.`}):(0,Q.jsxs)(`div`,{className:mt(be,`flex flex-col overflow-hidden rounded-lg border`),children:[j.reviewing&&(0,Q.jsx)(k_,{changes:j.changes,issues:j.issues.map(e=>({...e,name:N.get(e.key)?.name??e.key})),blocked:j.blocked,saving:ne,onSave:()=>void j.save(new Set(j.changes.flatMap(e=>j.blocked.has(e.key)?[]:[e.key]))),onClose:()=>j.setReviewing(!1)}),(0,Q.jsx)(`div`,{ref:Ce,className:`max-h-[min(70vh,48rem)] overflow-auto`,children:(0,Q.jsxs)(`table`,{ref:ye,role:`grid`,"aria-label":e.title??m,"aria-rowcount":we.length+1,"aria-colcount":Oe.length,"data-slot":`table`,className:`table-fixed border-separate border-spacing-0 text-sm`,style:{width:`100%`,minWidth:Oe.length*SE},onKeyDown:e=>{let t=z?void 0:yE(e);t!==void 0&&Fe&&e.target.dataset.cell!==void 0&&(e.preventDefault(),Ie(t))},onPaste:e=>{z||(e.preventDefault(),Ae.paste(e.clipboardData.getData(`text/plain`)))},children:[(0,Q.jsx)(Rt,{children:(0,Q.jsx)(Vt,{"aria-rowindex":1,className:`hover:bg-transparent`,children:F.getFlatHeaders().map(t=>{let r={style:{width:Ee(t.getSize())},className:`sticky top-0 z-10 border-b bg-background pr-9`},i=(0,Q.jsx)(`div`,{"aria-hidden":!0,"data-resizing":t.column.getIsResizing()||void 0,className:`absolute top-0 right-0 h-full w-1.5 cursor-col-resize touch-none select-none hover:bg-border data-resizing:bg-ring`,onMouseDown:t.getResizeHandler(),onTouchStart:t.getResizeHandler(),onDoubleClick:()=>t.column.resetSize()});return BS[t.id]?(0,Q.jsxs)(zt,{...r,children:[BS[t.id],t.id===`@by`&&e.declared&&(0,Q.jsx)(JS,{}),i]},t.id):(0,Q.jsxs)(I_,{field:t.id,order:n,staged:M!==void 0,...r,children:[e.declared&&(0,Q.jsx)(GS,{collection:e,field:t.id,rows:x,hide:l}),i]},t.id)})})}),(0,Q.jsxs)(Bt,{ref:Se,children:[Be>0&&(0,Q.jsx)(`tr`,{"aria-hidden":!0,children:(0,Q.jsx)(`td`,{colSpan:Oe.length,style:{height:Be}})}),ze.map(({index:e})=>{let t=we[e],n=t.original,i=Ge.get(n.key)??[],a=N.get(n.key)?.type;return[(0,Q.jsx)(Vt,{"aria-rowindex":e+2,"data-state":n.key===r?`selected`:void 0,"data-staged":a,className:mt(`hover:bg-transparent`,a===`insert`&&`bg-tone-ok/10 hover:bg-tone-ok/10`,a===`delete`&&`line-through opacity-60`),children:t.getVisibleCells().map((r,a)=>{let o=r.column.id,s=T.get(o),c=i.find(e=>e.field===o),l=v_({key:n.key,field:o}),d=j.issueAt.get(l),f=j.changedCells.has(l),p=W!==void 0&&Me!==void 0&&e>W.maxRowIndex&&e<=Me&&a>=W.minColumnIndex&&a<=W.maxColumnIndex,g=r.getSelectionEdges(),_=z?.key===n.key&&z.field===o&&s,v=!U&&e===0&&a===0?0:r.getTabIndex();return(0,Q.jsxs)(Ht,{"data-cell":r.id,tabIndex:v,"aria-selected":r.getIsSelected(),"aria-invalid":c||d?!0:void 0,"data-changed":f||void 0,title:d?.error,style:{width:Ee(r.column.getSize())},className:mt(`relative h-9 truncate border-b px-2 py-0 outline-none select-none`,o===h&&`font-medium`,(o===`@updated`||o===`@by`)&&`text-muted-foreground`,r.getIsSelected()&&`bg-primary/5`,f&&`bg-tone-waiting shadow-[inset_3px_0_0_var(--color-tone-waiting-foreground)]`,d&&`bg-tone-bad shadow-[inset_3px_0_0_var(--color-tone-bad-foreground)]`,c&&`bg-tone-waiting text-tone-waiting-foreground`,p&&`bg-primary/5 shadow-[inset_0_0_0_1px_var(--color-ring)]`,r.getIsFocused()&&`shadow-[inset_0_0_0_2px_var(--color-ring)]`,_&&`px-0.5`),onFocus:e=>{e.target===e.currentTarget&&!r.getIsFocused()&&F.setFocusedCell(t.id,o)},onMouseDown:_?void 0:r.getSelectionStartHandler(),onMouseEnter:Me===void 0?r.getSelectionExtendHandler():()=>Pe(Math.max(e,W?.maxRowIndex??e)),onDoubleClick:()=>Ie(),children:[_?(0,Q.jsx)(aw,{field:s,draft:z.draft,people:u,label:`${o} of ${n.key}`,onDraft:e=>H({...z,draft:e}),onBlur:()=>Le(void 0,!1)}):o===h&&Tv(n.key)?_n(n.record[o])||(0,Q.jsx)(`span`,{className:`font-normal text-muted-foreground italic`,children:`needs a key`}):o===h?(0,Q.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(EE,{name:m,recordKey:n.key,staged:M!==void 0}),n.issues&&(0,Q.jsx)(R_,{issues:n.issues}),oe?.includes(n.key)&&(0,Q.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-xs font-normal text-muted-foreground`,children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`size-2.5 shrink-0 rounded-full border-2 border-tone-waiting-foreground`}),(0,Q.jsx)(`span`,{className:`truncate`,children:`waits for approval`})]}),j.denied.has(n.key)&&(0,Q.jsx)(`span`,{className:`truncate text-xs font-normal text-tone-bad-foreground`,children:`refused`})]}):o===`@updated`?n.updatedAt===``?(0,Q.jsx)(`span`,{className:`italic`,children:`new`}):(0,Q.jsx)(je,{at:Date.parse(n.updatedAt)}):o===`@by`?n.updatedBy:(0,Q.jsx)(L_,{value:c?c.mine:n.record[o]}),w&&!z&&W&&g.bottom&&g.right&&(0,Q.jsx)(`span`,{"aria-hidden":!0,"data-fill-handle":!0,className:`absolute right-0 bottom-0 size-2 cursor-crosshair bg-ring`,onMouseDown:e=>{e.stopPropagation(),e.preventDefault(),Pe(W.maxRowIndex)}})]},r.id)})},t.id),i.length>0&&(0,Q.jsx)(b_,{conflicts:i,columns:Oe.length,onKeep:e=>e.staged?j.settle(e,`theirs`):pe(e),onUseMine:e=>e.staged?j.settle(e,`mine`):void de(e)},`${t.id}:conflicts`)]}),Ve>0&&(0,Q.jsx)(`tr`,{"aria-hidden":!0,children:(0,Q.jsx)(`td`,{colSpan:Oe.length,style:{height:Ve}})})]})]})}),M?(0,Q.jsx)(E_,{staged:M,counts:j.counts,issues:j.issues.length,conflicts:j.conflicts.length,saving:ne,onReview:()=>j.setReviewing(!0),onDiscard:y.discard,onSave:()=>void j.save()}):j.held&&(0,Q.jsx)(D_,{count:j.held.held,runId:j.held.runId,onClose:j.closeHeld}),(0,Q.jsxs)(`footer`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 border-t px-3 py-2 text-xs text-muted-foreground`,children:[(0,Q.jsx)(`span`,{children:O>=o?`The first ${o}${k===void 0?``:` of ${k}`} records: filter them, or show more, to see the rest`:O===1?`1 record matches`:`${O} records match`}),D!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":!0,children:`·`}),(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[`Saved `,(0,Q.jsx)(ke,{tone:`ok`,className:`size-1.5`}),` `,(0,Q.jsx)(je,{at:D})]})]}),M&&(0,Q.jsx)(A_,{staged:M,changes:j.counts.changes}),(0,Q.jsx)(`span`,{className:`ml-auto`,role:`status`,children:U&&(0,Q.jsxs)(Q.Fragment,{children:[`Row `,U.row.getDisplayIndex()+1,`, `,BS[U.column.id]??U.column.id,Fe&&(z?` · Enter to save · Esc to cancel`:` · Enter to change`),!z&&` · Space expands`]})}),(0,Q.jsxs)(dt,{variant:`ghost`,size:`sm`,onClick:()=>{let e=Oe.map(e=>BS[e.id]??e.id),t=we.map(e=>e.getVisibleCells().map(e=>e.getValue())),n=URL.createObjectURL(new Blob([gn([e,...t])],{type:`text/csv`}));Object.assign(document.createElement(`a`),{href:n,download:`${m}.csv`}).click(),setTimeout(()=>URL.revokeObjectURL(n))},children:[(0,Q.jsx)(GC,{"aria-hidden":`true`,"data-icon":`inline-start`}),`Export CSV`]})]})]})}function EE({name:e,recordKey:t,staged:n}){return(0,Q.jsx)(A,{to:`/data/$name`,params:{name:e},search:g(t),disabled:n,title:n?x_:void 0,resetScroll:!1,preload:!1,tabIndex:-1,className:`shrink-0 underline-offset-4 hover:underline aria-disabled:no-underline`,children:t})}var DE=e=>e[0]===`record`?e.slice(1):e;function OE({collection:{name:e,key:t,record:n,fields:r},view:{collection:a,edit:o},saved:s,staged:c,actor:l,onDone:u}){let d=(0,K.useMemo)(()=>(xn(n)??[]).filter(e=>!T(r[e.key])),[n,r]),p=(0,K.useMemo)(()=>{if(s)return yn(d,s.record);let e=l?d.filter(e=>e.kind===`person`).map(e=>[e.key,l]):[];return yn(d,Object.fromEntries(e))},[d,s,l]),m=Be(p,async n=>{let c=Cn(d,n);if(Object.keys(c.errors).length)return{fields:c.errors};let p=c.input,m=String(p[t]??``);try{if(!s&&m&&await f.data[e].get({key:m}))return{fields:{[t]:`A record has this key already: open it to change it`}};let n=Object.entries(s?.record??{}).filter(([e])=>T(r[e])),c=s?o({key:s.key,record:{...Object.fromEntries(n),...p}}):a.insert({key:m,record:p,updatedAt:new Date().toISOString(),updatedBy:l??``});await c.when(`settled`),bv(c,m)&&i.success((0,Q.jsxs)(Q.Fragment,{children:[`Saved `,(0,Q.jsx)(XC,{name:e,recordKey:m})]}))}catch(e){return He(e,d,{at:DE,mismatch:`The record does not match the collection's fields`,failed:`Could not save the record`})}u()});return(0,Q.jsx)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),m.handleSubmit()},children:(0,Q.jsxs)(qt,{children:[d.map(e=>s&&e.key===t?(0,Q.jsx)(`fieldset`,{disabled:!0,className:`contents`,children:(0,Q.jsx)(qe,{form:m,field:e,path:[e.key]})},e.key):(0,Q.jsx)(qe,{form:m,field:e,path:[e.key]},e.key)),c&&(0,Q.jsxs)(Ie,{children:[`Save or discard the staged changes first`,`, in the grid's bar.`]}),(0,Q.jsx)(We,{form:m,children:e=>(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(dt,{type:`submit`,disabled:e||c,children:[e?(0,Q.jsx)(Lt,{"data-icon":`inline-start`}):(0,Q.jsx)(wn,{"aria-hidden":`true`,"data-icon":`inline-start`}),e?`Saving…`:`Save`]}),s&&(0,Q.jsx)(kE,{records:a,recordKey:s.key,disabled:e||c,onDeleted:u})]})})]})})}function kE({records:e,recordKey:t,disabled:n,onDeleted:r}){let[a,o]=(0,K.useState)(!1),s=de({mutationFn:()=>e.delete(t).when(`settled`),onSuccess:e=>{bv(e,t)===null&&i.success(`Deleted ${t}`),o(!1),r()}});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(dt,{type:`button`,variant:`outline`,className:`ml-auto`,disabled:n,onClick:()=>o(!0),children:[(0,Q.jsx)(Ge,{"aria-hidden":`true`,"data-icon":`inline-start`}),`Delete`]}),(0,Q.jsx)(fn,{open:a,onOpenChange:e=>{!e&&!s.isPending&&(s.reset(),o(!1))},children:(0,Q.jsxs)(un,{children:[(0,Q.jsxs)(ln,{children:[(0,Q.jsxs)(dn,{children:[`Delete `,t,`?`]}),(0,Q.jsx)(sn,{children:`The record leaves the collection; the ledger keeps the call. Nothing else changes.`})]}),s.isError&&(0,Q.jsx)(Ie,{variant:`destructive`,children:p(s.error)}),(0,Q.jsxs)(on,{children:[(0,Q.jsx)(cn,{render:(0,Q.jsx)(dt,{type:`button`,variant:`outline`,disabled:s.isPending}),children:`Cancel`}),(0,Q.jsxs)(dt,{type:`button`,variant:`destructive`,disabled:s.isPending,onClick:()=>s.mutate(),children:[s.isPending&&(0,Q.jsx)(Lt,{"data-icon":`inline-start`}),`Delete`]})]})]})})]})}var AE=()=>()=>{};function jE(){let{name:e}=Zt.useParams(),t=Zt.useSearch(),n=(0,K.useMemo)(()=>t=>({collection:m(e)(t),people:z(t.resources).map(e=>e.id),...h(e)(t)}),[e]),{data:{collection:r,people:a,workflows:o,sites:l}}=se({...N(),select:n});if(!r)throw S();let u=w(r,t),{actor:d}=Xt(),g=ge({...I(e,u),enabled:d!==null,placeholderData:(t,n)=>n?.queryKey[1]===e?t:void 0}),[_,v]=(0,K.useState)(u),y=g.isPlaceholderData?_:u;M([y])!==M([_])&&v(y);let x=he(),C=g.data?jv(x,{query:I(e,y),key:r.key,calls:f.data[e],held:_e,history:t=>b(e,t).queryKey}):void 0,T=(0,K.useSyncExternalStore)(C?.stage.subscribe??AE,()=>C?.stage.current()!==void 0,()=>!1),E=(0,K.useCallback)(({current:e,next:t})=>{let n=e=>M([w(r,e.search)]),a=t.pathname!==e.pathname||n(t)!==n(e);return a&&i.info(x_),a},[r]);On({disabled:!T,shouldBlockFn:E});let D=Zt.useNavigate(),ee=()=>void D({search:s,resetScroll:!1}),te=t.new===!0||t.record!==void 0,{column:O}=t,k=te||O!==void 0,j=t.record===void 0?void 0:C?.collection.get(t.record);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(Se,{action:(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(Le,{variant:`outline`,children:(0,Q.jsxs)(A,{to:`/data/$name/import`,params:{name:e},children:[(0,Q.jsx)(Pn,{"aria-hidden":`true`,"data-icon":`inline-start`}),`Import`]})}),(0,Q.jsx)(Le,{children:(0,Q.jsxs)(A,{to:`.`,search:e=>({...s(e),new:!0}),resetScroll:!1,children:[(0,Q.jsx)(rn,{"aria-hidden":`true`,"data-icon":`inline-start`}),`Add record`]})})]}),children:[(0,Q.jsxs)(`code`,{className:`text-muted-foreground`,children:[`data.`,e]}),r.app&&(0,Q.jsx)(Te,{variant:`secondary`,children:r.app}),r.declared&&(0,Q.jsxs)(`span`,{className:`text-sm text-muted-foreground`,children:[`Declared in`,` `,(0,Q.jsx)(A,{to:`/hosting`,search:{resource:r.declared.id},className:`font-mono text-xs underline-offset-4 hover:underline`,children:r.declared.id})]})]}),(0,Q.jsxs)(`section`,{"aria-label":`Records`,className:`flex flex-col gap-(--gap-section)`,children:[(0,Q.jsx)(P_,{collection:r,search:t,staged:T},e),(0,Q.jsxs)(`div`,{className:mt(`grid items-start gap-4`,k&&`lg:grid-cols-[minmax(0,1fr)_24rem]`),children:[(0,Q.jsx)(`div`,{className:`min-w-0`,children:C?(0,Q.jsx)(TE,{collection:r,view:C,order:y.order,open:t.record,where:y.where,limit:y.limit,reading:g.isPlaceholderData,hide:t.hide,people:a},e):d===null?(0,Q.jsx)(Ie,{children:`Say who you are to see the records: the policy decides each read for the person asking.`}):g.isError?(0,Q.jsx)(Ie,{variant:`destructive`,children:p(g.error)}):(0,Q.jsx)(H,{role:`status`,"aria-label":`Loading the records`,className:`h-40 w-full`})}),O&&!te&&(0,Q.jsx)(tC,{collection:r,column:O},JSON.stringify(O)),te&&(0,Q.jsxs)(we,{"aria-label":`Record`,role:`region`,className:`lg:sticky lg:top-4`,children:[(0,Q.jsxs)(Fe,{children:[(0,Q.jsx)(Me,{className:`self-center`,children:t.new?`New record`:`Edit ${t.record}`}),(0,Q.jsx)(U,{children:(0,Q.jsx)(Le,{variant:`ghost`,size:`icon-sm`,children:(0,Q.jsxs)(A,{to:`.`,search:s,resetScroll:!1,children:[(0,Q.jsx)(nn,{"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})})]}),(0,Q.jsx)(De,{children:C&&(t.new||j)?(0,Q.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,Q.jsx)(OE,{collection:r,view:C,saved:j,staged:T,actor:d,onDone:()=>{ee(),x.invalidateQueries({queryKey:c(e,y.where).queryKey})}},t.new?`new:${d??``}`:t.record),j&&(0,Q.jsx)(KC,{name:e,recordKey:j.key})]}):g.data?(0,Q.jsxs)(Ie,{children:[`No record `,(0,Q.jsx)(`code`,{children:t.record}),` among those listed: it may be filtered out, or gone.`]}):d===null?(0,Q.jsx)(Ie,{children:`Say who you are to add or change a record.`}):(0,Q.jsx)(H,{className:`h-40 w-full`})})]})]})]}),(0,Q.jsx)(B,{workflows:o,sites:l})]})}export{jE as component};
|