@fuma-content/studio 1.0.0 → 1.0.1
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/build/client/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/build/client/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/build/client/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/build/client/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/build/client/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/build/client/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/build/client/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/build/client/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/build/client/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/build/client/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/build/client/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/build/client/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/build/client/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/build/client/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/build/client/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/build/client/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/build/client/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/build/client/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/build/client/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/build/client/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/build/client/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/build/client/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/build/client/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/build/client/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/build/client/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/build/client/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/build/client/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/build/client/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/build/client/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/build/client/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/build/client/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/build/client/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/build/client/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/build/client/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/build/client/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/build/client/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/build/client/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/build/client/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/build/client/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/build/client/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/build/client/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/build/client/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/build/client/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/build/client/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/build/client/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/build/client/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/build/client/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/build/client/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/build/client/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/build/client/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/build/client/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/build/client/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/build/client/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/build/client/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/build/client/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/build/client/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/build/client/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/build/client/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/build/client/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/build/client/assets/QueryClientProvider-DqiXnN2L.js +1 -0
- package/build/client/assets/actions-DkbV2Z0p.js +1 -0
- package/build/client/assets/actions-DpkI7OTF.js +1 -0
- package/build/client/assets/badge-CZkdLoIP.js +1 -0
- package/build/client/assets/button-Bm94vje1.js +41 -0
- package/build/client/assets/client-BWBqEatf.js +1 -0
- package/build/client/assets/client-Crg-pMcu.js +1 -0
- package/build/client/assets/client-DVneG3Rq.css +1 -0
- package/build/client/assets/client-OSVRoCKH.js +569 -0
- package/build/client/assets/dropdown-menu-EF-sTINr.js +1 -0
- package/build/client/assets/entry.rsc-D51PwnQL.js +1 -0
- package/build/client/assets/index-BdrDVoE8.js +1 -0
- package/build/client/assets/index-BpILsqFO.js +1 -0
- package/build/client/assets/index-Bx93mXy1.js +11 -0
- package/build/client/assets/index-CQRgqbuL.js +1 -0
- package/build/client/assets/index-DOs5iMXj.js +1 -0
- package/build/client/assets/index-DTzAH5JX.js +1 -0
- package/build/client/assets/layout-CnpYRqF0.js +1 -0
- package/build/client/assets/mdx-BNErtsK6.js +1 -0
- package/build/client/assets/page-DOzl4Kpa.js +1 -0
- package/build/client/assets/page-uNpJU_rv.js +1 -0
- package/build/client/assets/query-z9oLNeTD.js +1 -0
- package/build/client/assets/react-B8--K7an.js +10 -0
- package/build/client/assets/root-B_CXTQpA.js +1 -0
- package/build/client/assets/root-D3NoAGI1.js +1 -0
- package/build/client/assets/root-z8crlXSh.css +1 -0
- package/build/client/assets/route-DVneG3Rq.css +1 -0
- package/build/client/assets/router-a9jyj9wf.js +10 -0
- package/build/client/assets/separator-tWFpvpUX.js +1 -0
- package/build/client/assets/sidebar-BBYit8gY.js +12 -0
- package/build/client/assets/site-header-DQkKe-WA.js +1 -0
- package/build/client/assets/spinner-BdPhtfsc.js +1 -0
- package/build/client/assets/tooltip-Dvh-iHDG.js +16 -0
- package/build/client/assets/use-sync-ZgcwUdu_.js +9 -0
- package/build/client/assets/yaml-Cloe7OVn.js +32 -0
- package/build/server/__ssr_build/__vite_rsc_assets_manifest.js +268 -0
- package/build/server/__ssr_build/assets/QueryClientProvider-DlvBH3OQ.js +30 -0
- package/build/server/__ssr_build/assets/actions-B50-3n-a.js +63 -0
- package/build/server/__ssr_build/assets/actions-BFtCTvOL.js +21 -0
- package/{src/components/ui/badge.tsx → build/server/__ssr_build/assets/badge-DYFvBSp8.js} +23 -28
- package/build/server/__ssr_build/assets/button-C_-b_vqm.js +4098 -0
- package/build/server/__ssr_build/assets/client--HXec13w.js +130 -0
- package/build/server/__ssr_build/assets/client-BqW9rGyi.js +116885 -0
- package/build/server/__ssr_build/assets/client-CU90j0R8.js +154 -0
- package/build/server/__ssr_build/assets/dropdown-menu-D2YyT3lP.js +1312 -0
- package/build/server/__ssr_build/assets/entry.rsc-Cg_DxYkh.js +12 -0
- package/build/server/__ssr_build/assets/index-B-gno69w.js +58 -0
- package/build/server/__ssr_build/assets/index-DBc0nhEL.js +288 -0
- package/build/server/__ssr_build/assets/index-Dtw6X3NW.js +1092 -0
- package/build/server/__ssr_build/assets/index-DvVNShHF.js +86 -0
- package/build/server/__ssr_build/assets/index-PpqpVA51.js +612 -0
- package/build/server/__ssr_build/assets/layout-CPnSx9PI.js +454 -0
- package/build/server/__ssr_build/assets/mdx-bmeV1kyx.js +44 -0
- package/build/server/__ssr_build/assets/page-BwoghW3K.js +38 -0
- package/build/server/__ssr_build/assets/page-HxttullC.js +89 -0
- package/build/server/__ssr_build/assets/query-C1_xUNXy.js +1975 -0
- package/build/server/__ssr_build/assets/root-CS7F-km4.js +16 -0
- package/build/server/__ssr_build/assets/root-D-Y-rGw5.js +73 -0
- package/build/server/__ssr_build/assets/separator-8UA_ceSq.js +49 -0
- package/build/server/__ssr_build/assets/sidebar-BzNOZeBO.js +13194 -0
- package/build/server/__ssr_build/assets/site-header-CXHKSzqk.js +13 -0
- package/build/server/__ssr_build/assets/spinner-BXcLlTNs.js +1291 -0
- package/build/server/__ssr_build/assets/tooltip-DZ4WdJt-.js +9553 -0
- package/build/server/__ssr_build/assets/use-sync-TRS0zL-Y.js +3404 -0
- package/build/server/__ssr_build/assets/yaml-BEdFfhvc.js +63 -0
- package/build/server/__ssr_build/index.js +36076 -0
- package/build/server/__vite_rsc_assets_manifest.js +268 -0
- package/build/server/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/build/server/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/build/server/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/build/server/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/build/server/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/build/server/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/build/server/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/build/server/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/build/server/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/build/server/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/build/server/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/build/server/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/build/server/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/build/server/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/build/server/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/build/server/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/build/server/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/build/server/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/build/server/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/build/server/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/build/server/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/build/server/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/build/server/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/build/server/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/build/server/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/build/server/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/build/server/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/build/server/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/build/server/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/build/server/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/build/server/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/build/server/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/build/server/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/build/server/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/build/server/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/build/server/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/build/server/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/build/server/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/build/server/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/build/server/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/build/server/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/build/server/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/build/server/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/build/server/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/build/server/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/build/server/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/build/server/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/build/server/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/build/server/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/build/server/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/build/server/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/build/server/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/build/server/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/build/server/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/build/server/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/build/server/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/build/server/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/build/server/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/build/server/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/build/server/assets/actions-C92yn6jE.js +61 -0
- package/build/server/assets/actions-CWWFIcb1.js +46 -0
- package/build/server/assets/actions-DZdN0IBq.js +73 -0
- package/build/server/assets/client-BdxXy6rH.js +13 -0
- package/build/server/assets/client-DLzFPnCR.js +13 -0
- package/build/server/assets/config-Cb909uq6.js +257 -0
- package/build/server/assets/index-X49ifkk3.js +9 -0
- package/build/server/assets/jsx-runtime.react-server-D3We4JeM.js +324 -0
- package/build/server/assets/layout-CRw_6FCt.js +2071 -0
- package/build/server/assets/page-BcrsPZbM.js +9 -0
- package/build/server/assets/page-zlF_Ew1s.js +72 -0
- package/build/server/assets/root-CVOXO6T9.js +23 -0
- package/build/server/assets/root-dGb6ch_9.js +38 -0
- package/build/server/assets/root-z8crlXSh.css +1 -0
- package/build/server/assets/route-DVneG3Rq.css +1 -0
- package/build/server/assets/route-Ds0B4hTo.js +44 -0
- package/build/server/assets/route-DvwlfKZg.js +21 -0
- package/build/server/assets/route-o-6k10r9.js +70774 -0
- package/build/server/index.js +17032 -0
- package/dist/bin.mjs +10 -38
- package/dist/package.mjs +1 -1
- package/package.json +30 -32
- package/dist/index.d.mts +0 -52
- package/dist/index.mjs +0 -67
- package/dist/mdx/actions.mjs +0 -32
- package/dist/mdx/client.mjs +0 -167
- package/dist/src/components/code-editor/mdx.lazy.mjs +0 -19
- package/dist/src/components/code-editor/mdx.mjs +0 -44
- package/dist/src/components/code-editor/yaml.lazy.mjs +0 -22
- package/dist/src/components/code-editor/yaml.mjs +0 -63
- package/dist/src/components/editor/editor-base-kit.mjs +0 -41
- package/dist/src/components/editor/editor-kit.mjs +0 -73
- package/dist/src/components/editor/md.mjs +0 -42
- package/dist/src/components/editor/plugins/ai-kit.mjs +0 -68
- package/dist/src/components/editor/plugins/align-base-kit.mjs +0 -28
- package/dist/src/components/editor/plugins/align-kit.mjs +0 -30
- package/dist/src/components/editor/plugins/autoformat-kit.mjs +0 -214
- package/dist/src/components/editor/plugins/basic-blocks-base-kit.mjs +0 -22
- package/dist/src/components/editor/plugins/basic-blocks-kit.mjs +0 -51
- package/dist/src/components/editor/plugins/basic-marks-base-kit.mjs +0 -20
- package/dist/src/components/editor/plugins/basic-marks-kit.mjs +0 -28
- package/dist/src/components/editor/plugins/block-menu-kit.mjs +0 -11
- package/dist/src/components/editor/plugins/block-placeholder-kit.mjs +0 -14
- package/dist/src/components/editor/plugins/block-selection-kit.mjs +0 -48
- package/dist/src/components/editor/plugins/callout-base-kit.mjs +0 -8
- package/dist/src/components/editor/plugins/callout-kit.mjs +0 -10
- package/dist/src/components/editor/plugins/code-block-base-kit.mjs +0 -16
- package/dist/src/components/editor/plugins/code-block-kit.mjs +0 -19
- package/dist/src/components/editor/plugins/column-base-kit.mjs +0 -8
- package/dist/src/components/editor/plugins/column-kit.mjs +0 -10
- package/dist/src/components/editor/plugins/comment-base-kit.mjs +0 -8
- package/dist/src/components/editor/plugins/comment-kit.mjs +0 -53
- package/dist/src/components/editor/plugins/copilot-kit.mjs +0 -49
- package/dist/src/components/editor/plugins/cursor-overlay-kit.mjs +0 -11
- package/dist/src/components/editor/plugins/date-base-kit.mjs +0 -8
- package/dist/src/components/editor/plugins/date-kit.mjs +0 -10
- package/dist/src/components/editor/plugins/discussion-kit.mjs +0 -94
- package/dist/src/components/editor/plugins/dnd-kit.mjs +0 -31
- package/dist/src/components/editor/plugins/emoji-kit.mjs +0 -11
- package/dist/src/components/editor/plugins/exit-break-kit.mjs +0 -12
- package/dist/src/components/editor/plugins/fixed-toolbar-kit.mjs +0 -15
- package/dist/src/components/editor/plugins/floating-toolbar-kit.mjs +0 -15
- package/dist/src/components/editor/plugins/font-base-kit.mjs +0 -14
- package/dist/src/components/editor/plugins/font-kit.mjs +0 -19
- package/dist/src/components/editor/plugins/indent-base-kit.mjs +0 -17
- package/dist/src/components/editor/plugins/indent-kit.mjs +0 -20
- package/dist/src/components/editor/plugins/line-height-base-kit.mjs +0 -20
- package/dist/src/components/editor/plugins/line-height-kit.mjs +0 -22
- package/dist/src/components/editor/plugins/link-base-kit.mjs +0 -8
- package/dist/src/components/editor/plugins/link-kit.mjs +0 -15
- package/dist/src/components/editor/plugins/list-base-kit.mjs +0 -19
- package/dist/src/components/editor/plugins/list-kit.mjs +0 -22
- package/dist/src/components/editor/plugins/markdown-kit.mjs +0 -17
- package/dist/src/components/editor/plugins/math-base-kit.mjs +0 -8
- package/dist/src/components/editor/plugins/math-kit.mjs +0 -10
- package/dist/src/components/editor/plugins/media-base-kit.mjs +0 -23
- package/dist/src/components/editor/plugins/media-kit.mjs +0 -37
- package/dist/src/components/editor/plugins/slash-kit.mjs +0 -11
- package/dist/src/components/editor/plugins/suggestion-base-kit.mjs +0 -8
- package/dist/src/components/editor/plugins/suggestion-kit.mjs +0 -50
- package/dist/src/components/editor/plugins/table-base-kit.mjs +0 -13
- package/dist/src/components/editor/plugins/table-kit.mjs +0 -15
- package/dist/src/components/editor/transforms.mjs +0 -125
- package/dist/src/components/editor/ui/ai-chat-editor.mjs +0 -21
- package/dist/src/components/editor/ui/ai-menu.mjs +0 -488
- package/dist/src/components/editor/ui/ai-node.mjs +0 -24
- package/dist/src/components/editor/ui/ai-toolbar-button.mjs +0 -23
- package/dist/src/components/editor/ui/align-toolbar-button.mjs +0 -71
- package/dist/src/components/editor/ui/block-context-menu.mjs +0 -130
- package/dist/src/components/editor/ui/block-discussion.mjs +0 -200
- package/dist/src/components/editor/ui/block-draggable.mjs +0 -265
- package/dist/src/components/editor/ui/block-list-static.mjs +0 -48
- package/dist/src/components/editor/ui/block-list.mjs +0 -47
- package/dist/src/components/editor/ui/block-selection.mjs +0 -28
- package/dist/src/components/editor/ui/block-suggestion.mjs +0 -319
- package/dist/src/components/editor/ui/blockquote-node-static.mjs +0 -14
- package/dist/src/components/editor/ui/blockquote-node.mjs +0 -16
- package/dist/src/components/editor/ui/callout-node-static.mjs +0 -29
- package/dist/src/components/editor/ui/callout-node.mjs +0 -50
- package/dist/src/components/editor/ui/caption.mjs +0 -39
- package/dist/src/components/editor/ui/code-block-node-static.mjs +0 -30
- package/dist/src/components/editor/ui/code-block-node.mjs +0 -121
- package/dist/src/components/editor/ui/code-node-static.mjs +0 -15
- package/dist/src/components/editor/ui/code-node.mjs +0 -17
- package/dist/src/components/editor/ui/column-node-static.mjs +0 -32
- package/dist/src/components/editor/ui/column-node.mjs +0 -229
- package/dist/src/components/editor/ui/comment-node-static.mjs +0 -14
- package/dist/src/components/editor/ui/comment-node.mjs +0 -33
- package/dist/src/components/editor/ui/comment-toolbar-button.mjs +0 -23
- package/dist/src/components/editor/ui/comment.mjs +0 -422
- package/dist/src/components/editor/ui/cursor-overlay.mjs +0 -36
- package/dist/src/components/editor/ui/date-node-static.mjs +0 -32
- package/dist/src/components/editor/ui/date-node.mjs +0 -60
- package/dist/src/components/editor/ui/editor-static.mjs +0 -31
- package/dist/src/components/editor/ui/editor.mjs +0 -60
- package/dist/src/components/editor/ui/emoji-node.mjs +0 -46
- package/dist/src/components/editor/ui/emoji-toolbar-button.mjs +0 -415
- package/dist/src/components/editor/ui/equation-node-static.mjs +0 -65
- package/dist/src/components/editor/ui/equation-node.mjs +0 -159
- package/dist/src/components/editor/ui/equation-toolbar-button.mjs +0 -23
- package/dist/src/components/editor/ui/fixed-toolbar-buttons.mjs +0 -109
- package/dist/src/components/editor/ui/fixed-toolbar.mjs +0 -16
- package/dist/src/components/editor/ui/floating-toolbar-buttons.mjs +0 -54
- package/dist/src/components/editor/ui/floating-toolbar.mjs +0 -51
- package/dist/src/components/editor/ui/font-color-toolbar-button.mjs +0 -637
- package/dist/src/components/editor/ui/font-size-toolbar-button.mjs +0 -83
- package/dist/src/components/editor/ui/ghost-text.mjs +0 -22
- package/dist/src/components/editor/ui/heading-node-static.mjs +0 -60
- package/dist/src/components/editor/ui/heading-node.mjs +0 -62
- package/dist/src/components/editor/ui/highlight-node-static.mjs +0 -15
- package/dist/src/components/editor/ui/highlight-node.mjs +0 -17
- package/dist/src/components/editor/ui/history-toolbar-button.mjs +0 -35
- package/dist/src/components/editor/ui/hr-node-static.mjs +0 -18
- package/dist/src/components/editor/ui/hr-node.mjs +0 -23
- package/dist/src/components/editor/ui/indent-toolbar-button.mjs +0 -29
- package/dist/src/components/editor/ui/inline-combobox.mjs +0 -148
- package/dist/src/components/editor/ui/insert-toolbar-button.mjs +0 -199
- package/dist/src/components/editor/ui/kbd-node-static.mjs +0 -15
- package/dist/src/components/editor/ui/kbd-node.mjs +0 -17
- package/dist/src/components/editor/ui/line-height-toolbar-button.mjs +0 -56
- package/dist/src/components/editor/ui/link-node-static.mjs +0 -20
- package/dist/src/components/editor/ui/link-node.mjs +0 -28
- package/dist/src/components/editor/ui/link-toolbar-button.mjs +0 -21
- package/dist/src/components/editor/ui/link-toolbar.mjs +0 -141
- package/dist/src/components/editor/ui/list-toolbar-button.mjs +0 -131
- package/dist/src/components/editor/ui/mark-toolbar-button.mjs +0 -20
- package/dist/src/components/editor/ui/media-image-node-static.mjs +0 -32
- package/dist/src/components/editor/ui/media-image-node.mjs +0 -64
- package/dist/src/components/editor/ui/media-placeholder-node.mjs +0 -184
- package/dist/src/components/editor/ui/media-preview-dialog.mjs +0 -113
- package/dist/src/components/editor/ui/media-toolbar-button.mjs +0 -156
- package/dist/src/components/editor/ui/media-toolbar.mjs +0 -80
- package/dist/src/components/editor/ui/media-upload-toast.mjs +0 -39
- package/dist/src/components/editor/ui/media-video-node-static.mjs +0 -27
- package/dist/src/components/editor/ui/mode-toolbar-button.mjs +0 -112
- package/dist/src/components/editor/ui/paragraph-node-static.mjs +0 -15
- package/dist/src/components/editor/ui/paragraph-node.mjs +0 -17
- package/dist/src/components/editor/ui/resize-handle.mjs +0 -43
- package/dist/src/components/editor/ui/slash-node.mjs +0 -228
- package/dist/src/components/editor/ui/suggestion-node-static.mjs +0 -24
- package/dist/src/components/editor/ui/suggestion-node.mjs +0 -111
- package/dist/src/components/editor/ui/suggestion-toolbar-button.mjs +0 -24
- package/dist/src/components/editor/ui/table-icons.mjs +0 -1310
- package/dist/src/components/editor/ui/table-node-static.mjs +0 -68
- package/dist/src/components/editor/ui/table-node.mjs +0 -375
- package/dist/src/components/editor/ui/table-toolbar-button.mjs +0 -190
- package/dist/src/components/editor/ui/turn-into-toolbar-button.mjs +0 -168
- package/dist/src/components/editor/use-chat.mjs +0 -80
- package/dist/src/components/json-schema-editor/client.mjs +0 -46
- package/dist/src/components/json-schema-editor/components/inputs.mjs +0 -438
- package/dist/src/components/json-schema-editor/get-default-values.mjs +0 -23
- package/dist/src/components/json-schema-editor/schema.mjs +0 -131
- package/dist/src/components/json-schema-editor/utils/merge-schema.mjs +0 -134
- package/dist/src/components/json-schema-editor/utils/schema-to-string.mjs +0 -53
- package/dist/src/components/ui/alert-dialog.mjs +0 -90
- package/dist/src/components/ui/avatar.mjs +0 -32
- package/dist/src/components/ui/button.mjs +0 -48
- package/dist/src/components/ui/calendar.mjs +0 -108
- package/dist/src/components/ui/checkbox.mjs +0 -23
- package/dist/src/components/ui/combobox.mjs +0 -53
- package/dist/src/components/ui/command.mjs +0 -42
- package/dist/src/components/ui/context-menu.mjs +0 -67
- package/dist/src/components/ui/dialog.mjs +0 -9
- package/dist/src/components/ui/dropdown-menu.mjs +0 -122
- package/dist/src/components/ui/input-group.mjs +0 -31
- package/dist/src/components/ui/input.mjs +0 -15
- package/dist/src/components/ui/label.mjs +0 -19
- package/dist/src/components/ui/popover.mjs +0 -37
- package/dist/src/components/ui/select.mjs +0 -80
- package/dist/src/components/ui/separator.mjs +0 -19
- package/dist/src/components/ui/spinner.mjs +0 -16
- package/dist/src/components/ui/tabs.mjs +0 -39
- package/dist/src/components/ui/textarea.mjs +0 -14
- package/dist/src/components/ui/toolbar.mjs +0 -183
- package/dist/src/components/ui/tooltip.mjs +0 -38
- package/dist/src/hooks/editor/use-is-creator.mjs +0 -19
- package/dist/src/hooks/use-upload-file.mjs +0 -73
- package/dist/src/lib/config.mjs +0 -34
- package/dist/src/lib/data/store.d.mts +0 -15
- package/dist/src/lib/lowlight.mjs +0 -7
- package/dist/src/lib/utils/deep-equal.mjs +0 -18
- package/dist/src/lib/utils/remove-undefined.mjs +0 -18
- package/dist/src/lib/utils.mjs +0 -10
- package/next.config.ts +0 -23
- package/postcss.config.mjs +0 -7
- package/src/app/(dashboard)/collection/[name]/[...slug]/page.client.tsx +0 -26
- package/src/app/(dashboard)/collection/[name]/[...slug]/page.tsx +0 -18
- package/src/app/(dashboard)/collection/[name]/page.client.tsx +0 -82
- package/src/app/(dashboard)/collection/[name]/page.tsx +0 -11
- package/src/app/(dashboard)/layout.tsx +0 -34
- package/src/app/(dashboard)/page.tsx +0 -38
- package/src/app/api/ai/command/prompts.ts +0 -313
- package/src/app/api/ai/command/route.ts +0 -203
- package/src/app/api/ai/command/utils.ts +0 -242
- package/src/app/api/ai/copilot/route.ts +0 -33
- package/src/app/api/uploadthing/route.ts +0 -5
- package/src/app/codeblock/LICENSE +0 -21
- package/src/app/codeblock/styles.css +0 -289
- package/src/app/favicon.ico +0 -0
- package/src/app/globals.css +0 -223
- package/src/app/layout.client.tsx +0 -15
- package/src/app/layout.tsx +0 -30
- package/src/components/app-sidebar.tsx +0 -162
- package/src/components/code-editor/mdx.lazy.tsx +0 -18
- package/src/components/code-editor/mdx.tsx +0 -48
- package/src/components/code-editor/yaml.lazy.tsx +0 -20
- package/src/components/code-editor/yaml.tsx +0 -71
- package/src/components/collection/actions.tsx +0 -41
- package/src/components/collection/client.tsx +0 -63
- package/src/components/collection/context.tsx +0 -24
- package/src/components/collection/document/actions.tsx +0 -83
- package/src/components/editor/editor-base-kit.tsx +0 -37
- package/src/components/editor/editor-kit.tsx +0 -87
- package/src/components/editor/md.tsx +0 -60
- package/src/components/editor/plugins/ai-kit.tsx +0 -102
- package/src/components/editor/plugins/align-base-kit.tsx +0 -16
- package/src/components/editor/plugins/align-kit.tsx +0 -18
- package/src/components/editor/plugins/autoformat-kit.tsx +0 -236
- package/src/components/editor/plugins/basic-blocks-base-kit.tsx +0 -34
- package/src/components/editor/plugins/basic-blocks-kit.tsx +0 -87
- package/src/components/editor/plugins/basic-marks-base-kit.tsx +0 -26
- package/src/components/editor/plugins/basic-marks-kit.tsx +0 -40
- package/src/components/editor/plugins/basic-nodes-kit.tsx +0 -6
- package/src/components/editor/plugins/block-menu-kit.tsx +0 -14
- package/src/components/editor/plugins/block-placeholder-kit.tsx +0 -17
- package/src/components/editor/plugins/block-selection-kit.tsx +0 -54
- package/src/components/editor/plugins/callout-base-kit.tsx +0 -5
- package/src/components/editor/plugins/callout-kit.tsx +0 -7
- package/src/components/editor/plugins/code-block-base-kit.tsx +0 -16
- package/src/components/editor/plugins/code-block-kit.tsx +0 -19
- package/src/components/editor/plugins/column-base-kit.tsx +0 -11
- package/src/components/editor/plugins/column-kit.tsx +0 -10
- package/src/components/editor/plugins/comment-base-kit.tsx +0 -5
- package/src/components/editor/plugins/comment-kit.tsx +0 -92
- package/src/components/editor/plugins/copilot-kit.tsx +0 -70
- package/src/components/editor/plugins/cursor-overlay-kit.tsx +0 -13
- package/src/components/editor/plugins/date-base-kit.tsx +0 -5
- package/src/components/editor/plugins/date-kit.tsx +0 -7
- package/src/components/editor/plugins/discussion-kit.tsx +0 -142
- package/src/components/editor/plugins/dnd-kit.tsx +0 -25
- package/src/components/editor/plugins/emoji-kit.tsx +0 -13
- package/src/components/editor/plugins/exit-break-kit.tsx +0 -12
- package/src/components/editor/plugins/fixed-toolbar-kit.tsx +0 -19
- package/src/components/editor/plugins/floating-toolbar-kit.tsx +0 -19
- package/src/components/editor/plugins/font-base-kit.tsx +0 -20
- package/src/components/editor/plugins/font-kit.tsx +0 -29
- package/src/components/editor/plugins/indent-base-kit.tsx +0 -13
- package/src/components/editor/plugins/indent-kit.tsx +0 -22
- package/src/components/editor/plugins/line-height-base-kit.tsx +0 -14
- package/src/components/editor/plugins/line-height-kit.tsx +0 -16
- package/src/components/editor/plugins/link-base-kit.tsx +0 -5
- package/src/components/editor/plugins/link-kit.tsx +0 -15
- package/src/components/editor/plugins/list-base-kit.tsx +0 -17
- package/src/components/editor/plugins/list-kit.tsx +0 -26
- package/src/components/editor/plugins/markdown-kit.tsx +0 -13
- package/src/components/editor/plugins/math-base-kit.tsx +0 -11
- package/src/components/editor/plugins/math-kit.tsx +0 -10
- package/src/components/editor/plugins/media-base-kit.tsx +0 -25
- package/src/components/editor/plugins/media-kit.tsx +0 -28
- package/src/components/editor/plugins/slash-kit.tsx +0 -18
- package/src/components/editor/plugins/suggestion-base-kit.tsx +0 -5
- package/src/components/editor/plugins/suggestion-kit.tsx +0 -83
- package/src/components/editor/plugins/table-base-kit.tsx +0 -20
- package/src/components/editor/plugins/table-kit.tsx +0 -22
- package/src/components/editor/settings-dialog.tsx +0 -418
- package/src/components/editor/transforms.ts +0 -193
- package/src/components/editor/types.ts +0 -149
- package/src/components/editor/ui/ai-chat-editor.tsx +0 -20
- package/src/components/editor/ui/ai-menu.tsx +0 -663
- package/src/components/editor/ui/ai-node.tsx +0 -40
- package/src/components/editor/ui/ai-toolbar-button.tsx +0 -23
- package/src/components/editor/ui/align-toolbar-button.tsx +0 -78
- package/src/components/editor/ui/block-context-menu.tsx +0 -154
- package/src/components/editor/ui/block-discussion.tsx +0 -318
- package/src/components/editor/ui/block-draggable.tsx +0 -464
- package/src/components/editor/ui/block-list-static.tsx +0 -75
- package/src/components/editor/ui/block-list.tsx +0 -72
- package/src/components/editor/ui/block-selection.tsx +0 -37
- package/src/components/editor/ui/block-suggestion.tsx +0 -438
- package/src/components/editor/ui/blockquote-node-static.tsx +0 -5
- package/src/components/editor/ui/blockquote-node.tsx +0 -7
- package/src/components/editor/ui/callout-node-static.tsx +0 -30
- package/src/components/editor/ui/callout-node.tsx +0 -64
- package/src/components/editor/ui/caption.tsx +0 -55
- package/src/components/editor/ui/code-block-node-static.tsx +0 -33
- package/src/components/editor/ui/code-block-node.tsx +0 -161
- package/src/components/editor/ui/code-node-static.tsx +0 -15
- package/src/components/editor/ui/code-node.tsx +0 -17
- package/src/components/editor/ui/column-node-static.tsx +0 -27
- package/src/components/editor/ui/column-node.tsx +0 -285
- package/src/components/editor/ui/comment-node-static.tsx +0 -12
- package/src/components/editor/ui/comment-node.tsx +0 -43
- package/src/components/editor/ui/comment-toolbar-button.tsx +0 -24
- package/src/components/editor/ui/comment.tsx +0 -577
- package/src/components/editor/ui/cursor-overlay.tsx +0 -66
- package/src/components/editor/ui/date-node-static.tsx +0 -45
- package/src/components/editor/ui/date-node.tsx +0 -86
- package/src/components/editor/ui/editor-static.tsx +0 -47
- package/src/components/editor/ui/editor.tsx +0 -120
- package/src/components/editor/ui/emoji-node.tsx +0 -65
- package/src/components/editor/ui/emoji-toolbar-button.tsx +0 -582
- package/src/components/editor/ui/equation-node-static.tsx +0 -94
- package/src/components/editor/ui/equation-node.tsx +0 -218
- package/src/components/editor/ui/equation-toolbar-button.tsx +0 -24
- package/src/components/editor/ui/fixed-toolbar-buttons.tsx +0 -135
- package/src/components/editor/ui/fixed-toolbar.tsx +0 -17
- package/src/components/editor/ui/floating-toolbar-buttons.tsx +0 -72
- package/src/components/editor/ui/floating-toolbar.tsx +0 -76
- package/src/components/editor/ui/font-color-toolbar-button.tsx +0 -804
- package/src/components/editor/ui/font-size-toolbar-button.tsx +0 -102
- package/src/components/editor/ui/ghost-text.tsx +0 -27
- package/src/components/editor/ui/heading-node-static.tsx +0 -54
- package/src/components/editor/ui/heading-node.tsx +0 -54
- package/src/components/editor/ui/highlight-node-static.tsx +0 -11
- package/src/components/editor/ui/highlight-node.tsx +0 -13
- package/src/components/editor/ui/history-toolbar-button.tsx +0 -41
- package/src/components/editor/ui/hr-node-static.tsx +0 -16
- package/src/components/editor/ui/hr-node.tsx +0 -28
- package/src/components/editor/ui/indent-toolbar-button.tsx +0 -27
- package/src/components/editor/ui/inline-combobox.tsx +0 -251
- package/src/components/editor/ui/insert-toolbar-button.tsx +0 -242
- package/src/components/editor/ui/kbd-node-static.tsx +0 -15
- package/src/components/editor/ui/kbd-node.tsx +0 -17
- package/src/components/editor/ui/line-height-toolbar-button.tsx +0 -66
- package/src/components/editor/ui/link-node-static.tsx +0 -21
- package/src/components/editor/ui/link-node.tsx +0 -37
- package/src/components/editor/ui/link-toolbar-button.tsx +0 -18
- package/src/components/editor/ui/link-toolbar.tsx +0 -196
- package/src/components/editor/ui/list-toolbar-button.tsx +0 -195
- package/src/components/editor/ui/mark-toolbar-button.tsx +0 -20
- package/src/components/editor/ui/media-image-node-static.tsx +0 -33
- package/src/components/editor/ui/media-image-node.tsx +0 -75
- package/src/components/editor/ui/media-placeholder-node.tsx +0 -235
- package/src/components/editor/ui/media-preview-dialog.tsx +0 -145
- package/src/components/editor/ui/media-toolbar-button.tsx +0 -202
- package/src/components/editor/ui/media-toolbar.tsx +0 -100
- package/src/components/editor/ui/media-upload-toast.tsx +0 -59
- package/src/components/editor/ui/media-video-node-static.tsx +0 -23
- package/src/components/editor/ui/mode-toolbar-button.tsx +0 -121
- package/src/components/editor/ui/paragraph-node-static.tsx +0 -13
- package/src/components/editor/ui/paragraph-node.tsx +0 -15
- package/src/components/editor/ui/resize-handle.tsx +0 -79
- package/src/components/editor/ui/slash-node.tsx +0 -274
- package/src/components/editor/ui/suggestion-node-static.tsx +0 -30
- package/src/components/editor/ui/suggestion-node.tsx +0 -157
- package/src/components/editor/ui/suggestion-toolbar-button.tsx +0 -25
- package/src/components/editor/ui/table-icons.tsx +0 -685
- package/src/components/editor/ui/table-node-static.tsx +0 -86
- package/src/components/editor/ui/table-node.tsx +0 -569
- package/src/components/editor/ui/table-toolbar-button.tsx +0 -260
- package/src/components/editor/ui/turn-into-toolbar-button.tsx +0 -176
- package/src/components/editor/use-chat.ts +0 -120
- package/src/components/icons/logo.tsx +0 -37
- package/src/components/json-schema-editor/client.tsx +0 -55
- package/src/components/json-schema-editor/components/inputs.tsx +0 -612
- package/src/components/json-schema-editor/get-default-values.ts +0 -29
- package/src/components/json-schema-editor/schema.tsx +0 -206
- package/src/components/json-schema-editor/utils/merge-schema.ts +0 -167
- package/src/components/json-schema-editor/utils/schema-to-string.ts +0 -87
- package/src/components/nav-user.tsx +0 -102
- package/src/components/site-header.tsx +0 -13
- package/src/components/ui/alert-dialog.tsx +0 -182
- package/src/components/ui/avatar.tsx +0 -96
- package/src/components/ui/button.tsx +0 -65
- package/src/components/ui/calendar.tsx +0 -186
- package/src/components/ui/checkbox.tsx +0 -29
- package/src/components/ui/combobox.tsx +0 -267
- package/src/components/ui/command.tsx +0 -180
- package/src/components/ui/context-menu.tsx +0 -161
- package/src/components/ui/dialog.tsx +0 -142
- package/src/components/ui/drawer.tsx +0 -120
- package/src/components/ui/dropdown-menu.tsx +0 -239
- package/src/components/ui/field.tsx +0 -224
- package/src/components/ui/input-group.tsx +0 -144
- package/src/components/ui/input.tsx +0 -19
- package/src/components/ui/label.tsx +0 -18
- package/src/components/ui/popover.tsx +0 -76
- package/src/components/ui/select.tsx +0 -182
- package/src/components/ui/separator.tsx +0 -28
- package/src/components/ui/sheet.tsx +0 -130
- package/src/components/ui/sidebar.tsx +0 -608
- package/src/components/ui/sonner.tsx +0 -45
- package/src/components/ui/spinner.tsx +0 -15
- package/src/components/ui/table.tsx +0 -89
- package/src/components/ui/tabs.tsx +0 -60
- package/src/components/ui/textarea.tsx +0 -18
- package/src/components/ui/toggle-group.tsx +0 -86
- package/src/components/ui/toggle.tsx +0 -45
- package/src/components/ui/toolbar.tsx +0 -365
- package/src/components/ui/tooltip.tsx +0 -57
- package/src/hooks/editor/use-is-creator.ts +0 -21
- package/src/hooks/use-mobile.ts +0 -19
- package/src/hooks/use-mounted.ts +0 -11
- package/src/hooks/use-upload-file.ts +0 -121
- package/src/lib/ai/markdown-joiner-transform.ts +0 -235
- package/src/lib/config.ts +0 -42
- package/src/lib/data/actions.ts +0 -46
- package/src/lib/data/boundary.client.tsx +0 -22
- package/src/lib/data/boundary.tsx +0 -22
- package/src/lib/data/query.ts +0 -9
- package/src/lib/data/store.ts +0 -52
- package/src/lib/lowlight.ts +0 -3
- package/src/lib/uploadthing.ts +0 -19
- package/src/lib/utils/deep-equal.ts +0 -37
- package/src/lib/utils/remove-undefined.ts +0 -21
- package/src/lib/utils/urls.ts +0 -6
- package/src/lib/utils.ts +0 -6
- package/tsconfig.build.json +0 -24
- package/tsconfig.json +0 -37
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{r as z,f as os,g as as,j as k}from"./react-B8--K7an.js";import{S as Qn,p as Ms,r as ce,s as Lt,a as Qe,n as Jn,i as Ts,b as Ps,c as Yn,d as ut,f as Zn,e as Xn,g as Ds,h as er,j as ht,q as Sn}from"./query-z9oLNeTD.js";import{c as tr,t as L,B as xn,X as sr,S as nr,v as rr}from"./button-Bm94vje1.js";import{R as ir,C as or,a as ar,T as cr,D as lr,P as ur,O as hr,l as dr,m as fr,q as pr}from"./tooltip-Dvh-iHDG.js";const yr=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],gr=tr("panel-left",yr);var mr=class extends Qn{constructor(s,e){super(),this.options=e,this.#e=s,this.#o=null,this.#i=Ms(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#n=void 0;#r;#h;#i;#o;#y;#d;#f;#c;#l;#a;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ks(this.#t,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Nt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Nt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#S(),this.#t.removeObserver(this)}setOptions(s){const e=this.options,t=this.#t;if(this.options=this.#e.defaultQueryOptions(s),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ce(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#x(),this.#t.setOptions(this.options),e._defaulted&&!Lt(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const n=this.hasListeners();n&&js(this.#t,t,this.options,e)&&this.#u(),this.updateResult(),n&&(this.#t!==t||ce(this.options.enabled,this.#t)!==ce(e.enabled,this.#t)||Qe(this.options.staleTime,this.#t)!==Qe(e.staleTime,this.#t))&&this.#g();const r=this.#m();n&&(this.#t!==t||ce(this.options.enabled,this.#t)!==ce(e.enabled,this.#t)||r!==this.#a)&&this.#w(r)}getOptimisticResult(s){const e=this.#e.getQueryCache().build(this.#e,s),t=this.createResult(e,s);return vr(this,t)&&(this.#n=t,this.#h=this.options,this.#r=this.#t.state),t}getCurrentResult(){return this.#n}trackResult(s,e){return new Proxy(s,{get:(t,n)=>(this.trackProp(n),e?.(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#i.status==="pending"&&this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(t,n))})}trackProp(s){this.#p.add(s)}getCurrentQuery(){return this.#t}refetch({...s}={}){return this.fetch({...s})}fetchOptimistic(s){const e=this.#e.defaultQueryOptions(s),t=this.#e.getQueryCache().build(this.#e,e);return t.fetch().then(()=>this.createResult(t,e))}fetch(s){return this.#u({...s,cancelRefetch:s.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#u(s){this.#x();let e=this.#t.fetch(this.options,s);return s?.throwOnError||(e=e.catch(Jn)),e}#g(){this.#b();const s=Qe(this.options.staleTime,this.#t);if(Ts||this.#n.isStale||!Ps(s))return;const t=Yn(this.#n.dataUpdatedAt,s)+1;this.#c=ut.setTimeout(()=>{this.#n.isStale||this.updateResult()},t)}#m(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#w(s){this.#S(),this.#a=s,!(Ts||ce(this.options.enabled,this.#t)===!1||!Ps(this.#a)||this.#a===0)&&(this.#l=ut.setInterval(()=>{(this.options.refetchIntervalInBackground||Zn.isFocused())&&this.#u()},this.#a))}#v(){this.#g(),this.#w(this.#m())}#b(){this.#c&&(ut.clearTimeout(this.#c),this.#c=void 0)}#S(){this.#l&&(ut.clearInterval(this.#l),this.#l=void 0)}createResult(s,e){const t=this.#t,n=this.options,r=this.#n,i=this.#r,o=this.#h,c=s!==t?s.state:this.#s,{state:l}=s;let u={...l},h=!1,p;if(e._optimisticResults){const x=this.hasListeners(),b=!x&&Ks(s,e),E=x&&js(s,t,e,n);(b||E)&&(u={...u,...Xn(l.data,s.options)}),e._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:d,status:y}=u;p=u.data;let g=!1;if(e.placeholderData!==void 0&&p===void 0&&y==="pending"){let x;r?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(x=r.data,g=!0):x=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,x!==void 0&&(y="success",p=Ds(r?.data,x,e),h=!0)}if(e.select&&p!==void 0&&!g)if(r&&p===i?.data&&e.select===this.#y)p=this.#d;else try{this.#y=e.select,p=e.select(p),p=Ds(r?.data,p,e),this.#d=p,this.#o=null}catch(x){this.#o=x}this.#o&&(f=this.#o,p=this.#d,d=Date.now(),y="error");const m=u.fetchStatus==="fetching",w=y==="pending",S=y==="error",v=w&&m,O=p!==void 0,_={status:y,fetchStatus:u.fetchStatus,isPending:w,isSuccess:y==="success",isError:S,isInitialLoading:v,isLoading:v,data:p,dataUpdatedAt:u.dataUpdatedAt,error:f,errorUpdatedAt:d,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:m,isRefetching:m&&!w,isLoadingError:S&&!O,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:S&&O,isStale:cs(s,e),refetch:this.refetch,promise:this.#i,isEnabled:ce(e.enabled,s)!==!1};if(this.options.experimental_prefetchInRender){const x=_.data!==void 0,b=_.status==="error"&&!x,E=Q=>{b?Q.reject(_.error):x&&Q.resolve(_.data)},j=()=>{const Q=this.#i=_.promise=Ms();E(Q)},B=this.#i;switch(B.status){case"pending":s.queryHash===t.queryHash&&E(B);break;case"fulfilled":(b||_.data!==B.value)&&j();break;case"rejected":(!b||_.error!==B.reason)&&j();break}}return _}updateResult(){const s=this.#n,e=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#h=this.options,this.#r.data!==void 0&&(this.#f=this.#t),Lt(e,s))return;this.#n=e;const t=()=>{if(!s)return!0;const{notifyOnChangeProps:n}=this.options,r=typeof n=="function"?n():n;if(r==="all"||!r&&!this.#p.size)return!0;const i=new Set(r??this.#p);return this.options.throwOnError&&i.add("error"),Object.keys(this.#n).some(o=>{const a=o;return this.#n[a]!==s[a]&&i.has(a)})};this.#C({listeners:t()})}#x(){const s=this.#e.getQueryCache().build(this.#e,this.options);if(s===this.#t)return;const e=this.#t;this.#t=s,this.#s=s.state,this.hasListeners()&&(e?.removeObserver(this),s.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#C(s){er.batch(()=>{s.listeners&&this.listeners.forEach(e=>{e(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function wr(s,e){return ce(e.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&e.retryOnMount===!1)}function Ks(s,e){return wr(s,e)||s.state.data!==void 0&&Nt(s,e,e.refetchOnMount)}function Nt(s,e,t){if(ce(e.enabled,s)!==!1&&Qe(e.staleTime,s)!=="static"){const n=typeof t=="function"?t(s):t;return n==="always"||n!==!1&&cs(s,e)}return!1}function js(s,e,t,n){return(s!==e||ce(n.enabled,s)===!1)&&(!t.suspense||s.state.status!=="error")&&cs(s,t)}function cs(s,e){return ce(e.enabled,s)!==!1&&s.isStaleByTime(Qe(e.staleTime,s))}function vr(s,e){return!Lt(s.getCurrentResult(),e)}class je{}class Ke extends je{constructor(e,t){super(),this.collection=e,this.alias=t,this.type="collectionRef"}}class oe extends je{constructor(e,t){super(),this.query=e,this.alias=t,this.type="queryRef"}}class Z extends je{constructor(e){super(),this.path=e,this.type="ref"}}class X extends je{constructor(e){super(),this.value=e,this.type="val"}}class ne extends je{constructor(e,t){super(),this.name=e,this.args=t,this.type="func"}}class Cn extends je{constructor(e,t){super(),this.name=e,this.args=t,this.type="agg"}}function Xe(s){return s instanceof Cn||s instanceof ne||s instanceof Z||s instanceof X}function ls(s){return typeof s=="object"&&"expression"in s?s.expression:s}function Fs(s){return typeof s=="object"&&"expression"in s?s.expression:s}function Bs(s){return typeof s=="object"&&"expression"in s&&s.residual===!0}function br(s){return{expression:s,residual:!0}}function Sr(s,e){if(s.from.alias===e)return s.from;for(const t of s.join||[])if(t.from.alias===e)return t.from}function et(s,e,t){if(e.path.length!==0){if(e.path.length===1){const n=e.path[0];if(s.select){const r=s.select[n];if(r&&r.type==="ref")return et(s,r,t)}return{collection:t,path:[n]}}if(e.path.length>1){const[n,...r]=e.path,i=Sr(s,n);return i?i.type==="queryRef"?et(i.query,new Z(r),t):{collection:i.collection,path:r}:void 0}}}class re extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class zs extends re{constructor(e,t,n){const r=`${e==="insert"?"Insert":"Update"} validation failed: ${t.map(i=>`
|
|
2
|
+
- ${i.message} - path: ${i.path}`).join("")}`;super(n||r),this.name="SchemaValidationError",this.type=e,this.issues=t}}class rt extends re{constructor(e){super(e),this.name="CollectionConfigurationError"}}class xr extends rt{constructor(){super("Collection requires a config")}}class Cr extends rt{constructor(){super("Collection requires a sync config")}}class Ir extends rt{constructor(){super("Schema must implement the standard-schema interface")}}class Ls extends rt{constructor(){super("Schema validation must be synchronous")}}class it extends re{constructor(e){super(e),this.name="CollectionStateError"}}class Er extends it{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class Rr extends it{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}}class kr extends it{constructor(){super("Collection is in error state")}}class Or extends it{constructor(){super("Active subscribers count is negative - this should never happen")}}class ue extends re{constructor(e){super(e),this.name="CollectionOperationError"}}class _r extends ue{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class Ar extends ue{constructor(e,t){const n=e===null?"null":typeof e;super(`getKey returned an invalid key type. Expected string or number, but got ${n}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}}class Mr extends ue{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class Tr extends ue{constructor(e,t,n){const r=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${r}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):n?.hasCustomGetKey&&n.hasJoins?super(`${r}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(r)}}class Pr extends ue{constructor(){super("The first argument to update is missing")}}class Dr extends ue{constructor(){super("No keys were passed to update")}}class Kr extends ue{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class jr extends ue{constructor(e,t){super(`Updating the key of an item is not allowed. Original key: "${e}", Attempted new key: "${t}". Please delete the old item and create a new one if a key change is necessary.`)}}class Fr extends ue{constructor(){super("No keys were passed to delete")}}class Br extends ue{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class us extends re{constructor(e){super(e),this.name="MissingHandlerError"}}class zr extends us{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class Lr extends us{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class Nr extends us{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class xe extends re{constructor(e){super(e),this.name="TransactionError"}}class $r extends xe{constructor(){super("mutationFn is required when creating a transaction")}}class Ur extends xe{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class Vr extends xe{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class qr extends xe{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class Ns extends xe{constructor(){super("No pending sync transaction to write to")}}class $s extends xe{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class Wr extends xe{constructor(){super("No pending sync transaction to commit")}}class Gr extends xe{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class ke extends re{constructor(e){super(e),this.name="QueryBuilderError"}}class Hr extends ke{constructor(e){super(`Only one source is allowed in the ${e}`)}}class Qr extends ke{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}}class Jr extends ke{constructor(e){super(`Invalid source for live query: The value provided for alias "${e}" is not a Collection or subquery. Live queries only accept Collection instances or subqueries. Please ensure you're passing a valid Collection or QueryBuilder, not a plain array or other data type.`)}}class dt extends ke{constructor(e,t){super(`Invalid source for ${e}: Expected an object with a single key-value pair like { alias: collection }. For example: .from({ todos: todosCollection }). Got: ${t}`)}}class Yr extends ke{constructor(){super("Join condition must be an equality expression")}}class Zr extends ke{constructor(){super("Query must have a from clause")}}class Us extends ke{constructor(e){super(`Invalid where() expression: Expected a query expression, but received a ${e}. This usually happens when using JavaScript's comparison operators (===, !==, <, >, etc.) directly. Instead, use the query builder functions:
|
|
3
|
+
|
|
4
|
+
❌ .where(({ user }) => user.id === 'abc')
|
|
5
|
+
✅ .where(({ user }) => eq(user.id, 'abc'))
|
|
6
|
+
|
|
7
|
+
Available comparison functions: eq, gt, gte, lt, lte, and, or, not, like, ilike, isNull, isUndefined`)}}class ie extends re{constructor(e){super(e),this.name="QueryCompilationError"}}class Xr extends ie{constructor(){super("DISTINCT requires a SELECT clause.")}}class ei extends ie{constructor(){super("HAVING clause requires GROUP BY clause")}}class ti extends ie{constructor(){super("LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results")}}class In extends ie{constructor(e,t,n){const r=t?`alias "${e}" (collection "${t}")`:`collection "${e}"`,i=n?.length?`. Available keys: ${n.join(", ")}`:"";super(`Input for ${r} not found in inputs map${i}`)}}class si extends ie{constructor(e,t){super(`Subquery uses alias "${e}" which is already used in the parent query. Each alias must be unique across parent and subquery contexts. Parent query aliases: ${t.join(", ")}. Please rename "${e}" in either the parent query or subquery to avoid conflicts.`)}}class ni extends ie{constructor(e){super(`Unsupported FROM type: ${e}`)}}class ri extends ie{constructor(e){super(`Unknown expression type: ${e}`)}}class ii extends ie{constructor(){super("Reference path cannot be empty")}}class oi extends ie{constructor(e){super(`Unknown function: ${e}`)}}class Vs extends ie{constructor(e){super(`Collection "${e}" not found during compilation of join`)}}class Oe extends re{constructor(e){super(e),this.name="JoinError"}}class ai extends Oe{constructor(e){super(`Unsupported join type: ${e}`)}}class ci extends Oe{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}}class li extends Oe{constructor(){super("Invalid join condition: expressions must reference source aliases")}}class ui extends Oe{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}}class hi extends Oe{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}}class di extends Oe{constructor(){super("Invalid join condition")}}class fi extends Oe{constructor(e){super(`Unsupported join source type: ${e}`)}}class Et extends re{constructor(e){super(e),this.name="GroupByError"}}class pi extends Et{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}}class yi extends Et{constructor(e){super(`Unsupported aggregate function: ${e}`)}}class gi extends Et{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}}class mi extends Et{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}}class qs extends re{constructor(e,t){const n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name="SyncCleanupError"}}class wi extends re{constructor(e){super(e),this.name="QueryOptimizerError"}}class vi extends wi{constructor(){super("Cannot combine empty expression list")}}class bi extends ie{constructor(e,t,n,r){super(`Internal error: subscription for alias '${e}' (remapped from '${t}', collection '${n}') is missing in join pipeline. Available aliases: ${r.join(", ")}. This indicates a bug in alias tracking.`)}}class Si extends ie{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(", ")}. This indicates a bug in query compilation. Please report this issue.`)}}class xi extends ie{constructor(){super("setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.")}}const Mt=new WeakMap;let Ci=1;function Ws(s){if(Mt.has(s))return Mt.get(s);const e=Ci++;return Mt.set(s,e),e}const hs=(s,e,t)=>{const{nulls:n}=t;if(s==null&&e==null)return 0;if(s==null)return n==="first"?-1:1;if(e==null)return n==="first"?1:-1;if(typeof s=="string"&&typeof e=="string"&&t.stringSort==="locale")return s.localeCompare(e,t.locale,t.localeOptions);if(Array.isArray(s)&&Array.isArray(e)){for(let o=0;o<Math.min(s.length,e.length);o++){const a=hs(s[o],e[o],t);if(a!==0)return a}return s.length-e.length}if(s instanceof Date&&e instanceof Date)return s.getTime()-e.getTime();const r=typeof s=="object",i=typeof e=="object";if(r||i){if(r&&i){const o=Ws(s),a=Ws(e);return o-a}if(r)return 1;if(i)return-1}return s<e?-1:s>e?1:0},Ii=(s,e,t)=>hs(e,s,{...t,nulls:t.nulls==="first"?"last":"first"});function wt(s){return(e,t)=>s.direction==="asc"?hs(e,t,s):Ii(e,t,s)}const $t=wt({direction:"asc",nulls:"first",stringSort:"locale"});function Ei(s,e){if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}const Ri=128;function ye(s){return s instanceof Date?s.getTime():(typeof Buffer<"u"&&s instanceof Buffer||s instanceof Uint8Array)&&s.byteLength<=Ri?`__u8__${Array.from(s).join(",")}`:s}function ki(s,e){if(s===e)return!0;const t=typeof Buffer<"u"&&s instanceof Buffer||s instanceof Uint8Array,n=typeof Buffer<"u"&&e instanceof Buffer||e instanceof Uint8Array;return t&&n?Ei(s,e):!1}function U(s){return s==null}function De(s){return s===!0}function ee(s,e=!1){return fs(s,e)}function ds(s){return fs(s,!0)}function fs(s,e){switch(s.type){case"val":{const t=s.value;return()=>t}case"ref":return e?_i(s):Oi(s);case"func":return Ai(s,e);default:throw new ri(s.type)}}function Oi(s){const[e,...t]=s.path;if(!e)throw new ii;if(e==="$selected"){if(t.length===0)return r=>r.$selected;if(t.length===1){const r=t[0];return i=>i.$selected?.[r]}else return r=>{const i=r.$selected;if(i===void 0)return;let o=i;for(const a of t){if(o==null)return o;o=o[a]}return o}}const n=e;if(t.length===0)return r=>r[n];if(t.length===1){const r=t[0];return i=>i[n]?.[r]}else return r=>{const i=r[n];if(i===void 0)return;let o=i;for(const a of t){if(o==null)return o;o=o[a]}return o}}function _i(s){const e=s.path;return t=>{let n=t;for(const r of e){if(n==null)return n;n=n[r]}return n}}function Ai(s,e){const t=s.args.map(n=>fs(n,e));switch(s.name){case"eq":{const n=t[0],r=t[1];return i=>{const o=ye(n(i)),a=ye(r(i));return U(o)||U(a)?null:ki(o,a)}}case"gt":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return U(o)||U(a)?null:o>a}}case"gte":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return U(o)||U(a)?null:o>=a}}case"lt":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return U(o)||U(a)?null:o<a}}case"lte":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return U(o)||U(a)?null:o<=a}}case"and":return n=>{let r=!1;for(const i of t){const o=i(n);if(o===!1)return!1;U(o)&&(r=!0)}return r?null:!0};case"or":return n=>{let r=!1;for(const i of t){const o=i(n);if(o===!0)return!0;U(o)&&(r=!0)}return r?null:!1};case"not":{const n=t[0];return r=>{const i=n(r);return U(i)?null:!i}}case"in":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return U(o)?null:Array.isArray(a)?a.includes(o):!1}}case"like":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return U(o)||U(a)?null:Gs(o,a,!1)}}case"ilike":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return U(o)||U(a)?null:Gs(o,a,!0)}}case"upper":{const n=t[0];return r=>{const i=n(r);return typeof i=="string"?i.toUpperCase():i}}case"lower":{const n=t[0];return r=>{const i=n(r);return typeof i=="string"?i.toLowerCase():i}}case"length":{const n=t[0];return r=>{const i=n(r);return typeof i=="string"||Array.isArray(i)?i.length:0}}case"concat":return n=>t.map(r=>{const i=r(n);try{return String(i??"")}catch{try{return JSON.stringify(i)||""}catch{return"[object]"}}}).join("");case"coalesce":return n=>{for(const r of t){const i=r(n);if(i!=null)return i}return null};case"add":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return(o??0)+(a??0)}}case"subtract":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return(o??0)-(a??0)}}case"multiply":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return(o??0)*(a??0)}}case"divide":{const n=t[0],r=t[1];return i=>{const o=n(i),c=r(i)??0;return c!==0?(o??0)/c:null}}case"isUndefined":{const n=t[0];return r=>n(r)===void 0}case"isNull":{const n=t[0];return r=>n(r)===null}default:throw new oi(s.name)}}function Gs(s,e,t){if(typeof s!="string"||typeof e!="string")return!1;const n=t?s.toLowerCase():s;let i=(t?e.toLowerCase():e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return i=i.replace(/%/g,".*"),i=i.replace(/_/g,"."),new RegExp(`^${i}$`).test(n)}function le(s,e){return yt(s,e,new Map)}function yt(s,e,t){if(s===e)return!0;if(s==null||e==null||typeof s!=typeof e)return!1;if(s instanceof Date)return e instanceof Date?s.getTime()===e.getTime():!1;if(e instanceof Date)return!1;if(s instanceof RegExp)return e instanceof RegExp?s.source===e.source&&s.flags===e.flags:!1;if(e instanceof RegExp)return!1;if(s instanceof Map){if(!(e instanceof Map)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const r=Array.from(s.entries()).every(([i,o])=>e.has(i)&&yt(o,e.get(i),t));return t.delete(s),r}if(e instanceof Map)return!1;if(s instanceof Set){if(!(e instanceof Set)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=Array.from(s),r=Array.from(e);if(n.every(o=>typeof o!="object"))return t.delete(s),n.every(o=>e.has(o));const i=n.length===r.length;return t.delete(s),i}if(e instanceof Set)return!1;if(ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)&&!(s instanceof DataView)&&!(e instanceof DataView)){const n=s,r=e;if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)&&!ArrayBuffer.isView(s))return!1;if(Je(s)&&Je(e)){const n=Ut(s),r=Ut(e);return n!==r?!1:typeof s.equals=="function"?s.equals(e):s.toString()===e.toString()}if(Je(e))return!1;if(Array.isArray(s)){if(!Array.isArray(e)||s.length!==e.length)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=s.every((r,i)=>yt(r,e[i],t));return t.delete(s),n}if(Array.isArray(e))return!1;if(typeof s=="object"){if(t.has(s))return t.get(s)===e;t.set(s,e);const n=Object.keys(s),r=Object.keys(e);if(n.length!==r.length)return t.delete(s),!1;const i=n.every(o=>o in e&&yt(s[o],e[o],t));return t.delete(s),i}return!1}const Mi=["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"];function Ut(s){return s[Symbol.toStringTag]}function Je(s){const e=Ut(s);return typeof e=="string"&&Mi.includes(e)}const ps={direction:"asc",nulls:"first",stringSort:"locale"};class Ti{constructor(e){this.originalIndex=e}lookup(e,t){const n=e==="gt"?"lt":e==="gte"?"lte":e==="lt"?"gt":e==="lte"?"gte":e;return this.originalIndex.lookup(n,t)}rangeQuery(e={}){return this.originalIndex.rangeQueryReversed(e)}rangeQueryReversed(e={}){return this.originalIndex.rangeQuery(e)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeReversed(e,t,n){return this.originalIndex.take(e,t,n)}get orderedEntriesArray(){return this.originalIndex.orderedEntriesArrayReversed}get orderedEntriesArrayReversed(){return this.originalIndex.orderedEntriesArray}supports(e){return this.originalIndex.supports(e)}matchesField(e){return this.originalIndex.matchesField(e)}matchesCompareOptions(e){return this.originalIndex.matchesCompareOptions(e)}matchesDirection(e){return this.originalIndex.matchesDirection(e)}getStats(){return this.originalIndex.getStats()}add(e,t){this.originalIndex.add(e,t)}remove(e,t){this.originalIndex.remove(e,t)}update(e,t,n){this.originalIndex.update(e,t,n)}build(e){this.originalIndex.build(e)}clear(){this.originalIndex.clear()}get keyCount(){return this.originalIndex.keyCount}equalityLookup(e){return this.originalIndex.equalityLookup(e)}inArrayLookup(e){return this.originalIndex.inArrayLookup(e)}get indexedKeysSet(){return this.originalIndex.indexedKeysSet}get valueMapData(){return this.originalIndex.valueMapData}}function ot(s,e,t){const n=t??{...ps,...s.compareOptions};for(const r of s.indexes.values())if(r.matchesField(e)&&r.matchesCompareOptions(n))return r.matchesDirection(n.direction)?r:new Ti(r)}function Pi(s){if(s.length===0)return new Set;if(s.length===1)return new Set(s[0]);let e=new Set(s[0]);for(let t=1;t<s.length;t++){const n=new Set;for(const r of e)s[t].has(r)&&n.add(r);e=n}return e}function Di(s){const e=new Set;for(const t of s)for(const n of t)e.add(n);return e}function Ki(s,e){return ys(s,e)}function ys(s,e){if(s.type==="func")switch(s.name){case"eq":case"gt":case"gte":case"lt":case"lte":return Fi(s,e);case"and":return Bi(s,e);case"or":return zi(s,e);case"in":return Li(s,e)}return{canOptimize:!1,matchingKeys:new Set}}function ji(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const t=new Map;for(const n of s.args)if(n.type==="func"&&["gt","gte","lt","lte"].includes(n.name)){const r=n;if(r.args.length===2){const i=r.args[0],o=r.args[1];let a=null,c=null,l=r.name;if(i.type==="ref"&&o.type==="val")a=i,c=o;else if(i.type==="val"&&o.type==="ref")switch(a=o,c=i,l){case"gt":l="lt";break;case"gte":l="lte";break;case"lt":l="gt";break;case"lte":l="gte";break}if(a&&c){const h=a.path.join("."),p=c.value;t.has(h)||t.set(h,[]),t.get(h).push({operation:l,value:p})}}}for(const[n,r]of t)if(r.length>=2){const i=n.split("."),o=ot(e,i);if(o&&o.supports("gt")&&o.supports("lt")){let a,c,l=!0,u=!0;for(const{operation:p,value:f}of r)switch(p){case"gt":(a===void 0||f>a)&&(a=f,l=!1);break;case"gte":(a===void 0||f>a)&&(a=f,l=!0);break;case"lt":(c===void 0||f<c)&&(c=f,u=!1);break;case"lte":(c===void 0||f<c)&&(c=f,u=!0);break}return{canOptimize:!0,matchingKeys:o.rangeQuery({from:a,to:c,fromInclusive:l,toInclusive:u})}}}return{canOptimize:!1,matchingKeys:new Set}}function Fi(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const t=s.args[0],n=s.args[1];let r=null,i=null,o=s.name;if(t.type==="ref"&&n.type==="val")r=t,i=n;else if(t.type==="val"&&n.type==="ref")switch(r=n,i=t,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte";break}if(r&&i){const a=r.path,c=ot(e,a);if(c){const l=i.value,u=o;return c.supports(u)?{canOptimize:!0,matchingKeys:c.lookup(u,l)}:{canOptimize:!1,matchingKeys:new Set}}}return{canOptimize:!1,matchingKeys:new Set}}function Bi(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const t=ji(s,e);if(t.canOptimize)return t;const n=[];for(const r of s.args){const i=ys(r,e);i.canOptimize&&n.push(i)}if(n.length>0){const r=n.map(o=>o.matchingKeys);return{canOptimize:!0,matchingKeys:Pi(r)}}return{canOptimize:!1,matchingKeys:new Set}}function zi(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const t=[];for(const n of s.args){const r=ys(n,e);r.canOptimize&&t.push(r)}if(t.length>0){const n=t.map(i=>i.matchingKeys);return{canOptimize:!0,matchingKeys:Di(n)}}return{canOptimize:!1,matchingKeys:new Set}}function Li(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const t=s.args[0],n=s.args[1];if(t.type==="ref"&&n.type==="val"&&Array.isArray(n.value)){const r=t.path,i=n.value,o=ot(e,r);if(o){if(o.supports("in"))return{canOptimize:!0,matchingKeys:o.lookup("in",i)};if(o.supports("eq")){const a=new Set;for(const c of i){const l=o.lookup("eq",c);for(const u of l)a.add(u)}return{canOptimize:!0,matchingKeys:a}}}}return{canOptimize:!1,matchingKeys:new Set}}class Ni extends Map{constructor(e,t){super(t),this.defaultValue=e}get(e){return this.has(e)?super.get(e):this.defaultValue()}update(e,t){const n=this.get(e),r=t(n);return this.set(e,r),r}}const Tt=3e4;function Pt(s,e){if(e.length<=Tt)s.push(...e);else for(let t=0;t<e.length;t+=Tt){const n=e.slice(t,t+Tt);s.push(...n)}}function $i(s,e,t){let n=0,r=s.length;for(;n<r;){const i=Math.floor((n+r)/2),o=t(s[i],e);if(o<0)n=i+1;else if(o>0)r=i;else return i}return n}class Ui{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(e){if(typeof e!="object"||e===null){const t=String(e);let n=0;for(let r=0;r<t.length;r++){const i=t.charCodeAt(r);n=(n<<5)-n+i,n=n&n}return n}return this.objectIds.has(e)||this.objectIds.set(e,this.nextId++),this.objectIds.get(e)}getStringId(e){return e===null?"null":e===void 0?"undefined":typeof e!="object"?`str_${String(e)}`:`obj_${this.getId(e)}`}}const Dt=new Ui;function Vi(s,e){const[t,n]=s,[r,i]=e,o=[...ft(t,Math.min(n,r)),...ft(Math.max(t,i),n)],a=[...ft(r,Math.min(i,t)),...ft(Math.max(r,n),i)];return{onlyInA:o,onlyInB:a}}function ft(s,e){const t=[];for(let n=s;n<e;n++)t.push(n);return t}function vt(s,e){return typeof s==typeof e?s<e?-1:s>e?1:0:typeof s=="string"?-1:1}function En(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?t.toString():t instanceof Date?t.toISOString():t)}const qi=q(),Wi=q(),Gi=q(),Hi=q(),Qi=q();function q(){return Math.random()*(2**31-1)>>>0}const Rn=new ArrayBuffer(8),Ji=new DataView(Rn),ve=new Uint8Array(Rn);class Rt{constructor(){this.hash=qi,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)}update(e){switch(typeof e){case"symbol":{this.update(Qi);const t=e.description;if(!t)return;for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);this.writeByte(r&255),this.writeByte(r>>>8&255)}return}case"string":this.update(Wi);for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);this.writeByte(n&255),this.writeByte(n>>>8&255)}return;case"number":Ji.setFloat64(0,e,!0),this.writeByte(ve[0]),this.writeByte(ve[1]),this.writeByte(ve[2]),this.writeByte(ve[3]),this.writeByte(ve[4]),this.writeByte(ve[5]),this.writeByte(ve[6]),this.writeByte(ve[7]);return;case"bigint":{let t=e;for(t<0n?(t=-t,this.update(Hi)):this.update(Gi);t>0n;)this.writeByte(Number(t&0xffn)),t>>=8n;e===0n&&this.writeByte(0);return}default:throw new 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}}const Yi=q(),Zi=q(),Xi=q(),eo=q(),to=q(),so=q(),no=q(),ro=q(),io=q(),oo=q(),ao=q(),co=q(),lo=128,tt=new WeakMap;function J(s){const e=new Rt;return kn(e,s),e.digest()}function uo(s){const e=tt.get(s);if(e!==void 0)return e;let t;if(s instanceof Date)t=ho(s);else if(typeof Buffer<"u"&&s instanceof Buffer||s instanceof Uint8Array)if(s.byteLength<=lo)t=fo(s);else return Vt(s);else{if(s instanceof File)return Vt(s);{let n=s,r=ro;s instanceof Array&&(r=io),s instanceof Map&&(r=oo,n=[...s.entries()]),s instanceof Set&&(r=ao,n=[...s.entries()]),t=po(n,r)}}return tt.set(s,t),t}function ho(s){const e=new Rt;return e.update(no),e.update(s.getTime()),e.digest()}function fo(s){const e=new Rt;e.update(co),e.update(s.byteLength);for(let t=0;t<s.byteLength;t++)e.writeByte(s[t]);return e.digest()}function po(s,e){const t=new Rt;t.update(e);const n=Object.keys(s);n.sort(go);for(const r of n)t.update(to),t.update(r),kn(t,s[r]);return t.digest()}function kn(s,e){if(e===null){s.update(Xi);return}switch(typeof e){case"undefined":s.update(eo);return;case"boolean":s.update(e?Yi:Zi);return;case"number":s.update(isNaN(e)?NaN:e===0?0:e);return;case"bigint":case"string":case"symbol":s.update(e);return;case"object":s.update(yo(e));return;case"function":s.update(Vt(e));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof e} which is not supported`)}}function yo(s){let e=tt.get(s);return e===void 0&&(e=uo(s)),e}let Hs=1;function Vt(s){let e=tt.get(s);return e===void 0&&(e=Hs^so,Hs++,tt.set(s,e)),e}function go(s,e){return s.localeCompare(e)}class ${#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(e){return new $(JSON.parse(e))}map(e){return new $(this.#e.map(([t,n])=>[e(t),n]))}filter(e){return new $(this.#e.filter(([t,n])=>e(t)))}negate(){return new $(this.#e.map(([e,t])=>[e,-t]))}concat(e){const t=[];return Pt(t,this.#e),Pt(t,e.getInner()),new $(t)}consolidate(){if(this.#e.length>0){const e=this.#e[0]?.[0];if(Array.isArray(e)&&e.length===2)return this.#t()}return this.#s()}#t(){const e=new Map,t=new Map,n=i=>{if(i.length!==2)throw new Error("Expected tuple of length 2");const[o,a]=i;return`${Dt.getStringId(o)}|${Dt.getStringId(a)}`};for(const[i,o]of this.#e){if(!Array.isArray(i)||i.length!==2)return this.#s();const[a,c]=i;if(typeof a!="string"&&typeof a!="number")return this.#s();let l;Array.isArray(c)&&c.length===2?l=n(c):l=Dt.getStringId(c);const u=a+"|"+l;e.set(u,(e.get(u)||0)+o),t.has(u)||t.set(u,i)}const r=[];for(const[i,o]of e)o!==0&&r.push([t.get(i),o]);return new $(r)}#s(){const e=new Ni(()=>0),t=new Map;let n=!1,r=!1,i=!1;for(const[c,l]of this.#e)if(typeof c=="string")n=!0;else if(typeof c=="number")r=!0;else{i=!0;break}const o=i||n&&r;for(const[c,l]of this.#e){const u=o?J(c):c;o&&!t.has(u)&&t.set(u,c),e.update(u,h=>h+l)}const a=[];for(const[c,l]of e.entries())if(l!==0){const u=o?t.get(c):c;a.push([u,l])}return new $(a)}extend(e){const t=e instanceof $?e.getInner():e;Pt(this.#e,t)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}}class mo{#e;constructor(e){this.#e=e}drain(){const e=[...this.#e].reverse();return this.#e.length=0,e}isEmpty(){return this.#e.length===0}}class he{#e=[];sendData(e){e instanceof $||(e=new $(e));for(const t of this.#e)t.unshift(e)}newReader(){const e=[];return this.#e.push(e),new mo(e)}}class On{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}}class Fe extends On{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}}class wo extends On{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()}}class gs extends Fe{run(){for(const e of this.inputMessages())this.output.sendData(this.inner(e))}}class vo{#e=[];#t=0;#s=!1;constructor(){}#n(){if(this.#s)throw new Error("Graph already finalized")}getNextOperatorId(){return this.#n(),this.#t++}newInput(){this.#n();const e=new he;return new bo(this,e)}addOperator(e){this.#n(),this.#e.push(e)}finalize(){this.#n(),this.#s=!0}step(){if(!this.#s)throw new Error("Graph not finalized");for(const e of this.#e)e.run()}pendingWork(){return this.#e.some(e=>e.hasPendingWork())}run(){for(;this.pendingWork();)this.step()}}class de{#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((t,n)=>n(t),this)}}class bo extends de{sendData(e){this.writer.sendData(e)}}class So extends gs{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.map(this.#e)}}function Y(s){return e=>{const t=new de(e.graph,new he),n=new So(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}const We=Symbol("NO_PREFIX");class Qs extends Map{addValue(e,t){if(t===0)return this.size===0;const n=Ye(e),r=this.get(n);if(gt(r)){const[i,o]=r;if(Ye(i)!==n)throw new Error("Mismatching prefixes, this should never happen");if(i===e||J(i)===J(e)){const c=o+t;c===0?this.delete(n):this.set(n,[e,c])}else{const c=new Ge;c.set(J(i),r),c.set(J(e),[e,t]),this.set(n,c)}}else r===void 0?this.set(n,[e,t]):r.addValue(e,t)&&this.delete(n);return this.size===0}}class Ge extends Map{addValue(e,t){if(t===0)return this.size===0;const n=J(e),r=this.get(n);if(r){const[,i]=r,o=i+t;o===0?this.delete(n):this.set(n,[e,o])}else this.set(n,[e,t]);return this.size===0}}class be{#e;#t=new Map;constructor(){this.#e=new Map}static fromMultiSets(e){const t=new be;for(const n of e)for(const[r,i]of n.getInner()){const[o,a]=r;t.addValue(o,[a,i])}return t}toString(e=!1){return`Index(${JSON.stringify([...this.entries()],void 0,e?2:void 0)})`}get size(){return this.#e.size}has(e){return this.#e.has(e)}hasPresence(e){return(this.#t.get(e)||0)!==0}getConsolidatedMultiplicity(e){return this.#t.get(e)||0}getPresenceKeys(){return this.#t.keys()}get(e){return[...this.getIterator(e)]}*getIterator(e){const t=this.#e.get(e);if(gt(t))yield t;else{if(t===void 0)return;if(t instanceof Ge)for(const n of t.values())yield n;else for(const n of t.values())if(gt(n))yield n;else for(const r of n.values())yield r}}*entries(){for(const e of this.#e.keys())for(const t of this.getIterator(e))yield[e,t]}*entriesIterators(){for(const e of this.#e.keys())yield[e,this.getIterator(e)]}addValue(e,t){const[n,r]=t;if(r===0)return;const i=(this.#t.get(e)||0)+r;i===0?this.#t.delete(e):this.#t.set(e,i);const o=this.#e.get(e);if(o===void 0){this.#e.set(e,t);return}if(gt(o)){this.#s(e,o,n,r);return}if(o instanceof Ge){const a=Ye(n);if(a!==We){const c=new Qs;c.set(We,o),c.set(a,t),this.#e.set(e,c)}else o.addValue(n,r)&&this.#e.delete(e)}else o.addValue(n,r)&&this.#e.delete(e)}#s(e,t,n,r){const[i,o]=t;if(i===n){const l=o+r;l===0?this.#e.delete(e):this.#e.set(e,[n,l]);return}const a=Ye(n),c=Ye(i);if(c===a&&(i===n||J(i)===J(n))){const l=o+r;l===0?this.#e.delete(e):this.#e.set(e,[n,l]);return}if(c===We&&a===We){const l=new Ge;l.set(J(i),t),l.set(J(n),[n,r]),this.#e.set(e,l)}else{const l=new Qs;if(c===a){const u=new Ge;u.set(J(i),t),u.set(J(n),[n,r]),l.set(c,u)}else l.set(c,t),l.set(a,[n,r]);this.#e.set(e,l)}}append(e){for(const[t,n]of e.entries())this.addValue(t,n)}join(e){const t=[];if(this.size<=e.size)for(const[n,r]of this.entriesIterators()){if(!e.has(n))continue;const i=e.get(n);for(const[o,a]of r)for(const[c,l]of i)a!==0&&l!==0&&t.push([[n,[o,c]],a*l])}else for(const[n,r]of e.entriesIterators()){if(!this.has(n))continue;const i=this.get(n);for(const[o,a]of r)for(const[c,l]of i)l!==0&&a!==0&&t.push([[n,[c,o]],l*a])}return new $(t)}}function Ye(s){return Array.isArray(s)&&(typeof s[0]=="string"||typeof s[0]=="number"||typeof s[0]=="bigint")?s[0]:We}function gt(s){return Array.isArray(s)}class xo extends Fe{#e=new be;#t=new be;#s;constructor(e,t,n,r){super(e,t,n),this.#s=r}run(){const e=new Set;for(const n of this.inputMessages())for(const[r,i]of n.getInner()){const[o,a]=r;this.#e.addValue(o,[a,i]),e.add(o)}const t=[];for(const n of e){const r=this.#e.get(n),i=this.#t.get(n),o=this.#s(r),a=new Map,c=new Map;for(const[l,u]of o){const h=a.get(l)??0;a.set(l,h+u)}for(const[l,u]of i){const h=c.get(l)??0;c.set(l,h+u)}for(const[l,u]of c)a.has(l)||(t.push([[n,l],-u]),this.#t.addValue(n,[l,-u]));for(const[l,u]of a)c.has(l)||u!==0&&(t.push([[n,l],u]),this.#t.addValue(n,[l,u]));for(const[l,u]of a){const h=c.get(l);if(h!==void 0){const p=u-h;p!==0&&(t.push([[n,l],p]),this.#t.addValue(n,[l,p]))}}}t.length>0&&this.output.sendData(new $(t))}}function Co(s){return e=>{const t=new de(e.graph,new he),n=new xo(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}function Js(s){return"pipe"in s}function Ys(s,e={}){const t=Object.fromEntries(Object.entries(e).filter(([n,r])=>!Js(r)));return Object.fromEntries(Object.entries(e).filter(([n,r])=>Js(r))),n=>{const r="__original_key__";return n.pipe(Y(a=>{const c=s(a),l=En(c),u={};u[r]=c;for(const[h,p]of Object.entries(t))u[h]=p.preMap(a);return[l,u]})).pipe(Co(a=>{let c=0;for(const[h,p]of a)c+=p;if(c<=0)return[];const l={},u=a[0]?.[0]?.[r];l[r]=u;for(const[h,p]of Object.entries(t)){const f=a.map(([d,y])=>[d[h],y]);l[h]=p.reduce(f)}return[[l,1]]})).pipe(Y(([a,c])=>{const l=c[r],u={};Object.assign(u,l);for(const[h,p]of Object.entries(t))p.postMap?u[h]=p.postMap(c[h]):u[h]=c[h];return[a,u]}))}}function Io(s=e=>e){return{preMap:e=>s(e),reduce:e=>{let t=0;for(const[n,r]of e)t+=n*r;return t}}}function Eo(s=e=>e){return{preMap:e=>s(e)==null?0:1,reduce:e=>{let t=0;for(const[n,r]of e)t+=n*r;return t}}}function Ro(s=e=>e){return{preMap:e=>({sum:s(e),count:0}),reduce:e=>{let t=0,n=0;for(const[r,i]of e)t+=r.sum*i,n+=i;return{sum:t,count:n}},postMap:e=>e.sum/e.count}}function ko(s){const e=s??(t=>t);return{preMap:t=>e(t),reduce:t=>{let n;for(const[r,i]of t)(!n||r&&r<n)&&(n=r);return n}}}function Oo(s){const e=s??(t=>t);return{preMap:t=>e(t),reduce:t=>{let n;for(const[r,i]of t)(!n||r&&r>n)&&(n=r);return n}}}const _o={sum:Io,count:Eo,avg:Ro,min:ko,max:Oo};class Ao extends gs{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}}function Mo(s){return e=>{const t=new de(e.graph,new he),n=new Ao(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}class To extends gs{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}}function Se(s){return e=>{const t=new de(e.graph,new he),n=new To(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}class Po extends Fe{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}run(){for(const e of this.inputMessages())this.#e(e),this.output.sendData(e)}}function Do(s){return e=>{const t=new de(e.graph,new he),n=new Po(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}class Ko extends Fe{run(){const e=this.inputMessages();if(e.length===0)return;const t=new $;for(const r of e)t.extend(r);const n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}}function jo(){return s=>{const e=new de(s.graph,new he),t=new Ko(s.graph.getNextOperatorId(),s.connectReader(),e.writer);return s.graph.addOperator(t),e}}class Fo extends wo{#e=new be;#t=new be;#s;constructor(e,t,n,r,i="inner"){super(e,t,n,r),this.#s=i}run(){const e=be.fromMultiSets(this.inputAMessages()),t=be.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;const n=new $;this.#s!=="anti"&&this.emitInnerResults(e,t,n),(this.#s==="left"||this.#s==="full"||this.#s==="anti")&&this.emitLeftOuterResults(e,t,n),(this.#s==="right"||this.#s==="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(const[r,i]of e.entriesIterators()){const o=this.#t.getConsolidatedMultiplicity(r),a=t.getConsolidatedMultiplicity(r);if(o+a===0)for(const[l,u]of i)u!==0&&n.add([r,[l,null]],u)}if(t.size>0)for(const r of t.getPresenceKeys()){const i=this.#t.getConsolidatedMultiplicity(r),o=t.getConsolidatedMultiplicity(r);if(o===0)continue;const a=i+o;if(i===0==(a===0))continue;const c=i===0;for(const[l,u]of this.#e.getIterator(r))u!==0&&n.add([r,[l,null]],c?-u:+u)}}emitRightOuterResults(e,t,n){if(t.size>0)for(const[r,i]of t.entriesIterators()){const o=this.#e.getConsolidatedMultiplicity(r),a=e.getConsolidatedMultiplicity(r);if(o+a===0)for(const[l,u]of i)u!==0&&n.add([r,[null,l]],u)}if(e.size>0)for(const r of e.getPresenceKeys()){const i=this.#e.getConsolidatedMultiplicity(r),o=e.getConsolidatedMultiplicity(r);if(o===0)continue;const a=i+o;if(i===0==(a===0))continue;const c=i===0;for(const[l,u]of this.#t.getIterator(r))u!==0&&n.add([r,[null,l]],c?-u:+u)}}}function Bo(s,e="inner"){return t=>{if(t.graph!==s.graph)throw new Error("Cannot join streams from different graphs");const n=new de(t.graph,new he),r=new Fo(t.graph.getNextOperatorId(),t.connectReader(),s.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}class zo extends Fe{#e;#t;constructor(e,t,n,r=i=>i){super(e,t,n),this.#e=r,this.#t=new Map}run(){const e=new Map;for(const n of this.inputMessages())for(const[r,i]of n.getInner()){const o=J(this.#e(r)),c=(e.get(o)?.[0]??this.#t.get(o)??0)+i;e.set(o,[c,r])}const t=[];for(const[n,[r,i]]of e.entries()){const o=this.#t.get(n)??0;r===0?this.#t.delete(n):this.#t.set(n,r),o<=0&&r>0?t.push([[J(this.#e(i)),i[1]],1]):o>0&&r<=0&&t.push([[J(this.#e(i)),i[1]],-1])}t.length>0&&this.output.sendData(new $(t))}}function Lo(s=e=>e){return e=>{const t=new de(e.graph,new he),n=new zo(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}const No="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Te(s,e,t){const n=t[0];if(e!=null&&s>=e)throw new Error(s+" >= "+e);if(s.slice(-1)===n||e&&e.slice(-1)===n)throw new Error("trailing zero");if(e){let o=0;for(;(s[o]||n)===e[o];)o++;if(o>0)return e.slice(0,o)+Te(s.slice(o),e.slice(o),t)}const r=s?t.indexOf(s[0]):0,i=e!=null?t.indexOf(e[0]):t.length;if(i-r>1){const o=Math.round(.5*(r+i));return t[o]}else return e&&e.length>1?e.slice(0,1):t[r]+Te(s.slice(1),null,t)}function _n(s){if(s.length!==An(s[0]))throw new Error("invalid integer part of order key: "+s)}function An(s){if(s>="a"&&s<="z")return s.charCodeAt(0)-97+2;if(s>="A"&&s<="Z")return 90-s.charCodeAt(0)+2;throw new Error("invalid order key head: "+s)}function He(s){const e=An(s[0]);if(e>s.length)throw new Error("invalid order key: "+s);return s.slice(0,e)}function Zs(s,e){if(s==="A"+e[0].repeat(26))throw new Error("invalid order key: "+s);const t=He(s);if(s.slice(t.length).slice(-1)===e[0])throw new Error("invalid order key: "+s)}function Xs(s,e){_n(s);const[t,...n]=s.split("");let r=!0;for(let i=n.length-1;r&&i>=0;i--){const o=e.indexOf(n[i])+1;o===e.length?n[i]=e[0]:(n[i]=e[o],r=!1)}if(r){if(t==="Z")return"a"+e[0];if(t==="z")return null;const i=String.fromCharCode(t.charCodeAt(0)+1);return i>"a"?n.push(e[0]):n.pop(),i+n.join("")}else return t+n.join("")}function $o(s,e){_n(s);const[t,...n]=s.split("");let r=!0;for(let i=n.length-1;r&&i>=0;i--){const o=e.indexOf(n[i])-1;o===-1?n[i]=e.slice(-1):(n[i]=e[o],r=!1)}if(r){if(t==="a")return"Z"+e.slice(-1);if(t==="A")return null;const i=String.fromCharCode(t.charCodeAt(0)-1);return i<"Z"?n.push(e.slice(-1)):n.pop(),i+n.join("")}else return t+n.join("")}function Uo(s,e,t=No){if(s!=null&&Zs(s,t),e!=null&&Zs(e,t),s!=null&&e!=null&&s>=e)throw new Error(s+" >= "+e);if(s==null){if(e==null)return"a"+t[0];const c=He(e),l=e.slice(c.length);if(c==="A"+t[0].repeat(26))return c+Te("",l,t);if(c<e)return c;const u=$o(c,t);if(u==null)throw new Error("cannot decrement any more");return u}if(e==null){const c=He(s),l=s.slice(c.length),u=Xs(c,t);return u??c+Te(l,null,t)}const n=He(s),r=s.slice(n.length),i=He(e),o=e.slice(i.length);if(n===i)return n+Te(r,o,t);const a=Xs(n,t);if(a==null)throw new Error("cannot increment any more");return a<e?a:n+Te(r,null,t)}function en(s,e){return[s,e]}function tn(s){return s[0]}function sn(s){return s[1]}function Vo(s){return([e,t],[n,r])=>{const i=s(t,r);return i!==0?i:vt(e,n)}}class Mn{#e=[];#t;#s;#n;constructor(e,t,n){this.#s=e,this.#n=e+t,this.#t=n}get size(){const e=this.#s,t=this.#n-this.#s,n=this.#e.length-e;return Math.max(0,Math.min(t,n))}move({offset:e,limit:t}){const n=this.#s,r=this.#n-this.#s,i=[this.#s,this.#n===1/0?this.#s+this.size:this.#n];this.#s=e??n,this.#n=this.#s+(t??r);const o=[this.#s,this.#n===1/0?Math.max(this.#s+this.size,i[1]):this.#n],{onlyInA:a,onlyInB:c}=Vi(i,o),l=[];c.forEach(h=>{const p=this.#e[h];p&&l.push(p)});const u=[];return a.forEach(h=>{const p=this.#e[h];p&&u.push(p)}),{moveIns:l,moveOuts:u,changes:a.length+c.length>0}}insert(e){const t={moveIn:null,moveOut:null},n=this.#r(e),r=n===0?null:sn(this.#e[n-1]),i=n===this.#e.length?null:sn(this.#e[n]),o=Uo(r,i),a=en(e,o);if(this.#e.splice(n,0,a),n<this.#n){const c=Math.max(n,this.#s);c<this.#e.length&&(t.moveIn=this.#e[c],this.#n<this.#e.length&&(t.moveOut=this.#e[this.#n]))}return t}delete(e){const t={moveIn:null,moveOut:null},n=this.#r(e),[r]=this.#e.splice(n,1);if(n<this.#n){if(t.moveOut=r,n<this.#s){const o=this.#s-1;o<this.#e.length?t.moveOut=this.#e[o]:t.moveOut=null}const i=this.#n-1;i<this.#e.length&&(t.moveIn=this.#e[i])}return t}#r(e){return $i(this.#e,en(e,""),(t,n)=>this.#t(tn(t),tn(n)))}}class qo{#e=new Map;#t;constructor(e){this.#t=e}get size(){return this.#t.size}get isEmpty(){return this.#e.size===0&&this.#t.size===0}processElement(e,t,n){const{oldMultiplicity:r,newMultiplicity:i}=this.#s(e,n);return r<=0&&i>0?this.#t.insert([e,t]):r>0&&i<=0?this.#t.delete([e,t]):{moveIn:null,moveOut:null}}move(e){if(!(this.#t instanceof Mn))throw new Error("Cannot move B+-tree implementation of TopK with fractional index");return this.#t.move(e)}#s(e,t){if(t===0){const i=this.#e.get(e)??0;return{oldMultiplicity:i,newMultiplicity:i}}const n=this.#e.get(e)??0,r=n+t;return r===0?this.#e.delete(e):this.#e.set(e,r),{oldMultiplicity:n,newMultiplicity:r}}}function nn(s,e){if(s){const[[t,n],r]=s;e.push([[t,[n,r]],1])}}function rn(s,e){if(s){const[[t,n],r]=s;e.push([[t,[n,r]],-1])}}class Wo extends Fe{#e;constructor(e,t,n,r,i){super(e,t,n);const o=i.limit??1/0,a=i.offset??0,c=this.createTopK(a,o,Vo(r));this.#e=new qo(c),i.setSizeCallback?.(()=>this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}createTopK(e,t,n){return new Mn(e,t,n)}moveTopK({offset:e,limit:t}){const n=[],r=this.#e.move({offset:e,limit:t});r.moveIns.forEach(i=>nn(i,n)),r.moveOuts.forEach(i=>rn(i,n)),r.changes&&this.output.sendData(new $(n))}run(){const e=[];for(const t of this.inputMessages())for(const[n,r]of t.getInner()){const[i,o]=n;this.processElement(i,o,r,e)}e.length>0&&this.output.sendData(new $(e))}processElement(e,t,n,r){const i=this.#e.processElement(e,t,n);nn(i.moveIn,r),rn(i.moveOut,r)}}function Go(s,e){const t=e||{};return n=>{const r=new de(n.graph,new he),i=new Wo(n.graph.getNextOperatorId(),n.connectReader(),r.writer,s,t);return n.graph.addOperator(i),r}}function Ho(s,e,t){const n=t?.limit??1/0,r=t?.offset??0,i=t?.setSizeCallback,o=t?.setWindowFn,a=t?.comparator??((c,l)=>c===l?0:c<l?-1:1);return c=>c.pipe(s((l,u)=>a(e(l),e(u)),{limit:n,offset:r,setSizeCallback:i,setWindowFn:o}),jo())}function Qo(s,e){return Ho(Go,s,e)}class Jo{constructor(e,t,n){this._root=Kt,this._size=0,this._maxNodeSize=n>=4?Math.min(n,256):32,this._compare=e,t&&this.setPairs(t)}get size(){return this._size}get length(){return this._size}get isEmpty(){return this._size===0}clear(){this._root=Kt,this._size=0}get(e,t){return this._root.get(e,t,this)}set(e,t,n){this._root.isShared&&(this._root=this._root.clone());const r=this._root.set(e,t,n,this);return r===!0||r===!1?r:(this._root=new ms([this._root,r]),!0)}has(e){return this.forRange(e,e,!0,void 0)!==0}delete(e){return this.editRange(e,e,!0,Zo)!==0}get maxNodeSize(){return this._maxNodeSize}minKey(){return this._root.minKey()}maxKey(){return this._root.maxKey()}keysArray(){const e=[];return this._root.forRange(this.minKey(),this.maxKey(),!0,!1,this,0,(t,n)=>{e.push(t)}),e}nextHigherPair(e,t){return t=t||[],e===void 0?this._root.minPair(t):this._root.getPairOrNextHigher(e,this._compare,!1,t)}nextHigherKey(e){const t=this.nextHigherPair(e,on);return t&&t[0]}nextLowerPair(e,t){return t=t||[],e===void 0?this._root.maxPair(t):this._root.getPairOrNextLower(e,this._compare,!1,t)}nextLowerKey(e){const t=this.nextLowerPair(e,on);return t&&t[0]}setPairs(e,t){let n=0;for(const r of e)this.set(r[0],r[1],t)&&n++;return n}forRange(e,t,n,r,i){const o=this._root.forRange(e,t,n,!1,this,i||0,r);return typeof o=="number"?o:o.break}editRange(e,t,n,r,i){let o=this._root;o.isShared&&(this._root=o=o.clone());try{const a=o.forRange(e,t,n,!0,this,i||0,r);return typeof a=="number"?a:a.break}finally{let a;for(;o.keys.length<=1&&!o.isLeaf;)a||=o.isShared,this._root=o=o.keys.length===0?Kt:o.children[0];a&&(o.isShared=!0)}}}class st{get isLeaf(){return this.children===void 0}constructor(e=[],t){this.keys=e,this.values=t||H,this.isShared=void 0}maxKey(){return this.keys[this.keys.length-1]}indexOf(e,t,n){const r=this.keys;let i=0,o=r.length,a=o>>1;for(;i<o;){const c=n(r[a],e);if(c<0)i=a+1;else if(c>0)o=a;else{if(c===0)return a;if(e===e)return r.length;throw new Error("BTree: NaN was used as a key")}a=i+o>>1}return a^t}minKey(){return this.keys[0]}minPair(e){if(this.keys.length!==0)return e[0]=this.keys[0],e[1]=this.values[0],e}maxPair(e){if(this.keys.length===0)return;const t=this.keys.length-1;return e[0]=this.keys[t],e[1]=this.values[t],e}clone(){const e=this.values;return new st(this.keys.slice(0),e===H?e:e.slice(0))}get(e,t,n){const r=this.indexOf(e,-1,n._compare);return r<0?t:this.values[r]}getPairOrNextLower(e,t,n,r){const i=this.indexOf(e,-1,t),o=i<0?~i-1:n?i:i-1;if(o>=0)return r[0]=this.keys[o],r[1]=this.values[o],r}getPairOrNextHigher(e,t,n,r){const i=this.indexOf(e,-1,t),o=i<0?~i:n?i:i+1,a=this.keys;if(o<a.length)return r[0]=a[o],r[1]=this.values[o],r}set(e,t,n,r){let i=this.indexOf(e,-1,r._compare);if(i<0){if(i=~i,r._size++,this.keys.length<r._maxNodeSize)return this.insertInLeaf(i,e,t,r);{const o=this.splitOffRightSide();let a=this;return i>this.keys.length&&(i-=this.keys.length,a=o),a.insertInLeaf(i,e,t,r),o}}else return n!==!1&&(t!==void 0&&this.reifyValues(),this.keys[i]=e,this.values[i]=t),!1}reifyValues(){return this.values===H?this.values=this.values.slice(0,this.keys.length):this.values}insertInLeaf(e,t,n,r){if(this.keys.splice(e,0,t),this.values===H){for(;H.length<r._maxNodeSize;)H.push(void 0);if(n===void 0)return!0;this.values=H.slice(0,this.keys.length-1)}return this.values.splice(e,0,n),!0}takeFromRight(e){let t=this.values;e.values===H?t!==H&&t.push(void 0):(t=this.reifyValues(),t.push(e.values.shift())),this.keys.push(e.keys.shift())}takeFromLeft(e){let t=this.values;e.values===H?t!==H&&t.unshift(void 0):(t=this.reifyValues(),t.unshift(e.values.pop())),this.keys.unshift(e.keys.pop())}splitOffRightSide(){const e=this.keys.length>>1,t=this.keys.splice(e),n=this.values===H?H:this.values.splice(e);return new st(t,n)}forRange(e,t,n,r,i,o,a){const c=i._compare;let l,u;if(t===e){if(!n||(u=(l=this.indexOf(e,-1,c))+1,l<0))return o}else l=this.indexOf(e,0,c),u=this.indexOf(t,-1,c),u<0?u=~u:n===!0&&u++;const h=this.keys,p=this.values;if(a!==void 0)for(let f=l;f<u;f++){const d=h[f],y=a(d,p[f],o++);if(y!==void 0){if(r===!0){if(d!==h[f]||this.isShared===!0)throw new Error("BTree illegally changed or cloned in editRange");y.delete?(this.keys.splice(f,1),this.values!==H&&this.values.splice(f,1),i._size--,f--,u--):y.hasOwnProperty("value")&&(p[f]=y.value)}if(y.break!==void 0)return y}}else o+=u-l;return o}mergeSibling(e,t){if(this.keys.push.apply(this.keys,e.keys),this.values===H){if(e.values===H)return;this.values=this.values.slice(0,this.keys.length)}this.values.push.apply(this.values,e.reifyValues())}}class ms extends st{constructor(e,t){if(!t){t=[];for(let n=0;n<e.length;n++)t[n]=e[n].maxKey()}super(t),this.children=e}minKey(){return this.children[0].minKey()}minPair(e){return this.children[0].minPair(e)}maxPair(e){return this.children[this.children.length-1].maxPair(e)}get(e,t,n){const r=this.indexOf(e,0,n._compare),i=this.children;return r<i.length?i[r].get(e,t,n):void 0}getPairOrNextLower(e,t,n,r){const i=this.indexOf(e,0,t),o=this.children;if(i>=o.length)return this.maxPair(r);const a=o[i].getPairOrNextLower(e,t,n,r);return a===void 0&&i>0?o[i-1].maxPair(r):a}getPairOrNextHigher(e,t,n,r){const i=this.indexOf(e,0,t),o=this.children,a=o.length;if(i>=a)return;const c=o[i].getPairOrNextHigher(e,t,n,r);return c===void 0&&i<a-1?o[i+1].minPair(r):c}set(e,t,n,r){const i=this.children,o=r._maxNodeSize,a=r._compare;let c=Math.min(this.indexOf(e,0,a),i.length-1),l=i[c];if(l.isShared&&(i[c]=l=l.clone()),l.keys.length>=o){let h;c>0&&(h=i[c-1]).keys.length<o&&a(l.keys[0],e)<0?(h.isShared&&(i[c-1]=h=h.clone()),h.takeFromRight(l),this.keys[c-1]=h.maxKey()):(h=i[c+1])!==void 0&&h.keys.length<o&&a(l.maxKey(),e)<0&&(h.isShared&&(i[c+1]=h=h.clone()),h.takeFromLeft(l),this.keys[c]=i[c].maxKey())}const u=l.set(e,t,n,r);if(u===!1)return!1;if(this.keys[c]=l.maxKey(),u===!0)return!0;if(this.keys.length<o)return this.insert(c+1,u),!0;{const h=this.splitOffRightSide();let p=this;return a(u.maxKey(),this.maxKey())>0&&(p=h,c-=this.keys.length),p.insert(c+1,u),h}}insert(e,t){this.children.splice(e,0,t),this.keys.splice(e,0,t.maxKey())}splitOffRightSide(){const e=this.children.length>>1;return new ms(this.children.splice(e),this.keys.splice(e))}takeFromRight(e){this.keys.push(e.keys.shift()),this.children.push(e.children.shift())}takeFromLeft(e){this.keys.unshift(e.keys.pop()),this.children.unshift(e.children.pop())}forRange(e,t,n,r,i,o,a){const c=i._compare,l=this.keys,u=this.children;let h=this.indexOf(e,0,c),p=h;const f=Math.min(t===e?h:this.indexOf(t,0,c),l.length-1);if(r){if(p<=f)try{for(;p<=f;p++){u[p].isShared&&(u[p]=u[p].clone());const d=u[p].forRange(e,t,n,r,i,o,a);if(l[p]=u[p].maxKey(),typeof d!="number")return d;o=d}}finally{const d=i._maxNodeSize>>1;for(h>0&&h--,p=f;p>=h;p--)u[p].keys.length<=d&&(u[p].keys.length!==0?this.tryMerge(p,i._maxNodeSize):(l.splice(p,1),u.splice(p,1)));u.length!==0&&u[0].keys.length===0&&Xo(!1,"emptiness bug")}}else for(;p<=f;p++){const d=u[p].forRange(e,t,n,r,i,o,a);if(typeof d!="number")return d;o=d}return o}tryMerge(e,t){const n=this.children;return e>=0&&e+1<n.length&&n[e].keys.length+n[e+1].keys.length<=t?(n[e].isShared&&(n[e]=n[e].clone()),n[e].mergeSibling(n[e+1],t),n.splice(e+1,1),this.keys.splice(e+1,1),this.keys[e]=n[e].maxKey(),!0):!1}mergeSibling(e,t){const n=this.keys.length;this.keys.push.apply(this.keys,e.keys);const r=e.children;if(this.children.push.apply(this.children,r),e.isShared&&!this.isShared)for(const i of r)i.isShared=!0;this.tryMerge(n-1,t)}}const H=[],Yo={delete:!0},Zo=()=>Yo,Kt=(function(){const s=new st;return s.isShared=!0,s})(),on=[];function Xo(s,...e){throw e.unshift("B+ tree"),new Error(e.join(" "))}function Tn(){const s=new Map;function e(t){const n=t.join(".");if(s.has(n))return s.get(n);const r=new Proxy({},{get(i,o,a){if(o==="__refProxy")return!0;if(o==="__path")return t;if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(i,o,a);const c=[...t,String(o)];return e(c)},has(i,o){return o==="__refProxy"||o==="__path"||o==="__type"?!0:Reflect.has(i,o)},ownKeys(i){return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,o){return o==="__refProxy"||o==="__path"||o==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(i,o)}});return s.set(n,r),r}return e([])}function Re(s){const e=new Map;let t=0;function n(i){const o=i.join(".");if(e.has(o))return e.get(o);const a=new Proxy({},{get(c,l,u){if(l==="__refProxy")return!0;if(l==="__path")return i;if(l==="__type")return;if(typeof l=="symbol")return Reflect.get(c,l,u);const h=[...i,String(l)];return n(h)},has(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?!0:Reflect.has(c,l)},ownKeys(c){const l=++t,u=`__SPREAD_SENTINEL__${i.join(".")}__${l}`;return Object.prototype.hasOwnProperty.call(c,u)||Object.defineProperty(c,u,{enumerable:!0,configurable:!0,value:!0}),Reflect.ownKeys(c)},getOwnPropertyDescriptor(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(c,l)}});return e.set(o,a),a}return new Proxy({},{get(i,o,a){if(o==="__refProxy")return!0;if(o==="__path")return[];if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(i,o,a);const c=String(o);if(s.includes(c))return n([c])},has(i,o){return o==="__refProxy"||o==="__path"||o==="__type"||typeof o=="string"&&s.includes(o)?!0:Reflect.has(i,o)},ownKeys(i){return[...s,"__refProxy","__path","__type"]},getOwnPropertyDescriptor(i,o){if(o==="__refProxy"||o==="__path"||o==="__type")return{enumerable:!1,configurable:!0};if(typeof o=="string"&&s.includes(o))return{enumerable:!0,configurable:!0}}})}function an(s){const e=Re(s),t=new Map;function n(i){const o=i.join(".");if(t.has(o))return t.get(o);const a=new Proxy({},{get(c,l,u){if(l==="__refProxy")return!0;if(l==="__path")return["$selected",...i];if(l==="__type")return;if(typeof l=="symbol")return Reflect.get(c,l,u);const h=[...i,String(l)];return n(h)},has(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?!0:Reflect.has(c,l)},ownKeys(c){return Reflect.ownKeys(c)},getOwnPropertyDescriptor(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(c,l)}});return t.set(o,a),a}const r=n([]);return new Proxy(e,{get(i,o,a){return o==="$selected"?r:Reflect.get(i,o,a)},has(i,o){return o==="$selected"?!0:Reflect.has(i,o)},ownKeys(i){return[...Reflect.ownKeys(i),"$selected"]},getOwnPropertyDescriptor(i,o){return o==="$selected"?{enumerable:!0,configurable:!0,value:r}:Reflect.getOwnPropertyDescriptor(i,o)}})}function F(s){return ea(s)?new Z(s.__path):s&&typeof s=="object"&&"type"in s&&(s.type==="func"||s.type==="ref"||s.type==="val"||s.type==="agg")?s:new X(s)}function ea(s){return s&&typeof s=="object"&&s.__refProxy===!0}function qt(s,e){return new ne("eq",[F(s),F(e)])}function cn(s,e){return new ne("gt",[F(s),F(e)])}function ta(s,e){return new ne("gte",[F(s),F(e)])}function Wt(s,e){return new ne("lt",[F(s),F(e)])}function Gt(s,e,...t){const n=[s,e,...t];return new ne("and",n.map(r=>F(r)))}function sa(s,e,...t){const n=[s,e,...t];return new ne("or",n.map(r=>F(r)))}function na(s,e){return new ne("in",[F(s),F(e)])}function Ml(s,e){return new ne("ilike",[F(s),F(e)])}class ra{constructor(e,t,n,r){this.lookupCount=0,this.totalLookupTime=0,this.lastUpdated=new Date,this.id=e,this.expression=t,this.compareOptions=ps,this.name=n,this.initialize(r)}supports(e){return this.supportedOperations.has(e)}matchesField(e){return this.expression.type==="ref"&&this.expression.path.length===e.length&&this.expression.path.every((t,n)=>t===e[n])}matchesCompareOptions(e){const t={...this.compareOptions,direction:void 0},n={...e,direction:void 0};return le(t,n)}matchesDirection(e){return this.compareOptions.direction===e}getStats(){return{entryCount:this.keyCount,lookupCount:this.lookupCount,averageLookupTime:this.lookupCount>0?this.totalLookupTime/this.lookupCount:0,lastUpdated:this.lastUpdated}}evaluateIndexExpression(e){return ds(this.expression)(e)}trackLookup(e){const t=performance.now()-e;this.lookupCount++,this.totalLookupTime+=t}updateTimestamp(){this.lastUpdated=new Date}}class Ht extends ra{constructor(e,t,n,r){super(e,t,n,r),this.supportedOperations=new Set(["eq","gt","gte","lt","lte","in"]),this.valueMap=new Map,this.indexedKeys=new Set,this.compareFn=$t,this.compareFn=r?.compareFn??$t,r?.compareOptions&&(this.compareOptions=r.compareOptions),this.orderedEntries=new Jo(this.compareFn)}initialize(e){}add(e,t){let n;try{n=this.evaluateIndexExpression(t)}catch(i){throw new Error(`Failed to evaluate index expression for key ${e}: ${i}`)}const r=ye(n);if(this.valueMap.has(r))this.valueMap.get(r).add(e);else{const i=new Set([e]);this.valueMap.set(r,i),this.orderedEntries.set(r,void 0)}this.indexedKeys.add(e),this.updateTimestamp()}remove(e,t){let n;try{n=this.evaluateIndexExpression(t)}catch(i){console.warn(`Failed to evaluate index expression for key ${e} during removal:`,i);return}const r=ye(n);if(this.valueMap.has(r)){const i=this.valueMap.get(r);i.delete(e),i.size===0&&(this.valueMap.delete(r),this.orderedEntries.delete(r))}this.indexedKeys.delete(e),this.updateTimestamp()}update(e,t,n){this.remove(e,t),this.add(e,n)}build(e){this.clear();for(const[t,n]of e)this.add(t,n)}clear(){this.orderedEntries.clear(),this.valueMap.clear(),this.indexedKeys.clear(),this.updateTimestamp()}lookup(e,t){const n=performance.now();let r;switch(e){case"eq":r=this.equalityLookup(t);break;case"gt":r=this.rangeQuery({from:t,fromInclusive:!1});break;case"gte":r=this.rangeQuery({from:t,fromInclusive:!0});break;case"lt":r=this.rangeQuery({to:t,toInclusive:!1});break;case"lte":r=this.rangeQuery({to:t,toInclusive:!0});break;case"in":r=this.inArrayLookup(t);break;default:throw new Error(`Operation ${e} not supported by BTreeIndex`)}return this.trackLookup(n),r}get keyCount(){return this.indexedKeys.size}equalityLookup(e){const t=ye(e);return new Set(this.valueMap.get(t)??[])}rangeQuery(e={}){const{from:t,to:n,fromInclusive:r=!0,toInclusive:i=!0}=e,o=new Set,a=ye(t),c=ye(n),l=a??this.orderedEntries.minKey(),u=c??this.orderedEntries.maxKey();return this.orderedEntries.forRange(l,u,i,(h,p)=>{if(!r&&this.compareFn(h,t)===0)return;const f=this.valueMap.get(h);f&&f.forEach(d=>o.add(d))}),o}rangeQueryReversed(e={}){const{from:t,to:n,fromInclusive:r=!0,toInclusive:i=!0}=e;return this.rangeQuery({from:n??this.orderedEntries.maxKey(),to:t??this.orderedEntries.minKey(),fromInclusive:i,toInclusive:r})}takeInternal(e,t,n,r,i=!1){const o=new Set,a=[];let c,l=ye(n);for(;(c=t(l))!==void 0&&a.length<e;){l=c[0];const u=this.valueMap.get(l);if(u&&u.size>0){const h=Array.from(u).sort(vt);i&&h.reverse();for(const p of h){if(a.length>=e)break;!o.has(p)&&(r?.(p)??!0)&&(a.push(p),o.add(p))}}}return a}take(e,t,n){const r=i=>this.orderedEntries.nextHigherPair(i);return this.takeInternal(e,r,t,n)}takeReversed(e,t,n){const r=i=>this.orderedEntries.nextLowerPair(i);return this.takeInternal(e,r,t,n,!0)}inArrayLookup(e){const t=new Set;for(const n of e){const r=ye(n),i=this.valueMap.get(r);i&&i.forEach(o=>t.add(o))}return t}get indexedKeysSet(){return this.indexedKeys}get orderedEntriesArray(){return this.orderedEntries.keysArray().map(e=>[e,this.valueMap.get(e)??new Set])}get orderedEntriesArrayReversed(){return this.takeReversed(this.orderedEntries.size).map(e=>[e,this.valueMap.get(e)??new Set])}get valueMapData(){return this.valueMap}}function Pn(s){return s.config.autoIndex==="eager"}function kt(s,e,t,n,r){if(!Pn(t))return;const i=n??{...ps,...t.compareOptions};if(!Array.from(t.indexes.values()).find(a=>a.matchesField(e)&&a.matchesCompareOptions(i)))try{t.createIndex(a=>{let c=a;for(const l of e)c=c[l];return c},{name:`auto:${e.join(".")}`,indexType:Ht,options:r?{compareFn:r,compareOptions:i}:{}})}catch(a){console.warn(`${t.id?`[${t.id}] `:""}Failed to create auto-index for field path "${e.join(".")}":`,a)}}function ia(s,e){if(!Pn(e))return;const t=oa(s);for(const{fieldName:n,fieldPath:r}of t)kt(n,r,e)}function oa(s){const e=[];function t(n){if(n.type!=="func")return;const r=n;if(r.name==="and"){for(const l of r.args)t(l);return}if(!["eq","gt","gte","lt","lte","in"].includes(r.name)||r.args.length<1||r.args[0].type!=="ref")return;const a=r.args[0].path;if(a.length===0)return;const c=a.join("_");e.push({fieldName:c,fieldPath:a})}return t(s),e}const{sum:aa,count:ca,avg:la,min:ua,max:ha}=_o;function da(s,e){const t=new Map,n=[...s];if(!e)return{selectToGroupByIndex:t,groupByExpressions:n};for(const[r,i]of Object.entries(e)){if(i.type==="agg")continue;const o=n.findIndex(a=>bt(i,a));if(o===-1)throw new pi(r);t.set(r,o)}return{selectToGroupByIndex:t,groupByExpressions:n}}function ln(s,e,t,n,r){if(e.length===0){const l={};if(n){for(const[h,p]of Object.entries(n))if(p.type==="agg"){const f=p;l[h]=un(f)}}const u=()=>({__singleGroup:!0});if(s=s.pipe(Ys(u,l)),s=s.pipe(Y(([,h])=>{const f={...h.$selected||{}};if(n)for(const[d,y]of Object.entries(n))y.type==="agg"&&(f[d]=h[d]);return["single_group",{...h,$selected:f}]})),t&&t.length>0)for(const h of t){const p=Fs(h),f=St(p,n||{},"$selected"),d=ee(f);s=s.pipe(Se(([,y])=>{const g={$selected:y.$selected};return De(d(g))}))}if(r&&r.length>0)for(const h of r)s=s.pipe(Se(([,p])=>{const f={$selected:p.$selected};return De(h(f))}));return s}const i=da(e,n),o=e.map(l=>ee(l)),a=([,l])=>{const u={...l};delete u.$selected;const h={};for(let p=0;p<e.length;p++){const f=o[p],d=f(u);h[`__key_${p}`]=d}return h},c={};if(n){for(const[l,u]of Object.entries(n))if(u.type==="agg"){const h=u;c[l]=un(h)}}if(s=s.pipe(Ys(a,c)),s=s.pipe(Y(([,l])=>{const u=l.$selected||{},h={};if(n)for(const[f,d]of Object.entries(n))if(d.type!=="agg"){const y=i.selectToGroupByIndex.get(f);y!==void 0?h[f]=l[`__key_${y}`]:h[f]=u[f]}else h[f]=l[f];else for(let f=0;f<e.length;f++)h[`__key_${f}`]=l[`__key_${f}`];let p;if(e.length===1)p=l.__key_0;else{const f=[];for(let d=0;d<e.length;d++)f.push(l[`__key_${d}`]);p=En(f)}return[p,{...l,$selected:h}]})),t&&t.length>0)for(const l of t){const u=Fs(l),h=St(u,n||{}),p=ee(h);s=s.pipe(Se(([,f])=>{const d={$selected:f.$selected};return p(d)}))}if(r&&r.length>0)for(const l of r)s=s.pipe(Se(([,u])=>{const h={$selected:u.$selected};return De(l(h))}));return s}function bt(s,e){if(!s||!e||s.type!==e.type)return!1;switch(s.type){case"ref":return!s.path||!e.path||s.path.length!==e.path.length?!1:s.path.every((t,n)=>t===e.path[n]);case"val":return s.value===e.value;case"func":return s.name===e.name&&s.args?.length===e.args?.length&&(s.args||[]).every((t,n)=>bt(t,e.args[n]));case"agg":return s.name===e.name&&s.args?.length===e.args?.length&&(s.args||[]).every((t,n)=>bt(t,e.args[n]));default:return!1}}function un(s){const e=ee(s.args[0]),t=([,i])=>{const o=e(i);return typeof o=="number"?o:o!=null?Number(o):0},n=([,i])=>{const o=e(i);return typeof o=="number"||typeof o=="string"||typeof o=="bigint"||o instanceof Date?o:o!=null?Number(o):0},r=([,i])=>e(i);switch(s.name.toLowerCase()){case"sum":return aa(t);case"count":return ca(r);case"avg":return la(t);case"min":return ua(n);case"max":return ha(n);default:throw new yi(s.name)}}function St(s,e,t="$selected"){switch(s.type){case"agg":{const n=s;for(const[r,i]of Object.entries(e))if(i.type==="agg"&&fa(n,i))return new Z([t,r]);throw new gi(n.name)}case"func":{const n=s,r=n.args.map(i=>St(i,e));return new ne(n.name,r)}case"ref":return s;case"val":return s;default:throw new mi(s.type)}}function fa(s,e){return s.name===e.name&&s.args.length===e.args.length&&s.args.every((t,n)=>bt(t,e.args[n]))}function pa(s,e,t,n,r,i,o,a,c){const l=t.map(d=>{const y=St(d.expression,n,"$selected");return{compiledExpression:ee(y),compareOptions:Qt(d,r)}}),u=d=>{const y=d;return t.length>1?l.map(g=>g.compiledExpression(y)):t.length===1?l[0].compiledExpression(y):null},h=(d,y)=>{if(t.length>1){const g=d,m=y;for(let w=0;w<t.length;w++){const S=l[w],O=wt(S.compareOptions)(g[w],m[w]);if(O!==0)return O}return g.length-m.length}if(t.length===1){const g=l[0];return wt(g.compareOptions)(d,y)}return $t(d,y)};let p,f;if(a){let d,y,g,m=s.from.alias;const w=t[0],S=w.expression;if(S.type==="ref"){const v=et(s,S,r);if(v){y=v.collection;const O=v.path[0],I=Qt(w,y);O&&kt(O,v.path,y,I,h),g=ee(new Z(v.path),!0),d=ot(y,v.path,I),d?.supports("gt")||(d=void 0),m=S.path.length>1?String(S.path[0]):s.from.alias}}if(g){const O=t.every(b=>b.expression.type==="ref")?t.map(b=>{const E=b.expression,j=et(s,E,r);return ee(j?new Z(j.path):b.expression,!0)}):void 0;f={alias:m,offset:c??0,limit:a,comparator:(b,E)=>{if(t.length===1){const j=b&&g(b),B=E&&g(E);return h(j,B)}if(O){const j=B=>B&&O.map(Q=>Q(B));return h(j(b),j(E))}return 0},valueExtractorForRawRow:b=>{if(t.length===1)return g(b);if(O)return O.map(E=>E(b))},firstColumnValueExtractor:g,index:d,orderBy:t};const x=y?.id??r.id;i[x]=f,d&&(p=b=>{i[x].dataNeeded=()=>{const E=b();return Math.max(0,f.limit-E)}})}}return e.pipe(Qo(u,{limit:a,offset:c,comparator:h,setSizeCallback:p,setWindowFn:d=>{o(y=>{d(y),f&&(f.offset=y.offset??f.offset,f.limit=y.limit??f.limit)})}}))}function Qt(s,e){return s.compareOptions.stringSort!==void 0?s.compareOptions:{...e.compareOptions,direction:s.compareOptions.direction,nulls:s.compareOptions.nulls}}function ya(s,e={}){const t=n=>{const r=[];for(const[i,o]of s.entries())(n?.(o)??!0)&&r.push({type:"insert",key:i,value:o});return r};if(e.limit!==void 0&&!e.orderBy)throw new Error("limit cannot be used without orderBy");if(e.orderBy){const n=e.where?Ze(e.where):void 0,r=ma(s,e.orderBy,e.limit,n,e.optimizedOnly);if(r===void 0)return;const i=[];for(const o of r){const a=s.get(o);a!==void 0&&i.push({type:"insert",key:o,value:a})}return i}if(!e.where)return t();try{const n=e.where,r=Ki(n,s);if(r.canOptimize){const i=[];for(const o of r.matchingKeys){const a=s.get(o);a!==void 0&&i.push({type:"insert",key:o,value:a})}return i}else{if(e.optimizedOnly)return;const i=Ze(n);return t(i)}}catch(n){console.warn(`${s.id?`[${s.id}] `:""}Error processing where clause, falling back to full scan:`,n);const r=Ze(e.where);return e.optimizedOnly?void 0:t(r)}}function Ze(s){const e=ds(s);return t=>{try{const n=e(t);return De(n)}catch{return!1}}}function ga(s,e){const t=Ze(e.whereExpression);return n=>{const r=[];for(const i of n)if(i.type==="insert")t(i.value)&&r.push(i);else if(i.type==="update"){const o=t(i.value),a=i.previousValue?t(i.previousValue):!1;o&&a?r.push(i):o&&!a?r.push({...i,type:"insert"}):!o&&a&&r.push({...i,type:"delete",value:i.previousValue})}else t(i.value)&&r.push(i);(r.length>0||n.length===0)&&s(r)}}function ma(s,e,t,n,r){if(e.length===1){const c=e[0],l=c.expression;if(l.type==="ref"){const h=l.path,p=Qt(c,s);kt(h[0],h,s,p);const f=ot(s,h,p);if(f&&f.supports("gt")){const d=y=>{const g=s.get(y);return g===void 0?!1:n?.(g)??!0};return f.take(t??f.keyCount,void 0,d)}}}if(r)return;const i=[];for(const[c,l]of s.entries())(n?.(l)??!0)&&i.push({key:c,value:l});const o=(c,l)=>{for(const u of e){const h=wt(u.compareOptions),p=hn(c.value,u.expression),f=hn(l.value,u.expression),d=h(p,f);if(d!==0)return d}return 0};i.sort(o);const a=i.map(c=>c.key);return t!==void 0?a.slice(0,t):a}function hn(s,e){if(e.type==="ref"){const t=e;let n=s;for(const r of t.path)n=n?.[r];return n}else return e.type==="val"?e.value:ds(e)(s)}class dn{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,r=this.sortedKeys.length;if(!this.comparator){for(;n<r;){const i=Math.floor((n+r)/2),o=this.sortedKeys[i],a=vt(e,o);if(a<0)r=i;else if(a>0)n=i+1;else return i}return n}for(;n<r;){const i=Math.floor((n+r)/2),o=this.sortedKeys[i],a=this.map.get(o),c=this.comparator(t,a);if(c<0)r=i;else if(c>0)n=i+1;else{const l=vt(e,o);if(l<0)r=i;else if(l>0)n=i+1;else return i}}return n}set(e,t){if(this.map.has(e)){const r=this.map.get(e),i=this.indexOf(e,r);this.sortedKeys.splice(i,1)}const n=this.indexOf(e,t);return this.sortedKeys.splice(n,0,e),this.map.set(e,t),this}get(e){return this.map.get(e)}delete(e){if(this.map.has(e)){const t=this.map.get(e),n=this.indexOf(e,t);return this.sortedKeys.splice(n,1),this.map.delete(e)}return!1}has(e){return this.map.has(e)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(const e of this.sortedKeys)yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(const e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(const t of this.sortedKeys)e(this.map.get(t),t,this.map)}}class wa{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.commitPendingTransactions=()=>{let t=!1;for(const a of this.transactions.values())if(a.state==="persisting"){t=!0;break}const{committedSyncedTransactions:n,uncommittedSyncedTransactions:r,hasTruncateSync:i,hasImmediateSync:o}=this.pendingSyncedTransactions.reduce((a,c)=>(c.committed?(a.committedSyncedTransactions.push(c),c.truncate&&(a.hasTruncateSync=!0),c.immediate&&(a.hasImmediateSync=!0)):a.uncommittedSyncedTransactions.push(c),a),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!t||i||o){this.isCommittingSyncTransactions=!0;const a=i?n.find(f=>f.truncate)?.optimisticSnapshot:null,c=new Set;for(const f of n)for(const d of f.operations)c.add(d.key);let l=this.preSyncVisibleState;if(l.size===0){l=new Map;for(const f of c){const d=this.get(f);d!==void 0&&l.set(f,d)}}const u=[],h=this.config.sync.rowUpdateMode||"partial";for(const f of n){if(f.truncate){const d=new Set([...this.syncedData.keys(),...a?.upserts.keys()||[]]);for(const y of d){if(a?.deletes.has(y))continue;const g=a?.upserts.get(y)||this.syncedData.get(y);g!==void 0&&u.push({type:"delete",key:y,value:g})}this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear();for(const y of c)l.delete(y);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(const d of f.operations){const y=d.key;switch(this.syncedKeys.add(y),d.type){case"insert":this.syncedMetadata.set(y,d.metadata);break;case"update":this.syncedMetadata.set(y,Object.assign({},this.syncedMetadata.get(y),d.metadata));break;case"delete":this.syncedMetadata.delete(y);break}switch(d.type){case"insert":this.syncedData.set(y,d.value);break;case"update":{if(h==="partial"){const g=Object.assign({},this.syncedData.get(y),d.value);this.syncedData.set(y,g)}else this.syncedData.set(y,d.value);break}case"delete":this.syncedData.delete(y);break}}}if(i){const f=new Set;for(const g of n)for(const m of g.operations)(m.type==="insert"||m.type==="update")&&f.add(m.key);const d=new Map(a.upserts),y=new Set(a.deletes);for(const[g,m]of d)if(!y.has(g))if(f.has(g)){let w=!1;for(let S=u.length-1;S>=0;S--){const v=u[S];if(v.key===g&&v.type==="insert"){v.value=m,w=!0;break}}w||u.push({type:"insert",key:g,value:m})}else u.push({type:"insert",key:g,value:m});if(u.length>0&&y.size>0){const g=[];for(const m of u)m.type==="insert"&&y.has(m.key)||g.push(m);u.length=0,u.push(...g)}this.lifecycle.status!=="ready"&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,i&&a){for(const[f,d]of a.upserts)this.optimisticUpserts.set(f,d);for(const f of a.deletes)this.optimisticDeletes.add(f)}for(const f of this.transactions.values())if(!["completed","failed"].includes(f.state)){for(const d of f.mutations)if(this.isThisCollection(d.collection)&&d.optimistic)switch(d.type){case"insert":case"update":this.optimisticUpserts.set(d.key,d.modified),this.optimisticDeletes.delete(d.key);break;case"delete":this.optimisticUpserts.delete(d.key),this.optimisticDeletes.add(d.key);break}}const p=new Map;for(const f of this.transactions.values())if(f.state==="completed")for(const d of f.mutations)d.optimistic&&this.isThisCollection(d.collection)&&c.has(d.key)&&p.set(d.key,{type:d.type,value:d.modified});for(const f of c){const d=l.get(f),y=this.get(f),g=p.get(f);let m=!1;g&&(g.type==="delete"&&d!==void 0&&y===void 0&&le(g.value,d)||y!==void 0&&le(g.value,y))&&(m=!0),m||(d===void 0&&y!==void 0?u.push({type:"insert",key:f,value:y}):d!==void 0&&y===void 0?u.push({type:"delete",key:f,value:d}):d!==void 0&&y!==void 0&&!le(d,y)&&u.push({type:"update",key:f,value:y,previousValue:d}))}this.size=this.calculateSize(),u.length>0&&this.indexes.updateIndexes(u),this.changes.emitEvents(u,!0),this.pendingSyncedTransactions=r,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0)}},this.config=e,this.transactions=new dn((t,n)=>t.compareCreatedAt(n)),this.syncedData=new dn(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}get(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;if(!t.has(e))return n.has(e)?n.get(e):r.get(e)}has(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;return t.has(e)?!1:n.has(e)?!0:r.has(e)}*keys(){const{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(const r of e.keys())t.has(r)||(yield r);for(const r of n.keys())!e.has(r)&&!t.has(r)&&(yield r)}*values(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){for(const[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(const[n,r]of this.entries())e(r,n,t++)}map(e){const t=[];let n=0;for(const[r,i]of this.entries())t.push(e(i,r,n++));return t}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;const t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes);this.optimisticUpserts.clear(),this.optimisticDeletes.clear();const r=[];for(const a of this.transactions.values())["completed","failed"].includes(a.state)||r.push(a);for(const a of r)for(const c of a.mutations)if(this.isThisCollection(c.collection)&&c.optimistic)switch(c.type){case"insert":case"update":this.optimisticUpserts.set(c.key,c.modified),this.optimisticDeletes.delete(c.key);break;case"delete":this.optimisticUpserts.delete(c.key),this.optimisticDeletes.add(c.key);break}this.size=this.calculateSize();const i=[];this.collectOptimisticChanges(t,n,i);const o=i.filter(a=>!!(!this.recentlySyncedKeys.has(a.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){const a=new Set;for(const l of this.pendingSyncedTransactions)for(const u of l.operations)a.add(u.key);const c=o.filter(l=>!(l.type==="delete"&&a.has(l.key)&&!r.some(h=>h.mutations.some(p=>this.isThisCollection(p.collection)&&p.key===l.key))));c.length>0&&this.indexes.updateIndexes(c),this.changes.emitEvents(c,e)}else o.length>0&&this.indexes.updateIndexes(o),this.changes.emitEvents(o,e)}calculateSize(){const e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(r=>this.syncedData.has(r)&&!this.optimisticUpserts.has(r)).length,n=Array.from(this.optimisticUpserts.keys()).filter(r=>!this.syncedData.has(r)).length;return e-t+n}collectOptimisticChanges(e,t,n){const r=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(const i of r){const o=this.get(i),a=this.getPreviousValue(i,e,t);a!==void 0&&o===void 0?n.push({type:"delete",key:i,value:a}):a===void 0&&o!==void 0?n.push({type:"insert",key:i,value:o}):a!==void 0&&o!==void 0&&a!==o&&n.push({type:"update",key:i,value:o,previousValue:a})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}scheduleTransactionCleanup(e){if(e.state==="completed"){this.transactions.delete(e.id);return}e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;const e=new Set;for(const t of this.pendingSyncedTransactions)for(const n of t.operations)e.add(n.key);for(const t of e)this.recentlySyncedKeys.add(t);for(const t of e)if(!this.preSyncVisibleState.has(t)){const n=this.get(t);n!==void 0&&this.preSyncVisibleState.set(t,n)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncedData.clear(),this.syncedMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}}class Dn{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}once(e,t){const n=this.on(e,r=>{t(r),n()});return n}off(e,t){this.listeners.get(e)?.delete(t)}waitFor(e,t){return new Promise((n,r)=>{let i;const o=this.on(e,a=>{i&&(clearTimeout(i),i=void 0),n(a),o()});t&&(i=setTimeout(()=>{i=void 0,o(),r(new Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.listeners.get(e)?.forEach(n=>{try{n(t)}catch(r){queueMicrotask(()=>{throw r})}})}clearListeners(){this.listeners.clear()}}function va(s,e){if(e.length===0||s.length===0)return;if(s.length===1){const{expression:n,compareOptions:r}=s[0];return(r.direction==="asc"?cn:Wt)(n,new X(e[0]))}const t=[];for(let n=0;n<s.length&&n<e.length;n++){const r=s[n],i=e[n],o=[];for(let l=0;l<n;l++){const u=s[l],h=e[l];o.push(qt(u.expression,new X(h)))}const c=(r.compareOptions.direction==="asc"?cn:Wt)(r.expression,new X(i));if(o.length===0)t.push(c);else{const l=[...o,c];t.push(l.reduce((u,h)=>Gt(u,h)))}}return t.length===1?t[0]:t.reduce((n,r)=>sa(n,r))}class ba extends Dn{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.loadedSubsets=[],this.sentKeys=new Set,this.limitedSnapshotRowCount=0,this._status="ready",this.pendingLoadSubsetPromises=new Set,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches=new Set,n.onUnsubscribe&&this.on("unsubscribed",i=>n.onUnsubscribe(i)),n.whereExpression&&ia(n.whereExpression,this.collection);const r=i=>{t(i),this.trackSentKeys(i)};this.callback=r,this.filteredCallback=n.whereExpression?ga(this.callback,n):this.callback,this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){const e=[...this.loadedSubsets],t=this.collection._sync.syncLoadSubsetFn!==null;if(e.length===0||!t){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[];return}this.isBufferingForTruncate=!0,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[],queueMicrotask(()=>{if(this.isBufferingForTruncate){for(const n of e){const r=this.collection._sync.loadSubset(n);this.loadedSubsets.push(n),this.trackLoadSubsetPromise(r),r instanceof Promise&&(this.pendingTruncateRefetches.add(r),r.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(r),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;const e=this.truncateBuffer.flat();e.length>0&&this.filteredCallback(e),this.truncateBuffer=[]}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this._status===e)return;const t=this._status;this._status=e,this.emitInner("status:change",{type:"status:change",subscription:this,previousStatus:t,status:e});const n=`status:${e}`;this.emitInner(n,{type:n,subscription:this,previousStatus:t,status:e})}trackLoadSubsetPromise(e){e instanceof Promise&&(this.pendingLoadSubsetPromises.add(e),this.setStatus("loadingSubset"),e.finally(()=>{this.pendingLoadSubsetPromises.delete(e),this.pendingLoadSubsetPromises.size===0&&this.setStatus("ready")}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(e){const t=this.filterAndFlipChanges(e);this.isBufferingForTruncate?t.length>0&&this.truncateBuffer.push(t):this.filteredCallback(t)}requestSnapshot(e){if(this.loadedInitialState)return!1;const t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if("where"in e){const c=e.where;if(t.where){const l=t.where,u=Gt(l,c);t.where=u}else t.where=c}}else this.loadedInitialState=!0;const n={where:t.where,subscription:this,orderBy:e?.orderBy,limit:e?.limit},r=this.collection._sync.loadSubset(n);this.loadedSubsets.push(n),(e?.trackLoadSubsetPromise??!0)&&this.trackLoadSubsetPromise(r);const o=this.collection.currentStateAsChanges(t);if(o===void 0)return!1;const a=o.filter(c=>!this.sentKeys.has(c.key));for(const c of a)this.sentKeys.add(c.key);return this.snapshotSent=!0,this.callback(a),!0}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:r}){if(!t)throw new Error("limit is required");if(!this.orderByIndex)throw new Error("Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.");const o=n?.[0],a=this.orderByIndex,c=this.options.whereExpression,l=c?Ze(c):void 0,u=I=>{if(this.sentKeys.has(I))return!1;const _=this.collection.get(I);return _===void 0?!1:l?.(_)??!0};let h=o;const p=[];let f=[];if(o!==void 0){const{expression:I}=e[0],_=this.collection.currentStateAsChanges({where:qt(I,new X(o))});if(_){const x=_.map(E=>E.key).filter(E=>!this.sentKeys.has(E)&&u(E));f.push(...x);const b=a.take(t-f.length,o,u);f.push(...b)}else f=a.take(t,o,u)}else f=a.take(t,o,u);const d=()=>Math.max(t-p.length,0),y=()=>f.length===0,g=e[0].expression,m=g.type==="ref"?ee(new Z(g.path),!0):null;for(;d()>0&&!y();){const I=new Set;for(const _ of f){const x=this.collection.get(_);p.push({type:"insert",key:_,value:x}),h=m?m(x):x,I.add(_)}f=a.take(d(),h,u)}const w=this.limitedSnapshotRowCount;for(const I of p)this.sentKeys.add(I.key);this.callback(p),this.limitedSnapshotRowCount+=p.length,p.length>0&&(this.lastSentKey=p[p.length-1].key);let S;if(n!==void 0&&n.length>0){const I=va(e,n);if(I){const{expression:_}=e[0],x=n[0];let b;if(x instanceof Date){const E=new Date(x.getTime()+1);b=Gt(ta(_,new X(x)),Wt(_,new X(E)))}else b=qt(_,new X(x));S={whereFrom:I,whereCurrent:b,lastKey:this.lastSentKey}}}const v={where:c,limit:t,orderBy:e,cursor:S,offset:r??w,subscription:this},O=this.collection._sync.loadSubset(v);this.loadedSubsets.push(v),this.trackLoadSubsetPromise(O)}filterAndFlipChanges(e){if(this.loadedInitialState||this.skipFiltering)return e;const t=this.isBufferingForTruncate,n=[];for(const r of e){let i=r;if(this.sentKeys.has(r.key)){if(r.type==="insert")continue;r.type==="delete"&&this.sentKeys.delete(r.key)}else{if(r.type==="update")i={...r,type:"insert",previousValue:void 0};else if(r.type==="delete"&&!t)continue;this.sentKeys.add(r.key)}n.push(i)}return n}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering))for(const t of e)t.type==="delete"?this.sentKeys.delete(t.key):this.sentKeys.add(t.key)}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){this.truncateCleanup?.(),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear();for(const e of this.loadedSubsets)this.collection._sync.unloadSubset(e);this.loadedSubsets=[],this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),this.clearListeners()}}class Sa{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection}emitEmptyReadyEvent(){for(const e of this.changeSubscriptions)e.emitEvents([])}emitEvents(e,t=!1){if(this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let n=e;if(t&&(this.batchedEvents.length>0&&(n=[...this.batchedEvents,...e]),this.batchedEvents=[],this.shouldBatchEvents=!1),n.length!==0)for(const r of this.changeSubscriptions)r.emitEvents(n)}subscribeChanges(e,t={}){if(this.addSubscriber(),t.where&&t.whereExpression)throw new Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");const{where:n,...r}=t;let i=r.whereExpression;if(n){const a=Tn(),c=n(a);i=F(c)}const o=new ba(this.collection,e,{...r,whereExpression:i,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(o)}});return t.onStatusChange&&o.on("status:change",t.onStatusChange),t.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1}):t.includeInitialState===!1&&o.markAllStateAsSeen(),this.changeSubscriptions.add(o),o}addSubscriber(){const e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer(),(this.lifecycle.status==="cleaned-up"||this.lifecycle.status==="idle")&&this.sync.startSync(),this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){const e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new Or;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}}const xa=s=>setTimeout(()=>{s({didTimeout:!0,timeRemaining:()=>50})},0),Ca=s=>{clearTimeout(s)},Ia=typeof window<"u"&&"requestIdleCallback"in window?(s,e)=>window.requestIdleCallback(s,e):(s,e)=>xa(s),jt=typeof window<"u"&&"cancelIdleCallback"in window?s=>window.cancelIdleCallback(s):Ca;class Ea{constructor(e,t){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.gcTimeoutId=null,this.idleCallbackId=null,this.config=e,this.id=t}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)return;if(!{idle:["loading","error","cleaned-up"],loading:["ready","error","cleaned-up"],ready:["cleaned-up","error"],error:["cleaned-up","idle"],"cleaned-up":["loading","error"]}[e].includes(t))throw new Rr(e,t,this.id)}setStatus(e,t=!1){if(e==="ready"&&!t)throw new it(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);const n=this.status;this.status=e,e==="ready"&&!this.indexes.isIndexesResolved&&this.indexes.resolveAllIndexes().catch(r=>{console.warn(`${this.config.id?`[${this.config.id}] `:""}Failed to resolve indexes:`,r)}),this.events.emitStatusChange(e,n)}validateCollectionUsable(e){switch(this.status){case"error":throw new Er(e,this.id);case"cleaned-up":this.sync.startSync();break}}markReady(){if(this.validateStatusTransition(this.status,"ready"),this.status==="loading"){if(this.setStatus("ready",!0),!this.hasBeenReady){this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0);const e=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],e.forEach(t=>t())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){this.gcTimeoutId&&clearTimeout(this.gcTimeoutId);const e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||(this.gcTimeoutId=setTimeout(()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()},e))}cancelGCTimer(){this.gcTimeoutId&&(clearTimeout(this.gcTimeoutId),this.gcTimeoutId=null),this.idleCallbackId!==null&&(jt(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&jt(this.idleCallbackId),this.idleCallbackId=Ia(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){return!e||e.timeRemaining()>0||e.didTimeout?(this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),this.gcTimeoutId&&(clearTimeout(this.gcTimeoutId),this.gcTimeoutId=null),this.hasBeenReady=!1,this.onFirstReadyCallbacks=[],this.setStatus("cleaned-up"),this.events.cleanup(),!0):(this.scheduleIdleCleanup(),!1)}onFirstReady(e){if(this.hasBeenReady){e();return}this.onFirstReadyCallbacks.push(e)}cleanup(){this.idleCallbackId!==null&&(jt(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const ws=Symbol("liveQueryInternal");class Ra{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,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._events=e.events}startSync(){if(!(this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up")){this.lifecycle.setStatus("loading");try{const e=ka(this.config.sync.sync({collection:this.collection,begin:t=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,immediate:t?.immediate})},write:t=>{const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!n)throw new Ns;if(n.committed)throw new $s;let r;"key"in t?r=t.key:r=this.config.getKey(t.value);let i=t.type;if(t.type==="insert"){const a=this.state.syncedData.has(r),c=n.deletedKeys.has(r),l=n.truncate===!0;if(a&&!c&&!l){const u=this.state.syncedData.get(r);if(u!==void 0&&le(u,t.value))i="update";else{const f=this.config.utils[ws];throw new Tr(r,this.id,{hasCustomGetKey:f?.hasCustomGetKey??!1,hasJoins:f?.hasJoins??!1,hasDistinct:f?.hasDistinct??!1})}}}const o={...t,type:i,key:r};n.operations.push(o),i==="delete"&&n.deletedKeys.add(r)},commit:()=>{const t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new Wr;if(t.committed)throw new Gr;t.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{const t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new Ns;if(t.committed)throw new $s;t.operations=[],t.deletedKeys.clear(),t.truncate=!0,t.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}}}));if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode==="on-demand"&&!this.syncLoadSubsetFn)throw new rt(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(e){throw this.lifecycle.setStatus("error"),e}}}preload(){return this.preloadPromise?this.preloadPromise:(this.syncMode==="on-demand"&&console.warn(`${this.id?`[${this.id}] `:""}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`),this.preloadPromise=new Promise((e,t)=>{if(this.lifecycle.status==="ready"){e();return}if(this.lifecycle.status==="error"){t(new kr);return}if(this.lifecycle.onFirstReady(()=>{e()}),this.lifecycle.status==="idle"||this.lifecycle.status==="cleaned-up")try{this.startSync()}catch(n){t(n);return}}),this.preloadPromise)}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(e){const t=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),t&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:"start"}),e.finally(()=>{const n=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"})})}loadSubset(e){if(this.syncMode==="eager")return!0;if(this.syncLoadSubsetFn){const t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}cleanup(){try{this.syncCleanupFn&&(this.syncCleanupFn(),this.syncCleanupFn=null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){const t=new qs(this.id,e);throw t.cause=e,t.stack=e.stack,t}else throw new qs(this.id,e)})}this.preloadPromise=null}}function ka(s){if(typeof s=="function")return{cleanup:s};if(typeof s=="object")return s}function Kn(s){return typeof s=="function"&&s.prototype!==void 0&&s.prototype.constructor===s}async function Oa(s){return Kn(s)?s:await s()}class _a{constructor(e,t,n,r,i,o){this.id=e,this.expression=t,this.name=n,this.resolver=r,this.options=i,this.collectionEntries=o,this.indexPromise=null,this.resolvedIndex=null,Kn(this.resolver)&&(this.resolvedIndex=new this.resolver(this.id,this.expression,this.name,this.options),this.collectionEntries&&this.resolvedIndex.build(this.collectionEntries))}async resolve(){return this.resolvedIndex?this.resolvedIndex:(this.indexPromise||(this.indexPromise=this.createIndex()),this.resolvedIndex=await this.indexPromise,this.resolvedIndex)}isResolved(){return this.resolvedIndex!==null}getResolved(){if(!this.resolvedIndex)throw new Error(`Index ${this.id} has not been resolved yet. Ensure collection is synced.`);return this.resolvedIndex}getId(){return this.id}getName(){return this.name}getExpression(){return this.expression}async createIndex(){const e=await Oa(this.resolver);return new e(this.id,this.expression,this.name,this.options)}}class Aa{constructor(e,t){this.indexId=e,this.lazyIndex=t}get index(){return this.lazyIndex.getResolved()}get isReady(){return this.lazyIndex.isResolved()}async whenReady(){return await this.lazyIndex.resolve()}get id(){return this.indexId}get name(){return this.isReady?this.index.name:this.lazyIndex.getName()}get expression(){return this.lazyIndex.getExpression()}supports(e){return this.index.supports(e)}getStats(){return this.index.getStats()}matchesField(e){const t=this.expression;return t.type==="ref"&&t.path.length===e.length&&t.path.every((n,r)=>n===e[r])}get keyCount(){return this.index.keyCount}get indexedKeysSet(){return this.index.indexedKeysSet}get orderedEntriesArray(){return this.index.orderedEntriesArray}get valueMapData(){return this.index.valueMapData}equalityLookup(e){return this.index.equalityLookup?.(e)??new Set}rangeQuery(e){return this.index.rangeQuery?.(e)??new Set}inArrayLookup(e){return this.index.inArrayLookup?.(e)??new Set}_getLazyWrapper(){return this.lazyIndex}}class Ma{constructor(){this.lazyIndexes=new Map,this.resolvedIndexes=new Map,this.isIndexesResolved=!1,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle}createIndex(e,t={}){this.lifecycle.validateCollectionUsable("createIndex");const n=++this.indexCounter,r=Tn(),i=e(r),o=F(i),a=t.indexType??Ht,c=new _a(n,o,t.name,a,t.options,this.state.entries());if(this.lazyIndexes.set(n,c),a===Ht)try{const l=c.getResolved();this.resolvedIndexes.set(n,l)}catch(l){console.warn("Failed to resolve BTreeIndex:",l)}else if(typeof a=="function"&&a.prototype)try{const l=c.getResolved();this.resolvedIndexes.set(n,l)}catch{this.resolveSingleIndex(n,c).catch(l=>{console.warn("Failed to resolve single index:",l)})}else this.isIndexesResolved&&this.resolveSingleIndex(n,c).catch(l=>{console.warn("Failed to resolve single index:",l)});return new Aa(n,c)}async resolveAllIndexes(){if(this.isIndexesResolved)return;const e=Array.from(this.lazyIndexes.entries()).map(async([t,n])=>{const r=await n.resolve();return r.build(this.state.entries()),this.resolvedIndexes.set(t,r),{indexId:t,resolvedIndex:r}});await Promise.all(e),this.isIndexesResolved=!0}async resolveSingleIndex(e,t){const n=await t.resolve();return n.build(this.state.entries()),this.resolvedIndexes.set(e,n),n}get indexes(){return this.resolvedIndexes}updateIndexes(e){for(const t of this.resolvedIndexes.values())for(const 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);break}}cleanup(){this.lazyIndexes.clear(),this.resolvedIndexes.clear()}}var Ta={};const Pa=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),Da=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),Ka=new Set(["set","delete","clear","add"]),ja=new Set(["entries","keys","values","forEach"]);function vs(s){return s!==null&&typeof s=="object"&&!(s instanceof Date)&&!(s instanceof RegExp)&&!Je(s)}function Fa(s,e,t,n){if(Pa.has(s))return function(...r){const i=r[0];if(typeof i!="function")return e.apply(t.copy_,r);const o=(l,u)=>{if(vs(l)){const h={tracker:t,prop:String(u)},{proxy:p}=n(l,h);return p}return l},a=function(l,u,h){const p=o(l,u);return i.call(this,p,u,h)};if(s==="reduce"||s==="reduceRight"){const l=function(u,h,p,f){const d=o(h,p);return i.call(this,u,d,p,f)};return e.apply(t.copy_,[l,...r.slice(1)])}const c=e.apply(t.copy_,[a,...r.slice(1)]);if((s==="find"||s==="findLast")&&c&&typeof c=="object"){const l=t.copy_.indexOf(c);if(l!==-1)return o(c,l)}return s==="filter"&&Array.isArray(c)?c.map(l=>{const u=t.copy_.indexOf(l);return u!==-1?o(l,u):l}):c}}function Ba(s,e){return function(){const t=s.copy_;let n=0;return{next(){if(n>=t.length)return{done:!0,value:void 0};const r=t[n];let i=r;if(vs(r)){const o={tracker:s,prop:String(n)},{proxy:a}=e(r,o);i=a}return n++,{done:!1,value:i}},[Symbol.iterator](){return this}}}}function fn(s,e,t){return function(...n){const r=s.apply(e.copy_,n);return t(e),r}}function za(s,e,t,n,r,i,o){if(ja.has(s)||e===Symbol.iterator)return function(...c){const l=t.apply(r.copy_,c);if(s==="forEach"){const h=c[0];if(typeof h=="function"){const p=function(f,d,y){const g=h.call(this,f,d,y);return o(r),g};return t.apply(n,[p,...c.slice(1)])}}if(s==="entries"||s==="values"||s===Symbol.iterator.toString()||e===Symbol.iterator){const h=l,p=new Map;if(s==="values"&&n instanceof Map)for(const[d,y]of r.copy_.entries())p.set(y,d);const f=new Map;if(n instanceof Set)for(const d of r.copy_.values())f.set(d,d);return{next(){const d=h.next();if(!d.done&&d.value&&typeof d.value=="object"){if(s==="entries"&&Array.isArray(d.value)&&d.value.length===2){if(d.value[1]&&typeof d.value[1]=="object"){const y=d.value[0],g={tracker:r,prop:y,updateMap:w=>{r.copy_ instanceof Map&&r.copy_.set(y,w)}},{proxy:m}=i(d.value[1],g);d.value[1]=m}}else if(s==="values"||s===Symbol.iterator.toString()||e===Symbol.iterator)if(s==="values"&&n instanceof Map){const y=p.get(d.value);if(y!==void 0){const g={tracker:r,prop:y,updateMap:w=>{r.copy_ instanceof Map&&r.copy_.set(y,w)}},{proxy:m}=i(d.value,g);d.value=m}}else if(n instanceof Set){const y=d.value,g={tracker:r,prop:y,updateSet:w=>{r.copy_ instanceof Set&&(r.copy_.delete(y),r.copy_.add(w),f.set(y,w))}},{proxy:m}=i(d.value,g);d.value=m}else{const y=Symbol("iterator-value"),{proxy:g}=i(d.value,{tracker:r,prop:y});d.value=g}}return d},[Symbol.iterator](){return this}}}return l}}function M(...s){const e=typeof window<"u"&&typeof localStorage<"u";e&&localStorage.getItem("DEBUG")==="true"?console.log("[proxy]",...s):!e&&typeof process<"u"&&Ta.DEBUG==="true"&&console.log("[proxy]",...s)}function ge(s,e=new WeakMap){if(s==null||typeof s!="object")return s;if(e.has(s))return e.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(Array.isArray(s)){const r=[];return e.set(s,r),s.forEach((i,o)=>{r[o]=ge(i,e)}),r}if(ArrayBuffer.isView(s)&&!(s instanceof DataView)){const r=Object.getPrototypeOf(s).constructor,i=new r(s.length);e.set(s,i);for(let o=0;o<s.length;o++)i[o]=s[o];return i}if(s instanceof Map){const r=new Map;return e.set(s,r),s.forEach((i,o)=>{r.set(o,ge(i,e))}),r}if(s instanceof Set){const r=new Set;return e.set(s,r),s.forEach(i=>{r.add(ge(i,e))}),r}if(Je(s))return s;const t={};e.set(s,t);for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t[r]=ge(s[r],e));const n=Object.getOwnPropertySymbols(s);for(const r of n)t[r]=ge(s[r],e);return t}let pn=0;function La(){return pn+=1,pn}function bs(s,e){const t=new Map;function n(h,p){if(M("Object ID:",h.constructor.name),t.has(h))return t.get(h);{const f=bs(h,p);return t.set(h,f),f}}const r=new Map,i={copy_:ge(s),originalObject:ge(s),proxyCount:La(),modified:!1,assigned_:{},parent:e,target:s};M("createChangeProxy called for target",s,i.proxyCount);function o(h){h.modified||(h.modified=!0),h.parent&&(M("propagating change to parent"),"updateMap"in h.parent?h.parent.updateMap(h.copy_):"updateSet"in h.parent?h.parent.updateSet(h.copy_):(h.parent.tracker.copy_[h.parent.prop]=h.copy_,h.parent.tracker.assigned_[h.parent.prop]=!0),o(h.parent.tracker))}function a(h){if(M("checkIfReverted called with assigned keys:",Object.keys(h.assigned_)),Object.keys(h.assigned_).length===0&&Object.getOwnPropertySymbols(h.assigned_).length===0)return M("No assigned properties, returning true"),!0;for(const f in h.assigned_)if(h.assigned_[f]===!0){const d=h.copy_[f],y=h.originalObject[f];if(M(`Checking property ${String(f)}, current:`,d,"original:",y),!le(d,y))return M(`Property ${String(f)} is different, returning false`),!1}else if(h.assigned_[f]===!1)return M(`Property ${String(f)} was deleted, returning false`),!1;const p=Object.getOwnPropertySymbols(h.assigned_);for(const f of p)if(h.assigned_[f]===!0){const d=h.copy_[f],y=h.originalObject[f];if(!le(d,y))return M("Symbol property is different, returning false"),!1}else if(h.assigned_[f]===!1)return M("Symbol property was deleted, returning false"),!1;return M("All properties match original values, returning true"),!0}function c(h,p){M("checkParentStatus called for child prop:",p);const f=a(h);M("Parent checkIfReverted returned:",f),f&&(M("Parent is fully reverted, clearing tracking"),h.modified=!1,h.assigned_={},h.parent&&(M("Continuing up the parent chain"),c(h.parent.tracker,h.parent.prop)))}function l(h){if(M("createObjectProxy",h),r.has(h))return M("proxyCache found match"),r.get(h);const p=new Proxy(h,{get(f,d){M("get",f,d);const y=i.copy_[d]??i.originalObject[d],g=i.originalObject[d];if(M("value (at top of proxy get)",y),Object.getOwnPropertyDescriptor(f,d)?.get)return y;if(typeof y=="function"){if(Array.isArray(f)){const w=d.toString();if(Da.has(w))return fn(y,i,o);const S=Fa(w,y,i,n);if(S)return S;if(d===Symbol.iterator)return Ba(i,n)}if(f instanceof Map||f instanceof Set){const w=d.toString();if(Ka.has(w))return fn(y,i,o);const S=za(w,d,y,f,i,n,o);if(S)return S}return y.bind(f)}if(vs(y)){const w={tracker:i,prop:String(d)},{proxy:S}=n(g,w);return r.set(y,S),S}return y},set(f,d,y){const g=i.copy_[d];if(M(`set called for property ${String(d)}, current:`,g,"new:",y),le(g,y))M("Value unchanged, not tracking");else{const m=i.originalObject[d],w=le(y,m);if(M("value:",y,"original:",m,"isRevertToOriginal:",w),w){M(`Reverting property ${String(d)} to original value`),delete i.assigned_[d.toString()],M(`Updating copy with original value for ${String(d)}`),i.copy_[d]=ge(m),M("Checking if all properties reverted");const S=a(i);M("All reverted:",S),S?(M("All properties reverted, clearing tracking"),i.modified=!1,i.assigned_={},e&&(M("Updating parent for property:",e.prop),c(e.tracker,e.prop))):(M("Some properties still changed, keeping modified flag"),i.modified=!0)}else M(`Setting new value for property ${String(d)}`),i.copy_[d]=y,i.assigned_[d.toString()]=!0,M("Marking object and ancestors as modified",i),o(i)}return!0},defineProperty(f,d,y){const g=Reflect.defineProperty(f,d,y);return g&&"value"in y&&(i.copy_[d]=ge(y.value),i.assigned_[d.toString()]=!0,o(i)),g},getOwnPropertyDescriptor(f,d){return Reflect.getOwnPropertyDescriptor(f,d)},preventExtensions(f){return Reflect.preventExtensions(f)},isExtensible(f){return Reflect.isExtensible(f)},deleteProperty(f,d){M("deleteProperty",f,d);const y=typeof d=="symbol"?d.toString():d;if(y in f){const g=y in i.originalObject,m=Reflect.deleteProperty(f,d);return m&&(g?(i.assigned_[y]=!1,o(i)):(delete i.assigned_[y],Object.keys(i.assigned_).length===0&&Object.getOwnPropertySymbols(i.assigned_).length===0?i.modified=!1:i.modified=!0)),m}return!0}});return r.set(h,p),p}return{proxy:l(i.copy_),getChanges:()=>{if(M("getChanges called, modified:",i.modified),M(i),!i.modified)return M("Object not modified, returning empty object"),{};if(typeof i.copy_!="object"||Array.isArray(i.copy_)||Object.keys(i.assigned_).length===0)return i.copy_;const h={};for(const p in i.copy_)i.assigned_[p]===!0&&p in i.copy_&&(h[p]=i.copy_[p]);return M("Returning copy:",h),h}}}function Na(s){const e=s.map(t=>bs(t));return{proxies:e.map(t=>t.proxy),getChanges:()=>e.map(t=>t.getChanges())}}function $a(s,e){const{proxy:t,getChanges:n}=bs(s);return e(t),n()}function Ua(s,e){const{proxies:t,getChanges:n}=Na(s);return e(t),n()}function Va(){let s,e,t=!0;return{promise:new Promise((r,i)=>{s=o=>{t=!1,r(o)},e=o=>{t=!1,i(o)}}),resolve:s,reject:e,isPending:()=>t}}function qa(s){return typeof s=="object"&&s!==null&&typeof s.hasPendingGraphRun=="function"}class Wa{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(e){let t=this.contexts.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:r}){if(typeof e>"u"){r();return}const i=this.getOrCreateContext(e);if(i.jobs.has(t)||i.queue.push(t),i.jobs.set(t,r),n){const o=new Set(n);o.delete(t),i.dependencies.set(t,o)}else i.dependencies.has(t)||i.dependencies.set(t,new Set);i.completed.delete(t)}flush(e){const t=this.contexts.get(e);if(!t)return;const{queue:n,jobs:r,dependencies:i,completed:o}=t;for(;n.length>0;){let a=!1;const c=n.length;for(let l=0;l<c;l++){const u=n.shift(),h=r.get(u);if(!h){i.delete(u),o.delete(u);continue}const p=i.get(u);let f=!p;if(p){f=!0;for(const d of p){if(d===u)continue;const y=qa(d)&&d.hasPendingGraphRun(e);if(r.has(d)&&!o.has(d)||!r.has(d)&&y){f=!1;break}}}f?(r.delete(u),i.delete(u),h(),o.add(u),a=!0):n.push(u)}if(!a)throw new Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}flushAll(){for(const e of Array.from(this.contexts.keys()))this.flush(e)}clear(e){this.contexts.delete(e),this.clearListeners.forEach(t=>t(e))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}hasPendingJobs(e){const t=this.contexts.get(e);return!!t&&t.jobs.size>0}clearJob(e,t){const n=this.contexts.get(e);n&&(n.jobs.delete(t),n.dependencies.delete(t),n.completed.delete(t),n.queue=n.queue.filter(r=>r!==t),n.jobs.size===0&&this.contexts.delete(e))}}const xt=new Wa,Ct=[];let nt=[],Ga=0;function Ha(s,e){switch(`${s.type}-${e.type}`){case"insert-update":return{...s,type:"insert",original:{},modified:e.modified,changes:{...s.changes,...e.changes},key:s.key,globalKey:s.globalKey,metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata},mutationId:e.mutationId,updatedAt:e.updatedAt};case"insert-delete":return null;case"update-delete":return e;case"update-update":return{...e,original:s.original,changes:{...s.changes,...e.changes},metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata}};case"delete-delete":case"insert-insert":return e;default:{const t=`${s.type}-${e.type}`;throw new Error(`Unhandled mutation combination: ${t}`)}}}function pt(s){const e=new Za(s);return Ct.push(e),e}function mt(){if(nt.length>0)return nt.slice(-1)[0]}function Qa(s){xt.clear(s.id),nt.push(s)}function Ja(s){try{xt.flush(s.id)}finally{nt=nt.filter(e=>e.id!==s.id)}}function Ya(s){const e=Ct.findIndex(t=>t.id===s.id);e!==-1&&Ct.splice(e,1)}class Za{constructor(e){if(typeof e.mutationFn>"u")throw new $r;this.id=e.id??crypto.randomUUID(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=Va(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Ga++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e==="completed"||e==="failed")&&Ya(this)}mutate(e){if(this.state!=="pending")throw new Ur;Qa(this);try{e()}finally{Ja(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){for(const t of e){const n=this.mutations.findIndex(r=>r.globalKey===t.globalKey);if(n>=0){const r=this.mutations[n],i=Ha(r,t);i===null?this.mutations.splice(n,1):this.mutations[n]=i}else this.mutations.push(t)}}rollback(e){const t=e?.isSecondaryRollback??!1;if(this.state==="completed")throw new Vr;if(this.setState("failed"),!t){const n=new Set;this.mutations.forEach(r=>n.add(r.globalKey));for(const r of Ct)r.state==="pending"&&r.mutations.some(i=>n.has(i.globalKey))&&r.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){const e=new Set;for(const t of this.mutations)e.has(t.collection.id)||(t.collection._state.onTransactionStateChange(),t.collection._state.pendingSyncedTransactions.length>0&&t.collection._state.commitPendingTransactions(),e.add(t.collection.id))}async commit(){if(this.state!=="pending")throw new qr;if(this.setState("persisting"),this.mutations.length===0)return this.setState("completed"),this.isPersisted.resolve(this),this;try{await this.mutationFn({transaction:this}),this.setState("completed"),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){const t=this.createdAt.getTime()-e.createdAt.getTime();return t!==0?t:this.sequenceNumber-e.sequenceNumber}}class Xa{constructor(e,t){this.insert=(n,r)=>{this.lifecycle.validateCollectionUsable("insert");const i=this.state,o=mt();if(!o&&!this.config.onInsert)throw new zr;const a=Array.isArray(n)?n:[n],c=[],l=new Set;if(a.forEach(u=>{const h=this.validateData(u,"insert"),p=this.config.getKey(h);if(this.state.has(p)||l.has(p))throw new Mr(p);l.add(p);const f=this.generateGlobalKey(p,u),d={mutationId:crypto.randomUUID(),original:{},modified:h,changes:Object.fromEntries(Object.keys(u).map(y=>[y,h[y]])),globalKey:f,key:p,metadata:r?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:r?.optimistic??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(d)}),o)return o.applyMutations(c),i.transactions.set(o.id,o),i.scheduleTransactionCleanup(o),i.recomputeOptimisticState(!0),o;{const u=pt({mutationFn:async h=>await this.config.onInsert({transaction:h.transaction,collection:this.collection})});return u.applyMutations(c),u.commit().catch(()=>{}),i.transactions.set(u.id,u),i.scheduleTransactionCleanup(u),i.recomputeOptimisticState(!0),u}},this.delete=(n,r)=>{const i=this.state;this.lifecycle.validateCollectionUsable("delete");const o=mt();if(!o&&!this.config.onDelete)throw new Nr;if(Array.isArray(n)&&n.length===0)throw new Fr;const a=Array.isArray(n)?n:[n],c=[];for(const u of a){if(!this.state.has(u))throw new Br(u);const h=this.generateGlobalKey(u,this.state.get(u)),p={mutationId:crypto.randomUUID(),original:this.state.get(u),modified:this.state.get(u),changes:this.state.get(u),globalKey:h,key:u,metadata:r?.metadata,syncMetadata:i.syncedMetadata.get(u)||{},optimistic:r?.optimistic??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(p)}if(o)return o.applyMutations(c),i.transactions.set(o.id,o),i.scheduleTransactionCleanup(o),i.recomputeOptimisticState(!0),o;const l=pt({autoCommit:!0,mutationFn:async u=>this.config.onDelete({transaction:u.transaction,collection:this.collection})});return l.applyMutations(c),l.commit().catch(()=>{}),i.transactions.set(l.id,l),i.scheduleTransactionCleanup(l),i.recomputeOptimisticState(!0),l},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}ensureStandardSchema(e){if(e&&"~standard"in e)return e;throw new Ir}validateData(e,t,n){if(!this.config.schema)return e;const r=this.ensureStandardSchema(this.config.schema);if(t==="update"&&n){const o=this.state.get(n);if(o&&e&&typeof e=="object"&&typeof o=="object"){const a=Object.assign({},o,e),c=r["~standard"].validate(a);if(c instanceof Promise)throw new Ls;if("issues"in c&&c.issues){const p=c.issues.map(f=>({message:f.message,path:f.path?.map(d=>String(d))}));throw new zs(t,p)}const l=c.value,u=Object.keys(e);return Object.fromEntries(u.map(p=>[p,l[p]]))}}const i=r["~standard"].validate(e);if(i instanceof Promise)throw new Ls;if("issues"in i&&i.issues){const o=i.issues.map(a=>({message:a.message,path:a.path?.map(c=>String(c))}));throw new zs(t,o)}return i.value}generateGlobalKey(e,t){if(typeof e!="string"&&typeof e!="number")throw typeof e>"u"?new _r(t):new Ar(e,t);return`KEY::${this.id}/${e}`}update(e,t,n){if(typeof e>"u")throw new Pr;const r=this.state;this.lifecycle.validateCollectionUsable("update");const i=mt();if(!i&&!this.config.onUpdate)throw new Lr;const o=Array.isArray(e),a=o?e:[e];if(o&&a.length===0)throw new Dr;const c=typeof t=="function"?t:n,l=typeof t=="function"?{}:t,u=a.map(d=>{const y=this.state.get(d);if(!y)throw new Kr(d);return y});let h;o?h=Ua(u,c):h=[$a(u[0],c)];const p=a.map((d,y)=>{const g=h[y];if(!g||Object.keys(g).length===0)return null;const m=u[y],w=this.validateData(g,"update",d),S=Object.assign({},m,w),v=this.config.getKey(m),O=this.config.getKey(S);if(v!==O)throw new jr(v,O);const I=this.generateGlobalKey(O,S);return{mutationId:crypto.randomUUID(),original:m,modified:S,changes:Object.fromEntries(Object.keys(g).map(_=>[_,S[_]])),globalKey:I,key:d,metadata:l.metadata,syncMetadata:r.syncedMetadata.get(d)||{},optimistic:l.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(p.length===0){const d=pt({mutationFn:async()=>{}});return d.commit().catch(()=>{}),r.scheduleTransactionCleanup(d),d}if(i)return i.applyMutations(p),r.transactions.set(i.id,i),r.scheduleTransactionCleanup(i),r.recomputeOptimisticState(!0),i;const f=pt({mutationFn:async d=>this.config.onUpdate({transaction:d.transaction,collection:this.collection})});return f.applyMutations(p),f.commit().catch(()=>{}),r.transactions.set(f.id,f),r.scheduleTransactionCleanup(f),r.recomputeOptimisticState(!0),f}}class ec extends Dn{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t){this.emit("status:change",{type:"status:change",collection:this.collection,previousStatus:t,status:e});const n=`status:${e}`;this.emit(n,{type:n,collection:this.collection,previousStatus:t,status:e})}emitSubscribersChange(e,t){this.emit("subscribers:change",{type:"subscribers:change",collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}cleanup(){this.clearListeners()}}function Ss(s){const e=new xs(s);return s.utils?e.utils=s.utils:e.utils={},e}class xs{constructor(e){if(this.utils={},this.insert=(t,n)=>this._mutations.insert(t,n),this.delete=(t,n)=>this._mutations.delete(t,n),!e)throw new xr;if(!e.sync)throw new Cr;e.id?this.id=e.id:this.id=crypto.randomUUID(),this.config={...e,autoIndex:e.autoIndex??"eager"},this._changes=new Sa,this._events=new ec,this._indexes=new Ma,this._lifecycle=new Ea(e,this.id),this._mutations=new Xa(e,this.id),this._state=new wa(e),this._sync=new Ra(e,this.id),this.comparisonOpts=tc(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status==="ready"}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}preload(){return this._sync.preload()}get(e){return this._state.get(e)}has(e){return this._state.has(e)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){yield*this._state.values()}*entries(){yield*this._state.entries()}*[Symbol.iterator](){yield*this._state[Symbol.iterator]()}forEach(e){return this._state.forEach(e)}map(e){return this._state.map(e)}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this._indexes.createIndex(e,t)}get indexes(){return this._indexes.indexes}validateData(e,t,n){return this._mutations.validateData(e,t,n)}get compareOptions(){return{...this.comparisonOpts}}update(e,t,n){return this._mutations.update(e,t,n)}get state(){const e=new Map;for(const[t,n]of this.entries())e.set(t,n);return e}stateWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return ya(this,e)}subscribeChanges(e,t={}){return this._changes.subscribeChanges(e,t)}on(e,t){return this._events.on(e,t)}once(e,t){return this._events.once(e,t)}off(e,t){this._events.off(e,t)}waitFor(e,t){return this._events.waitFor(e,t)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}}function tc(s){if(s.defaultStringCollation){const e=s.defaultStringCollation;return{stringSort:e.stringSort??"locale",locale:e.stringSort==="locale"?e.locale:void 0,localeOptions:e.stringSort==="locale"?e.localeOptions:void 0}}else return{stringSort:"locale"}}class N{constructor(e={}){this.query={},this.query={...e}}_createRefForSource(e,t){let n;try{n=Object.keys(e)}catch{const a=e===null?"null":"undefined";throw new dt(t,a)}if(Array.isArray(e))throw new dt(t,"array");if(n.length!==1)throw n.length===0?new dt(t,"empty object"):n.every(a=>!isNaN(Number(a)))?new dt(t,"string"):new Hr(t);const r=n[0],i=e[r];let o;if(i instanceof xs)o=new Ke(i,r);else if(i instanceof N){const a=i._getQuery();if(!a.from)throw new Qr(t);o=new oe(a,r)}else throw new Jr(r);return[r,o]}from(e){const[,t]=this._createRefForSource(e,"from clause");return new N({...this.query,from:t})}join(e,t,n="left"){const[r,i]=this._createRefForSource(e,"join clause"),a=[...this._getCurrentAliases(),r],c=Re(a),l=t(c);let u,h;if(l.type==="func"&&l.name==="eq"&&l.args.length===2)u=l.args[0],h=l.args[1];else throw new Yr;const p={from:i,type:n,left:u,right:h},f=this.query.join||[];return new N({...this.query,join:[...f,p]})}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){const t=this._getCurrentAliases(),n=Re(t),r=e(n);if(!Xe(r))throw new Us(yn(r));const i=this.query.where||[];return new N({...this.query,where:[...i,r]})}having(e){const t=this._getCurrentAliases(),n=this.query.select||this.query.fnSelect?an(t):Re(t),r=e(n);if(!Xe(r))throw new Us(yn(r));const i=this.query.having||[];return new N({...this.query,having:[...i,r]})}select(e){const t=this._getCurrentAliases(),n=Re(t),r=e(n),i=jn(r);return new N({...this.query,select:i,fnSelect:void 0})}orderBy(e,t="asc"){const n=this._getCurrentAliases(),r=this.query.select||this.query.fnSelect?an(n):Re(n),i=e(r),o=typeof t=="string"?{direction:t,nulls:"first"}:{direction:t.direction??"asc",nulls:t.nulls??"first",stringSort:t.stringSort,locale:t.stringSort==="locale"?t.locale:void 0,localeOptions:t.stringSort==="locale"?t.localeOptions:void 0},a=u=>({expression:F(u),compareOptions:o}),c=Array.isArray(i)?i.map(u=>a(u)):[a(i)],l=this.query.orderBy||[];return new N({...this.query,orderBy:[...l,...c]})}groupBy(e){const t=this._getCurrentAliases(),n=Re(t),r=e(n),i=Array.isArray(r)?r.map(a=>F(a)):[F(r)],o=this.query.groupBy||[];return new N({...this.query,groupBy:[...o,...i]})}limit(e){return new N({...this.query,limit:e})}offset(e){return new N({...this.query,offset:e})}distinct(){return new N({...this.query,distinct:!0})}findOne(){return new N({...this.query,singleResult:!0})}_getCurrentAliases(){const e=[];if(this.query.from&&e.push(this.query.from.alias),this.query.join)for(const t of this.query.join)e.push(t.from.alias);return e}get fn(){const e=this;return{select(t){return new N({...e.query,select:void 0,fnSelect:t})},where(t){return new N({...e.query,fnWhere:[...e.query.fnWhere||[],t]})},having(t){return new N({...e.query,fnHaving:[...e.query.fnHaving||[],t]})}}}_getQuery(){if(!this.query.from)throw new Zr;return this.query}}function yn(s){return s===null?"null":s===void 0?"undefined":typeof s=="object"?"object":typeof s}function sc(s){return s===void 0?F(null):s instanceof Cn||s instanceof ne||s instanceof Z||s instanceof X?s:F(s)}function nc(s){return s!==null&&typeof s=="object"&&!Xe(s)&&!s.__refProxy}function jn(s){if(!nc(s))return sc(s);const e={};for(const[t,n]of Object.entries(s)){if(typeof t=="string"&&t.startsWith("__SPREAD_SENTINEL__")){e[t]=n;continue}e[t]=jn(n)}return e}function rc(s){const e=s(new N);return Fn(e)}function Fn(s){return s._getQuery()}function ic(s){const e=oc(s);let t=s,n,r=0;const i=10;for(;r<i&&!le(t,n);)n=t,t=Jt(t),r++;return{optimizedQuery:Bn(t),sourceWhereClauses:e}}function oc(s){const e=new Map;if(!s.where||s.where.length===0)return e;const n=Zt(s.where).map(i=>zn(i)),r=Ln(n);for(const[i,o]of r.singleSource)ac(s,i)&&e.set(i,o);return e}function ac(s,e){if(s.from.alias===e)return s.from.type==="collectionRef";if(s.join){for(const t of s.join)if(t.from.alias===e)return t.from.type==="collectionRef"}return!1}function Jt(s){const e={...s,from:s.from.type==="queryRef"?new oe(Jt(s.from.query),s.from.alias):s.from,join:s.join?.map(t=>({...t,from:t.from.type==="queryRef"?new oe(Jt(t.from.query),t.from.alias):t.from}))};return cc(e)}function cc(s){if(!s.where||s.where.length===0)return s;if(!s.join||s.join.length===0){if(s.where.length>1){const a=Zt(s.where),c=It(a);return{...s,where:[c]}}return s}const e=s.where.filter(a=>!Bs(a)),n=Zt(e).map(a=>zn(a)),r=Ln(n),i=uc(s,r),o=s.where.filter(a=>Bs(a));return o.length>0&&(i.where=[...i.where||[],...o]),i}function Bn(s){return{...s,from:Yt(s.from),join:s.join?.map(e=>({...e,from:Yt(e.from)}))}}function Yt(s){if(s.type==="collectionRef")return s;const e=Bn(s.query);if(lc(e)){const t=Yt(e.from);return t.type==="collectionRef"?new Ke(t.collection,s.alias):new oe(t.query,s.alias)}return new oe(e,s.alias)}function lc(s){return(!s.where||s.where.length===0)&&!s.select&&(!s.groupBy||s.groupBy.length===0)&&(!s.having||s.having.length===0)&&(!s.orderBy||s.orderBy.length===0)&&(!s.join||s.join.length===0)&&s.limit===void 0&&s.offset===void 0&&!s.fnSelect&&(!s.fnWhere||s.fnWhere.length===0)&&(!s.fnHaving||s.fnHaving.length===0)}function Zt(s){const e=[];for(const t of s){const n=ls(t);e.push(...Cs(n))}return e}function Cs(s){if(s.type==="func"&&s.name==="and"){const e=[];for(const t of s.args)e.push(...Cs(t));return e}else return[s]}function zn(s){const e=new Set;let t=!1;function n(r){switch(r.type){case"ref":if(r.path&&r.path.length>0){const i=r.path[0];i&&(e.add(i),r.path.length===1&&(t=!0))}break;case"func":r.args&&r.args.forEach(n);break;case"val":break;case"agg":r.args&&r.args.forEach(n);break}}return n(s),{expression:s,touchedSources:e,hasNamespaceOnlyRef:t}}function Ln(s){const e=new Map,t=[];for(const i of s)if(i.touchedSources.size===1&&!i.hasNamespaceOnlyRef){const o=Array.from(i.touchedSources)[0];e.has(o)||e.set(o,[]),e.get(o).push(i.expression)}else(i.touchedSources.size>1||i.hasNamespaceOnlyRef)&&t.push(i.expression);const n=new Map;for(const[i,o]of e)n.set(i,It(o));const r=t.length>0?It(t):void 0;return{singleSource:n,multiSource:r}}function uc(s,e){const t=new Set,n=gn(s.from,e.singleSource,t),r=s.join?s.join.map(l=>({...l,from:gn(l.from,e.singleSource,t)})):void 0,i=[];e.multiSource&&i.push(e.multiSource);const o=s.join&&s.join.some(l=>l.type==="left"||l.type==="right"||l.type==="full");for(const[l,u]of e.singleSource)t.has(l)?o&&i.push(br(u)):i.push(u);const a=i.length>1?[It(i.flatMap(l=>Cs(ls(l))))]:i;return{select:s.select,groupBy:s.groupBy?[...s.groupBy]:void 0,having:s.having?[...s.having]:void 0,orderBy:s.orderBy?[...s.orderBy]:void 0,limit:s.limit,offset:s.offset,distinct:s.distinct,fnSelect:s.fnSelect,fnWhere:s.fnWhere?[...s.fnWhere]:void 0,fnHaving:s.fnHaving?[...s.fnHaving]:void 0,from:n,join:r,where:a.length>0?a:[]}}function Pe(s){return{from:s.from.type==="collectionRef"?new Ke(s.from.collection,s.from.alias):new oe(Pe(s.from.query),s.from.alias),select:s.select,join:s.join?s.join.map(e=>({type:e.type,left:e.left,right:e.right,from:e.from.type==="collectionRef"?new Ke(e.from.collection,e.from.alias):new oe(Pe(e.from.query),e.from.alias)})):void 0,where:s.where?[...s.where]:void 0,groupBy:s.groupBy?[...s.groupBy]:void 0,having:s.having?[...s.having]:void 0,orderBy:s.orderBy?[...s.orderBy]:void 0,limit:s.limit,offset:s.offset,fnSelect:s.fnSelect,fnWhere:s.fnWhere?[...s.fnWhere]:void 0,fnHaving:s.fnHaving?[...s.fnHaving]:void 0}}function gn(s,e,t){const n=e.get(s.alias);if(!n)return s.type==="collectionRef"?new Ke(s.collection,s.alias):new oe(Pe(s.query),s.alias);if(s.type==="collectionRef"){const o={from:new Ke(s.collection,s.alias),where:[n]};return t.add(s.alias),new oe(o,s.alias)}if(!gc(s.query,n,s.alias))return new oe(Pe(s.query),s.alias);if(wc(s.query,n,s.alias))return new oe(Pe(s.query),s.alias);const r=s.query.where||[],i={...Pe(s.query),where:[...r,n]};return t.add(s.alias),new oe(i,s.alias)}function hc(s,e,t){return s.select?Nn(s.select)||mc(s.select,e,t):!1}function dc(s){return s.groupBy&&s.groupBy.length>0}function fc(s){return s.having&&s.having.length>0}function pc(s){return s.orderBy&&s.orderBy.length>0&&(s.limit!==void 0||s.offset!==void 0)}function yc(s){return s.fnSelect||s.fnWhere&&s.fnWhere.length>0||s.fnHaving&&s.fnHaving.length>0}function gc(s,e,t){return!(hc(s,e,t)||dc(s)||fc(s)||pc(s)||yc(s))}function Nn(s){for(const e of Object.values(s))if(typeof e=="object"){const t=e;if(t.type==="agg"||!("type"in t)&&Nn(t))return!0}return!1}function Is(s){const e=[];if(s==null||typeof s!="object")return e;switch(s.type){case"ref":e.push(s);break;case"func":case"agg":for(const t of s.args??[])e.push(...Is(t));break}return e}function mc(s,e,t){const n=new Set;for(const[i,o]of Object.entries(s))i.startsWith("__SPREAD_SENTINEL__")||o instanceof Z||n.add(i);const r=Is(e);for(const i of r){const o=i.path;if(!Array.isArray(o)||o.length<2)continue;const a=o[0],c=o[1];if(a===t&&n.has(c))return!0}return!1}function wc(s,e,t){const n=Is(e);if(n.every(i=>i.path[0]!==t))return!1;if(s.fnSelect)return!0;const r=s.select;if(!r)return!1;for(const i of n){const o=i.path;if(o.length<2||o[0]!==t)continue;const a=r[o[1]];if(!a)continue;if(!(a instanceof Z)||a.path.length<2)return!0;const[c,l]=a.path;if(c!==t&&c!==s.from.alias||l!==o[1])return!0}return!1}function It(s){if(s.length===0)throw new vi;return s.length===1?s[0]:new ne("and",s)}function vc(s,e,t,n,r,i,o,a,c,l,u,h,p,f,d,y,g,m,w){let S=s;for(const v of e)S=bc(S,v,t,n,r,i,o,a,c,l,u,h,p,f,d,y,g,m,w);return S}function bc(s,e,t,n,r,i,o,a,c,l,u,h,p,f,d,y,g,m,w){const S=e.from.type==="collectionRef",{alias:v,input:O,collectionId:I}=xc(e.from,i,c,l,u,h,p,f,o,a,y,g,m,w);t[v]=O,S&&(g[v]=I);const _=c[n],x=c[I];if(!_)throw new Vs(n);if(!x)throw new Vs(I);const{activeSource:b,lazySource:E}=Ic(e.type,_,x),j=Object.keys(t),{mainExpr:B,joinedExpr:Q}=Sc(e.left,e.right,j,v),Be=ee(B),ze=ee(Q);let Ie=s.pipe(Y(([fe,me])=>[Be(me),[fe,me]])),Le=O.pipe(Y(([fe,me])=>{const T={[v]:me};return[ze(T),[fe,T]]}));if(!["inner","left","right","full"].includes(e.type))throw new ai(e.type);if(b){const fe=b==="main"?e.from:d.from,me=fe.type==="queryRef"&&(fe.query.limit||fe.query.offset),T=B.type==="func"||Q.type==="func";if(!me&&!T){const A=b==="main"?v:r;h.add(A);const R=b==="main"?Ie:Le,V=et(d,b==="main"?Q:B,E),pe=V.collection,Ne=V.path[0];Ne&&kt(Ne,V.path,pe);const $e=R.pipe(Mo(at=>{const Ue=m[A]||A,_e=l[Ue];if(!_e)throw new bi(Ue,A,E.id,Object.keys(l));if(_e.hasLoadedInitialState())return;const ct=at.getInner().map(([[_t]])=>_t),lt=new Z(V.path);_e.requestSnapshot({where:na(lt,ct),optimizedOnly:!0})||_e.requestSnapshot()}));b==="main"?Ie=$e:Le=$e}}return Ie.pipe(Bo(Le,e.type),Cc(e.type))}function Sc(s,e,t,n){const r=t.filter(a=>a!==n),i=Xt(s),o=Xt(e);if(i&&r.includes(i)&&o===n)return{mainExpr:s,joinedExpr:e};if(i===n&&o&&r.includes(o))return{mainExpr:e,joinedExpr:s};throw!i||!o?new li:i===o?new ci(i):r.includes(i)?o!==n?new hi(n):new di:new ui(i)}function Xt(s){switch(s.type){case"ref":return s.path[0]||null;case"func":{const e=new Set;for(const t of s.args){const n=Xt(t);n&&e.add(n)}return e.size===1?Array.from(e)[0]:null}default:return null}}function xc(s,e,t,n,r,i,o,a,c,l,u,h,p,f){switch(s.type){case"collectionRef":{const d=e[s.alias];if(!d)throw new In(s.alias,s.collection.id,Object.keys(e));return h[s.alias]=s.collection.id,{alias:s.alias,input:d,collectionId:s.collection.id}}case"queryRef":{const d=l.get(s.query)||s.query,y=u(d,e,t,n,r,i,o,a,c,l);Object.assign(h,y.aliasToCollectionId),Object.assign(p,y.aliasRemapping);const g=l.has(s.query),m=s.query.from.alias;if(!(!g&&s.alias===m))for(const[I,_]of y.sourceWhereClauses)f.set(I,_);const S=Object.keys(y.aliasToCollectionId).find(I=>y.aliasToCollectionId[I]===y.collectionId);S&&S!==s.alias&&(p[s.alias]=S);const O=y.pipeline.pipe(Y(I=>{const[_,[x,b]]=I;return[_,x]}));return{alias:s.alias,input:O,collectionId:y.collectionId}}default:throw new fi(s.type)}}function Cc(s){return function(e){return e.pipe(Se(t=>{const[n,[r,i]]=t,o=r?.[1],a=i?.[1];return s==="inner"?!!(o&&a):s==="left"?!!o:s==="right"?!!a:!0}),Y(t=>{const[n,[r,i]]=t,o=r?.[0],a=r?.[1],c=i?.[0],l=i?.[1],u={};return a&&Object.assign(u,a),l&&Object.assign(u,l),[`[${o},${c}]`,u]}))}}function Ic(s,e,t){switch(s){case"left":return{activeSource:"main",lazySource:t};case"right":return{activeSource:"joined",lazySource:e};case"inner":return e.size<t.size?{activeSource:"main",lazySource:t}:{activeSource:"joined",lazySource:e};default:return{activeSource:void 0,lazySource:void 0}}}function es(s){return s instanceof X?s.value:s}function Ec(s,e,t){const n=s.source(e);if(n&&typeof n=="object"){let r=t;const i=s.targetPath;if(i.length===0)for(const[o,a]of Object.entries(n))t[o]=es(a);else for(let o=0;o<i.length;o++){const a=i[o];if(o===i.length-1){const c=r[a]??={};if(typeof c=="object")for(const[l,u]of Object.entries(n))c[l]=es(u)}else{const c=r[a];(c==null||typeof c!="object")&&(r[a]={}),r=r[a]}}}}function Rc(s,e,t){const n=s.alias.split(".");if(n.length===1)t[s.alias]=s.compiled(e);else{let r=t;for(let i=0;i<n.length-1;i++){const o=n[i],a=r[o];(a==null||typeof a!="object")&&(r[o]={}),r=r[o]}r[n[n.length-1]]=es(s.compiled(e))}}function kc([s,e],t){const n={};for(const r of t)r.kind==="merge"?Ec(r,e,n):Rc(r,e,n);return[s,{...e,$selected:n}]}function Oc(s,e,t){const n=[];return $n([],e,n),s.pipe(Y(r=>kc(r,n)))}function _c(s){return s.type==="agg"}function Ac(s){return s&&typeof s=="object"&&!Xe(s)}function $n(s,e,t){for(const[n,r]of Object.entries(e)){if(n.startsWith("__SPREAD_SENTINEL__")){const o=n.slice(19),a=o.lastIndexOf("__"),c=a>=0?o.slice(0,a):o,l=r&&typeof r=="object"&&"type"in r&&r.type==="ref";if(c.includes(".")||l){const u=[...s],h=l?r:new Z(c.split(".")),p=ee(h);t.push({kind:"merge",targetPath:u,source:p})}else{const u=c,h=[...s];t.push({kind:"merge",targetPath:h,source:p=>p[u]})}continue}const i=r;if(Ac(i)){$n([...s,n],i,t);continue}if(_c(i))t.push({kind:"field",alias:[...s,n].join("."),compiled:()=>null});else{if(i===void 0||!Xe(i)){t.push({kind:"field",alias:[...s,n].join("."),compiled:()=>i});continue}if(i instanceof X){const o=i.value;t.push({kind:"field",alias:[...s,n].join("."),compiled:()=>o})}else t.push({kind:"field",alias:[...s,n].join("."),compiled:ee(i)})}}}function Es(s,e,t,n,r,i,o,a,c=new WeakMap,l=new WeakMap){const u=c.get(s);if(u)return u;ts(s);const{optimizedQuery:h,sourceWhereClauses:p}=ic(s);l.set(h,s),ns(h,s,l);const f={...e},d={},y={},g={},{alias:m,input:w,collectionId:S}=Tc(h.from,f,t,n,r,i,o,a,c,l,d,y,p);g[m]=w;let v=w.pipe(Y(([x,b])=>[x,{[m]:b}]));if(h.join&&h.join.length>0&&(v=vc(v,h.join,g,S,m,f,c,l,t,n,r,i,o,a,s,Es,d,y,p)),h.where&&h.where.length>0)for(const x of h.where){const b=ls(x),E=ee(b);v=v.pipe(Se(([j,B])=>De(E(B))))}if(h.fnWhere&&h.fnWhere.length>0)for(const x of h.fnWhere)v=v.pipe(Se(([b,E])=>De(x(E))));if(h.distinct&&!h.fnSelect&&!h.select)throw new Xr;if(h.fnSelect?v=v.pipe(Y(([x,b])=>{const E=h.fnSelect(b);return[x,{...b,$selected:E}]})):h.select?v=Oc(v,h.select):v=v.pipe(Y(([x,b])=>{const E=!h.join&&!h.groupBy?b[m]:b;return[x,{...b,$selected:E}]})),h.groupBy&&h.groupBy.length>0?v=ln(v,h.groupBy,h.having,h.select,h.fnHaving):h.select&&Object.values(h.select).some(b=>b.type==="agg")&&(v=ln(v,[],h.having,h.select,h.fnHaving)),h.having&&(!h.groupBy||h.groupBy.length===0)&&!(h.select?Object.values(h.select).some(b=>b.type==="agg"):!1))throw new ei;if(h.fnHaving&&h.fnHaving.length>0&&(!h.groupBy||h.groupBy.length===0))for(const x of h.fnHaving)v=v.pipe(Se(([b,E])=>x(E)));if(h.distinct&&(v=v.pipe(Lo(([x,b])=>b.$selected))),h.orderBy&&h.orderBy.length>0){const E=pa(s,v,h.orderBy,h.select||{},t[S],o,a,h.limit,h.offset).pipe(Y(([B,[Q,Be]])=>{const ze=Q.$selected,Ie=ss(ze);return[B,[Ie,Be]]})),j={collectionId:S,pipeline:E,sourceWhereClauses:p,aliasToCollectionId:d,aliasRemapping:y};return c.set(s,j),j}else if(h.limit!==void 0||h.offset!==void 0)throw new ti;const I=v.pipe(Y(([x,b])=>{const E=b.$selected,j=ss(E);return[x,[j,void 0]]})),_={collectionId:S,pipeline:I,sourceWhereClauses:p,aliasToCollectionId:d,aliasRemapping:y};return c.set(s,_),_}function Mc(s){const e=new Set;if(s.from.type==="collectionRef"&&e.add(s.from.alias),s.join)for(const t of s.join)t.from.type==="collectionRef"&&e.add(t.from.alias);return e}function ts(s,e=new Set){const t=Mc(s);for(const r of t)if(e.has(r))throw new si(r,Array.from(e));const n=new Set([...e,...t]);if(s.from.type==="queryRef"&&ts(s.from.query,n),s.join)for(const r of s.join)r.from.type==="queryRef"&&ts(r.from.query,n)}function Tc(s,e,t,n,r,i,o,a,c,l,u,h,p){switch(s.type){case"collectionRef":{const f=e[s.alias];if(!f)throw new In(s.alias,s.collection.id,Object.keys(e));return u[s.alias]=s.collection.id,{alias:s.alias,input:f,collectionId:s.collection.id}}case"queryRef":{const f=l.get(s.query)||s.query,d=Es(f,e,t,n,r,i,o,a,c,l);Object.assign(u,d.aliasToCollectionId),Object.assign(h,d.aliasRemapping);const y=l.has(s.query),g=s.query.from.alias;if(!(!y&&s.alias===g))for(const[O,I]of d.sourceWhereClauses)p.set(O,I);const w=Object.keys(d.aliasToCollectionId).find(O=>d.aliasToCollectionId[O]===d.collectionId);w&&w!==s.alias&&(h[s.alias]=w);const v=d.pipeline.pipe(Y(O=>{const[I,[_,x]]=O,b=ss(_);return[I,b]}));return{alias:s.alias,input:v,collectionId:d.collectionId}}default:throw new ni(s.type)}}function Pc(s){return s instanceof X||s&&typeof s=="object"&&"type"in s&&s.type==="val"}function ss(s){return Pc(s)?s.value:s}function ns(s,e,t){if(s.from.type==="queryRef"&&e.from.type==="queryRef"&&(t.set(s.from.query,e.from.query),ns(s.from.query,e.from.query,t)),s.join&&e.join)for(let n=0;n<s.join.length&&n<e.join.length;n++){const r=s.join[n],i=e.join[n];r.from.type==="queryRef"&&i.from.type==="queryRef"&&(t.set(r.from.query,i.from.query),ns(r.from.query,i.from.query,t))}}function Rs(s,e){const t=s.type;if(t==="val")return new X(s.value);if(t==="ref"){const n=s.path;if(Array.isArray(n)){if(n[0]===e&&n.length>1)return new Z(n.slice(1));if(n.length===1&&n[0]!==void 0)return new Z([n[0]])}return new Z(Array.isArray(n)?n:[String(n)])}else{const n=[];for(const r of s.args){const i=Rs(r,e);n.push(i)}return new ne(s.name,n)}}function mn(s,e){return s.map(n=>{const r=Rs(n.expression,e);return{...n,expression:r}})}const wn=Symbol.for("@tanstack/db.collection-config-builder");class Dc{constructor(e,t,n,r){this.alias=e,this.collectionId=t,this.collection=n,this.collectionConfigBuilder=r,this.biggest=void 0,this.subscriptionLoadingPromises=new Map,this.sentToD2Keys=new Set}subscribe(){const e=this.getWhereClauseForAlias();if(e){const t=Rs(e,this.alias);return this.subscribeToChanges(t)}return this.subscribeToChanges()}subscribeToChanges(e){const t=this.getOrderByInfo(),n=a=>{if(!this.subscriptionLoadingPromises.has(a)){let c;const l=new Promise(u=>{c=u});this.subscriptionLoadingPromises.set(a,{resolve:c}),this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(l)}},r=a=>{const c=a.subscription;if(a.status==="loadingSubset")n(c);else{const l=this.subscriptionLoadingPromises.get(c);l&&(this.subscriptionLoadingPromises.delete(c),l.resolve())}};let i;if(t)i=this.subscribeToOrderedChanges(e,t,r);else{const a=!this.collectionConfigBuilder.isLazyAlias(this.alias);i=this.subscribeToMatchingChanges(e,a,r)}i.status==="loadingSubset"&&n(i);const o=()=>{const a=this.subscriptionLoadingPromises.get(i);a&&(this.subscriptionLoadingPromises.delete(i),a.resolve()),i.unsubscribe()};return this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(o),i}sendChangesToPipeline(e,t){const n=Array.isArray(e)?e:[...e],r=[];for(const c of n){if(c.type==="insert"){if(this.sentToD2Keys.has(c.key))continue;this.sentToD2Keys.add(c.key)}else c.type==="delete"&&this.sentToD2Keys.delete(c.key);r.push(c)}const i=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],a=Kc(i,r,this.collection.config.getKey)>0?t:void 0;this.collectionConfigBuilder.scheduleGraphRun(a,{alias:this.alias})}subscribeToMatchingChanges(e,t,n){const r=o=>{this.sendChangesToPipeline(o)};return this.collection.subscribeChanges(r,{...t&&{includeInitialState:t},whereExpression:e,onStatusChange:n})}subscribeToOrderedChanges(e,t,n){const{orderBy:r,offset:i,limit:o,index:a}=t,c={},l=f=>{const d=jc(f);this.sendChangesToPipelineWithTracking(d,c.current)},u=this.collection.subscribeChanges(l,{whereExpression:e,onStatusChange:n});c.current=u;const h=this.collection.on("truncate",()=>{this.biggest=void 0,this.sentToD2Keys.clear()});u.on("unsubscribed",()=>{h()});const p=mn(r,this.alias);return a?(u.setOrderByIndex(a),u.requestLimitedSnapshot({limit:i+o,orderBy:p})):u.requestSnapshot({orderBy:p,limit:i+o}),u}loadMoreIfNeeded(e){const t=this.getOrderByInfo();if(!t)return!0;const{dataNeeded:n}=t;if(!n)return!0;const r=n();return r>0&&this.loadNextItems(r,e),!0}sendChangesToPipelineWithTracking(e,t){const n=this.getOrderByInfo();if(!n){this.sendChangesToPipeline(e);return}const r=this.trackSentValues(e,n.comparator),i=t;i[wn]??=this.loadMoreIfNeeded.bind(this,t),this.sendChangesToPipeline(r,i[wn])}loadNextItems(e,t){const n=this.getOrderByInfo();if(!n)return;const{orderBy:r,valueExtractorForRawRow:i,offset:o}=n,a=this.biggest,c=a?i(a):void 0,l=c!==void 0?Array.isArray(c)?c:[c]:void 0,u=mn(r,this.alias);t.requestLimitedSnapshot({orderBy:u,limit:e,minValues:l,offset:o})}getWhereClauseForAlias(){const e=this.collectionConfigBuilder.sourceWhereClausesCache;if(e)return e.get(this.alias)}getOrderByInfo(){const e=this.collectionConfigBuilder.optimizableOrderByCollections[this.collectionId];if(e&&e.alias===this.alias)return e}*trackSentValues(e,t){for(const n of e)n.type!=="delete"&&(this.biggest?t(this.biggest,n.value)<0&&(this.biggest=n.value):this.biggest=n.value),yield n}}function Kc(s,e,t){const n=[];for(const r of e){const i=t(r.value);r.type==="insert"?n.push([[i,r.value],1]):r.type==="update"?(n.push([[i,r.previousValue],-1]),n.push([[i,r.value],1])):n.push([[i,r.value],-1])}return n.length!==0&&s.sendData(new $(n)),n.length}function*jc(s){for(const e of s)e.type==="update"?(yield{type:"delete",key:e.key,value:e.previousValue},yield{type:"insert",key:e.key,value:e.value}):yield e}const Un=new WeakMap;function Fc(s){return s.utils?.[ws]?.getBuilder?.()}function Bc(s,e){Un.set(s,e)}function zc(s){return Un.get(s)}let Lc=0;class Nc{constructor(e){this.config=e,this.compiledAliasToCollectionId={},this.resultKeys=new WeakMap,this.orderByIndices=new WeakMap,this.isGraphRunning=!1,this.runCount=0,this.isInErrorState=!1,this.aliasDependencies={},this.builderDependencies=new Set,this.pendingGraphRuns=new Map,this.subscriptions={},this.lazySourcesCallbacks={},this.lazySources=new Set,this.optimizableOrderByCollections={},this.id=e.id||`live-query-${++Lc}`,this.query=$c(e),this.collections=Vc(this.query);const t=qc(this.query);this.collectionByAlias={};for(const[n,r]of t.entries()){const i=this.collections[n];if(i)for(const o of r)this.collectionByAlias[o]=i}this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=Uc(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??Vn(this.query).compareOptions,this.compileBasePipeline()}hasJoins(e){return!!(e.join&&e.join.length>0||e.from.type==="queryRef"&&this.hasJoins(e.from.query))}getConfig(){return{id:this.id,getKey:this.config.getKey||(e=>this.resultKeys.get(e)),sync:this.getSyncConfig(),compare:this.compare,defaultStringCollation:this.compareOptions,gcTime:this.config.gcTime||5e3,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:{getRunCount:this.getRunCount.bind(this),setWindow:this.setWindow.bind(this),getWindow:this.getWindow.bind(this),[ws]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){if(!this.windowFn)throw new xi;return this.currentWindow=e,this.windowFn(e),this.maybeRunGraphFn?.(),this.liveQueryCollection?.isLoadingSubset?new Promise(t=>{const n=this.liveQueryCollection.on("loadingSubset:change",r=>{r.isLoadingSubset||(n(),t())})}):!0}getWindow(){if(!(!this.windowFn||!this.currentWindow))return{offset:this.currentWindow.offset??0,limit:this.currentWindow.limit??0}}getCollectionIdForAlias(e){const t=this.compiledAliasToCollectionId[e];if(t)return t;const n=this.collectionByAlias[e];if(n)return n.id;throw new Error(`Unknown source alias "${e}"`)}isLazyAlias(e){return this.lazySources.has(e)}maybeRunGraph(e){if(!this.isGraphRunning){if(!this.currentSyncConfig||!this.currentSyncState)throw new Error("maybeRunGraph called without active sync session. This should not happen.");this.isGraphRunning=!0;try{const{begin:t,commit:n}=this.currentSyncConfig,r=this.currentSyncState;if(this.isInErrorState)return;if(r.subscribedToAllCollections){for(;r.graph.pendingWork();)r.graph.run(),r.flushPendingChanges?.(),e?.();r.messagesCount===0&&(t(),n()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(e,t){const n=t?.contextId??mt()?.id,r=t?.jobId??this,i=(()=>{if(t?.dependencies)return t.dependencies;const c=new Set(this.builderDependencies);if(t?.alias){const l=this.aliasDependencies[t.alias];if(l)for(const u of l)c.add(u)}return c.delete(this),Array.from(c)})();if(n)for(const c of i)typeof c.scheduleGraphRun=="function"&&c.scheduleGraphRun(void 0,{contextId:n});if(!this.currentSyncConfig||!this.currentSyncState)throw new Error("scheduleGraphRun called without active sync session. This should not happen.");let o=n?this.pendingGraphRuns.get(n):void 0;o||(o={loadCallbacks:new Set},n&&this.pendingGraphRuns.set(n,o)),e&&o.loadCallbacks.add(e);const a=n?void 0:o;xt.schedule({contextId:n,jobId:r,dependencies:i,run:()=>this.executeGraphRun(n,a)})}clearPendingGraphRun(e){this.pendingGraphRuns.delete(e)}hasPendingGraphRun(e){return this.pendingGraphRuns.has(e)}executeGraphRun(e,t){const n=t??(e?this.pendingGraphRuns.get(e):void 0);if(e&&this.pendingGraphRuns.delete(e),!n||!this.currentSyncConfig||!this.currentSyncState)return;this.incrementRunCount();const r=()=>{let i=!0,o;if(n.loadCallbacks.forEach(a=>{try{i=a()&&i}catch(c){i=!1,o??=c}}),o)throw o;return i};this.maybeRunGraph(r)}getSyncConfig(){return{rowUpdateMode:"full",sync:this.syncFn.bind(this)}}incrementRunCount(){this.runCount++}getRunCount(){return this.runCount}syncFn(e){this.liveQueryCollection=e.collection,this.currentSyncConfig=e;const t={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},n=this.extendPipelineWithChangeProcessing(e,t);this.currentSyncState=n,this.unsubscribeFromSchedulerClears=xt.onClear(o=>{this.clearPendingGraphRun(o)});const r=e.collection.on("loadingSubset:change",o=>{o.isLoadingSubset||this.updateLiveQueryStatus(e)});t.unsubscribeCallbacks.add(r);const i=this.subscribeToAllCollections(e,n);return this.maybeRunGraphFn=()=>this.scheduleGraphRun(i),this.scheduleGraphRun(i),()=>{t.unsubscribeCallbacks.forEach(o=>o()),this.currentSyncConfig=void 0,this.currentSyncState=void 0,this.pendingGraphRuns.clear(),this.graphCache=void 0,this.inputsCache=void 0,this.pipelineCache=void 0,this.sourceWhereClausesCache=void 0,this.lazySources.clear(),this.optimizableOrderByCollections={},this.lazySourcesCallbacks={},Object.keys(this.subscriptions).forEach(o=>delete this.subscriptions[o]),this.compiledAliasToCollectionId={},this.unsubscribeFromSchedulerClears?.(),this.unsubscribeFromSchedulerClears=void 0}}compileBasePipeline(){this.graphCache=new vo,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(n=>[n,this.graphCache.newInput()]));const e=Es(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,n=>{this.windowFn=n});this.pipelineCache=e.pipeline,this.sourceWhereClausesCache=e.sourceWhereClauses,this.compiledAliasToCollectionId=e.aliasToCollectionId;const t=Object.keys(this.compiledAliasToCollectionId).filter(n=>!Object.hasOwn(this.inputsCache,n));if(t.length>0)throw new Si(t)}maybeCompileBasePipeline(){return(!this.graphCache||!this.inputsCache||!this.pipelineCache)&&this.compileBasePipeline(),{graph:this.graphCache,inputs:this.inputsCache,pipeline:this.pipelineCache}}extendPipelineWithChangeProcessing(e,t){const{begin:n,commit:r}=e,{graph:i,inputs:o,pipeline:a}=this.maybeCompileBasePipeline();let c=new Map;return a.pipe(Do(l=>{const u=l.getInner();t.messagesCount+=u.length,u.reduce(Wc,c)})),t.flushPendingChanges=()=>{c.size!==0&&(n(),c.forEach(this.applyChanges.bind(this,e)),r(),c=new Map)},i.finalize(),t.graph=i,t.inputs=o,t.pipeline=a,t}applyChanges(e,t,n){const{write:r,collection:i}=e,{deletes:o,inserts:a,value:c,orderByIndex:l}=t;if(this.resultKeys.set(c,n),l!==void 0&&this.orderByIndices.set(c,l),a&&o===0)r({value:c,type:"insert"});else if(a>o||a===o&&i.has(i.getKeyFromItem(c)))r({value:c,type:"update"});else if(o>0)r({value:c,type:"delete"});else throw new Error(`Could not apply changes: ${JSON.stringify(t)}. This should never happen.`)}handleSourceStatusChange(e,t,n){const{status:r}=n;if(r==="error"){this.transitionToError(`Source collection '${t}' entered error state`);return}if(r==="cleaned-up"){this.transitionToError(`Source collection '${t}' was manually cleaned up while live query '${this.id}' depends on it. Live queries prevent automatic GC, so this was likely a manual cleanup() call.`);return}this.updateLiveQueryStatus(e)}updateLiveQueryStatus(e){const{markReady:t}=e;this.isInErrorState||this.currentSyncState?.subscribedToAllCollections&&this.allCollectionsReady()&&!this.liveQueryCollection?.isLoadingSubset&&t()}transitionToError(e){this.isInErrorState=!0,console.error(`[Live Query Error] ${e}`),this.liveQueryCollection?._lifecycle.setStatus("error")}allCollectionsReady(){return Object.values(this.collections).every(e=>e.isReady())}subscribeToAllCollections(e,t){const n=Object.entries(this.compiledAliasToCollectionId);if(n.length===0)throw new Error(`Compiler returned no alias metadata for query '${this.id}'. This should not happen; please report.`);const r=n.map(([o,a])=>{const c=this.collectionByAlias[o]??this.collections[a],l=zc(c);l&&l!==this?(this.aliasDependencies[o]=[l],this.builderDependencies.add(l)):this.aliasDependencies[o]=[];const u=new Dc(o,a,c,this),h=c.on("status:change",d=>{this.handleSourceStatusChange(e,a,d)});t.unsubscribeCallbacks.add(h);const p=u.subscribe();return this.subscriptions[o]=p,u.loadMoreIfNeeded.bind(u,p)}),i=()=>(r.map(o=>o()),!0);return t.subscribedToAllCollections=!0,i}}function $c(s){return typeof s.query=="function"?rc(s.query):Fn(s.query)}function Uc(s){return(e,t)=>{const n=s.get(e),r=s.get(t);return n&&r?n<r?-1:n>r?1:0:0}}function Vc(s){const e={};function t(r){r.type==="collectionRef"?e[r.collection.id]=r.collection:r.type==="queryRef"&&n(r.query)}function n(r){if(r.from&&t(r.from),r.join&&Array.isArray(r.join))for(const i of r.join)i.from&&t(i.from)}return n(s),e}function Vn(s){const e=s.from;if(e.type==="collectionRef")return e.collection;if(e.type==="queryRef")return Vn(e.query);throw new Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(s)}`)}function qc(s){const e=new Map;function t(r){if(r)if(r.type==="collectionRef"){const{id:i}=r.collection,o=e.get(i);o?o.add(r.alias):e.set(i,new Set([r.alias]))}else r.type==="queryRef"&&n(r.query)}function n(r){if(r&&(t(r.from),r.join))for(const i of r.join)t(i.from)}return n(s),e}function Wc(s,[[e,t],n]){const[r,i]=t,o=s.get(e)||{deletes:0,inserts:0,value:r,orderByIndex:i};return n<0?o.deletes+=Math.abs(n):n>0&&(o.inserts+=n,o.value=r,i!==void 0&&(o.orderByIndex=i)),s.set(e,o),s}function vn(s){return new Nc(s).getConfig()}function Ft(s){if(typeof s=="function"){const t=vn({query:s});return bn(t)}else{const e=s,t=vn(e);return e.utils&&(t.utils={...t.utils,...e.utils}),bn(t)}}function bn(s){const e=Ss(s),t=Fc(s);return t&&Bc(e,t),e}const Bt=1;function Tl(s,e=[]){const t=s&&typeof s=="object"&&typeof s.subscribeChanges=="function"&&typeof s.startSyncImmediate=="function"&&typeof s.id=="string",n=z.useRef(null),r=z.useRef(null),i=z.useRef(null),o=z.useRef(0),a=z.useRef(null),c=!n.current||t&&i.current!==s||!t&&(r.current===null||r.current.length!==e.length||r.current.some((d,y)=>d!==e[y]));if(c)if(t)s.config?.syncMode==="on-demand"&&console.warn(`[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.
|
|
8
|
+
|
|
9
|
+
Instead, use a query builder function:
|
|
10
|
+
const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))
|
|
11
|
+
|
|
12
|
+
Or switch to syncMode "eager" if you want all data to sync automatically.`),s.startSyncImmediate(),n.current=s,i.current=s;else if(typeof s=="function"){const d=new N,y=s(d);if(y==null)n.current=null;else if(y instanceof xs)y.startSyncImmediate(),n.current=y;else if(y instanceof N)n.current=Ft({query:s,startSync:!0,gcTime:Bt});else if(y&&typeof y=="object")n.current=Ft({startSync:!0,gcTime:Bt,...y});else throw new Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof y}`);r.current=[...e]}else n.current=Ft({startSync:!0,gcTime:Bt,...s}),r.current=[...e];c&&(o.current=0,a.current=null);const l=z.useRef(null);(!l.current||c)&&(l.current=d=>{if(!n.current)return()=>{};const y=n.current.subscribeChanges(()=>{o.current+=1,d()});return n.current.status==="ready"&&(o.current+=1,d()),()=>{y.unsubscribe()}});const u=z.useRef(null);(!u.current||c)&&(u.current=()=>{const d=o.current,y=n.current;return(!a.current||a.current.version!==d||a.current.collection!==y)&&(a.current={collection:y,version:d}),a.current});const h=z.useSyncExternalStore(l.current,u.current),p=z.useRef(null),f=z.useRef(null);if(!p.current||p.current.version!==h.version||p.current.collection!==h.collection){if(!h.collection)f.current={state:void 0,data:void 0,collection:void 0,status:"disabled",isLoading:!1,isReady:!0,isIdle:!1,isError:!1,isCleanedUp:!1,isEnabled:!1};else{const d=Array.from(h.collection.entries()),g=h.collection.config.singleResult;let m=null,w=null;f.current={get state(){return m||(m=new Map(d)),m},get data(){return w||(w=d.map(([,S])=>S)),g?w[0]:w},collection:h.collection,status:h.collection.status,isLoading:h.collection.status==="loading",isReady:h.collection.status==="ready",isIdle:h.collection.status==="idle",isError:h.collection.status==="error",isCleanedUp:h.collection.status==="cleaned-up",isEnabled:!0}}p.current=h}return f.current}class Ce extends re{constructor(e){super(e),this.name="QueryCollectionError"}}class Gc extends Ce{constructor(){super("[QueryCollection] queryKey must be provided."),this.name="QueryKeyRequiredError"}}class Hc extends Ce{constructor(){super("[QueryCollection] queryFn must be provided."),this.name="QueryFnRequiredError"}}class Qc extends Ce{constructor(){super("[QueryCollection] queryClient must be provided."),this.name="QueryClientRequiredError"}}class Jc extends Ce{constructor(){super("[QueryCollection] getKey must be provided."),this.name="GetKeyRequiredError"}}class Yc extends Ce{constructor(){super("Collection must be in 'ready' state for manual sync operations. Sync not initialized yet."),this.name="SyncNotInitializedError"}}class Zc extends Ce{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name="DuplicateKeyInBatchError"}}class Xc extends Ce{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name="UpdateOperationItemNotFoundError"}}class el extends Ce{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name="DeleteOperationItemNotFoundError"}}const Ee=new WeakMap;function tl(s,e){const t=Array.isArray(s)?s:[s],n=[];for(const r of t)if(r.type==="delete"){const i=Array.isArray(r.key)?r.key:[r.key];for(const o of i)n.push({type:"delete",key:o})}else{const i=Array.isArray(r.data)?r.data:[r.data];for(const o of i){let a;if(r.type==="update")a=e.getKey(o);else{const c=e.collection.validateData(o,r.type==="upsert"?"insert":r.type);a=e.getKey(c)}n.push({type:r.type,key:a,data:o})}}return n}function sl(s,e){const t=new Set;for(const n of s){if(t.has(n.key))throw new Zc(n.key);if(t.add(n.key),n.type==="update"){if(!e.collection._state.syncedData.has(n.key))throw new Xc(n.key)}else if(n.type==="delete"&&!e.collection._state.syncedData.has(n.key))throw new el(n.key)}}function qe(s,e){const t=tl(s,e);sl(t,e),e.begin({immediate:!0});for(const r of t)switch(r.type){case"insert":{const i=e.collection.validateData(r.data,"insert");e.write({type:"insert",value:i});break}case"update":{const o={...e.collection._state.syncedData.get(r.key),...r.data},a=e.collection.validateData(o,"update",r.key);e.write({type:"update",value:a});break}case"delete":{const i=e.collection._state.syncedData.get(r.key);e.write({type:"delete",value:i});break}case"upsert":{const i=e.collection._state.syncedData.has(r.key),o=e.collection.validateData(r.data,i?"update":"insert",r.key);i?e.write({type:"update",value:o}):e.write({type:"insert",value:o});break}}e.commit();const n=Array.from(e.collection._state.syncedData.values());e.updateCacheData?e.updateCacheData(n):e.queryClient.setQueryData(e.queryKey,n)}function nl(s){function e(){const t=s();if(!t)throw new Yc;return t}return{writeInsert(t){const n={type:"insert",data:t},r=e(),i=Ee.get(r);if(i?.isActive){i.operations.push(n);return}qe(n,r)},writeUpdate(t){const n={type:"update",data:t},r=e(),i=Ee.get(r);if(i?.isActive){i.operations.push(n);return}qe(n,r)},writeDelete(t){const n={type:"delete",key:t},r=e(),i=Ee.get(r);if(i?.isActive){i.operations.push(n);return}qe(n,r)},writeUpsert(t){const n={type:"upsert",data:t},r=e(),i=Ee.get(r);if(i?.isActive){i.operations.push(n);return}qe(n,r)},writeBatch(t){const n=e();if(Ee.get(n)?.isActive)throw new Error("Cannot nest writeBatch calls. Complete the current batch before starting a new one.");const i={operations:[],isActive:!0};Ee.set(n,i);try{const o=t();if(o&&typeof o=="object"&&"then"in o&&typeof o.then=="function")throw new Error("writeBatch does not support async callbacks. The callback must be synchronous.");i.operations.length>0&&qe(i.operations,n)}finally{i.isActive=!1,Ee.delete(n)}}}}function rl(s){if(!s)return;const e={};return s.where&&(e.where=rs(s.where)),s.orderBy?.length&&(e.orderBy=s.orderBy.map(t=>{const n={expression:rs(t.expression),direction:t.compareOptions.direction,nulls:t.compareOptions.nulls,stringSort:t.compareOptions.stringSort};return t.compareOptions.stringSort==="locale"?{...n,locale:t.compareOptions.locale,localeOptions:t.compareOptions.localeOptions}:n})),s.limit!==void 0&&(e.limit=s.limit),s.offset!==void 0&&(e.offset=s.offset),Object.keys(e).length===0?void 0:JSON.stringify(e)}function rs(s){if(!s)return null;switch(s.type){case"val":return{type:"val",value:is(s.value)};case"ref":return{type:"ref",path:[...s.path]};case"func":return{type:"func",name:s.name,args:s.args.map(e=>rs(e))};default:return null}}function is(s){if(s===void 0)return{__type:"undefined"};if(typeof s=="number"){if(Number.isNaN(s))return{__type:"nan"};if(s===Number.POSITIVE_INFINITY)return{__type:"infinity",sign:1};if(s===Number.NEGATIVE_INFINITY)return{__type:"infinity",sign:-1}}return s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:s instanceof Date?{__type:"date",value:s.toJSON()}:Array.isArray(s)?s.map(e=>is(e)):typeof s=="object"?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,is(t)])):s}class il{constructor(e,t,n){this.state=e,this.refetchFn=t,this.refetch=t,this.writeInsert=n.writeInsert,this.writeUpdate=n.writeUpdate,this.writeDelete=n.writeDelete,this.writeUpsert=n.writeUpsert,this.writeBatch=n.writeBatch}async clearError(){this.state.lastError=void 0,this.state.errorCount=0,this.state.lastErrorUpdatedAt=0,await this.refetchFn({throwOnError:!0})}get lastError(){return this.state.lastError}get isError(){return!!this.state.lastError}get errorCount(){return this.state.errorCount}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(){return Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().fetchStatus)}}function qn(s){const{queryKey:e,queryFn:t,select:n,queryClient:r,enabled:i,refetchInterval:o,retry:a,retryDelay:c,staleTime:l,getKey:u,onInsert:h,onUpdate:p,onDelete:f,meta:d,...y}=s,g=y.syncMode??"eager";if(!e)throw new Gc;if(!t)throw new Hc;if(!r)throw new Qc;if(!u)throw new Jc;const m={lastError:void 0,errorCount:0,lastErrorUpdatedAt:0,observers:new Map},w=new Map,S=new Map,v=new Map,O=new Map,I=new Map,_=(T,A)=>{const R=v.get(T)||new Set;R.add(A),v.set(T,R);const W=S.get(A)||new Set;W.add(T),S.set(A,W)},x=(T,A)=>{const R=v.get(T)||new Set;R.delete(A),v.set(T,R);const W=S.get(A)||new Set;return W.delete(T),S.set(A,W),R.size===0},b=T=>{const{begin:A,write:R,commit:W,markReady:V,collection:pe}=T;let Ne=!1;const $e=C=>{if(typeof e=="function")return e(C);if(g==="on-demand"){const D=rl(C);return D!==void 0?[...e,D]:e}else return e},at=(C={},D=t)=>{const K=$e(C),P=ht(K),te={...d,loadSubsetOptions:C};if(m.observers.has(P)){I.set(P,(I.get(P)||0)+1);const G=m.observers.get(P),se=G.getCurrentResult();return se.isSuccess?!0:se.isError?Promise.reject(se.error):new Promise((we,Me)=>{const As=G.subscribe(At=>{queueMicrotask(()=>{At.isSuccess?(As(),we()):At.isError&&(As(),Me(At.error))})})})}const ae={queryKey:K,queryFn:D,meta:te,structuralSharing:!0,notifyOnChangeProps:"all",...i!==void 0&&{enabled:i},...o!==void 0&&{refetchInterval:o},...a!==void 0&&{retry:a},...c!==void 0&&{retryDelay:c},...l!==void 0&&{staleTime:l}},Ae=new mr(r,ae);w.set(P,K),m.observers.set(P,Ae),I.set(P,(I.get(P)||0)+1);const Ve=new Promise((G,se)=>{const we=Ae.subscribe(Me=>{queueMicrotask(()=>{Me.isSuccess?(we(),G()):Me.isError&&(we(),se(Me.error))})})});return(Ne||pe.subscriberCount>0)&&ct(Ae,P),Ve},Ue=C=>{const D=ht(C);return P=>{if(P.isSuccess){m.lastError=void 0,m.errorCount=0;const te=P.data,ae=n?n(te):te;if(!Array.isArray(ae)||ae.some(G=>typeof G!="object")){const G=n?`@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof ae} for queryKey ${JSON.stringify(C)}`:`@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof ae} for queryKey ${JSON.stringify(C)}`;console.error(G);return}const Ae=new Map(pe._state.syncedData.entries()),Ve=new Map;ae.forEach(G=>{const se=u(G);Ve.set(se,G)}),A(),Ae.forEach((G,se)=>{const we=Ve.get(se);we?le(G,we)||R({type:"update",value:we}):x(se,D)&&R({type:"delete",value:G})}),Ve.forEach((G,se)=>{_(se,D),Ae.has(se)||R({type:"insert",value:G})}),W(),V()}else P.isError&&(P.errorUpdatedAt!==m.lastErrorUpdatedAt&&(m.lastError=P.error,m.errorCount++,m.lastErrorUpdatedAt=P.errorUpdatedAt),console.error(`[QueryCollection] Error observing query ${String(C)}:`,P.error),V())}},_e=C=>O.has(C),ct=(C,D)=>{if(!_e(D)){const K=w.get(D),P=Ue(K),te=C.subscribe(P);O.set(D,te);const ae=C.getCurrentResult();(ae.isSuccess||ae.isError)&&P(ae)}},lt=()=>{m.observers.forEach(ct)},Ot=()=>{O.forEach(C=>{C()}),O.clear()};Ne=!0;const _t=pe.on("subscribers:change",({subscriberCount:C})=>{C>0?lt():C===0&&Ot()});if(g==="eager"){const C=at({});C instanceof Promise&&C.catch(()=>{})}else V();lt(),m.observers.forEach((C,D)=>{const K=w.get(D);Ue(K)(C.getCurrentResult())});const Os=C=>{O.get(C)?.(),O.delete(C);const D=S.get(C)??new Set,K=[];D.forEach(P=>{const te=v.get(P);te&&(te.delete(C),te.size===0&&(v.delete(P),pe.has(P)&&K.push(pe.get(P))))}),K.length>0&&(A(),K.forEach(P=>{R({type:"delete",value:P})}),W()),m.observers.delete(C),S.delete(C),w.delete(C),I.delete(C)},_s=C=>{const D=I.get(C)||0,K=m.observers.get(C);if(D<=0&&(O.get(C)?.(),O.delete(C)),K?.hasListeners()??!1){I.set(C,0);return}D>0&&console.warn(`[cleanupQueryIfIdle] Invariant violation: refcount=${D} but no listeners. Cleaning up to prevent leak.`,{hashedQueryKey:C}),Os(C)},Gn=C=>{Os(C)},Hn=r.getQueryCache().subscribe(C=>{const D=C.query.queryHash;C.type==="removed"&&w.has(D)&&_s(D)});return{loadSubset:g==="eager"?void 0:at,unloadSubset:g==="eager"?void 0:C=>{const D=$e(C),K=ht(D),te=(I.get(K)||0)-1;te<=0?(I.set(K,0),_s(K)):I.set(K,te)},cleanup:async()=>{_t(),Ot();const C=[...w.values()],D=[...m.observers.keys()];for(const K of D)Gn(K);Hn(),await Promise.all(C.map(async K=>{await r.cancelQueries({queryKey:K,exact:!0}),r.removeQueries({queryKey:K,exact:!0})}))}}},E=async T=>{const R=[...w.values()].map(W=>m.observers.get(ht(W)).refetch({throwOnError:T?.throwOnError}));return Promise.all(R)},j=(T,A)=>{n?r.setQueryData(T,R=>{if(!R||typeof R!="object")return R;if(Array.isArray(R))return A;const W=n(R);if(Array.isArray(W)){for(const V of Object.keys(R))if(R[V]===W)return{...R,[V]:A}}if(Array.isArray(R.data))return{...R,data:A};if(Array.isArray(R.items))return{...R,items:A};if(Array.isArray(R.results))return{...R,results:A};for(const V of Object.keys(R))if(Array.isArray(R[V]))return{...R,[V]:A};return R}):r.setQueryData(T,A)},B=T=>{const A=Array.from(w.values());if(A.length>0)for(const R of A)j(R,T);else{const R=typeof e=="function"?e({}):e;j(R,T)}};let Q=null;const Be=T=>{const{begin:A,write:R,commit:W,collection:V}=T,pe=typeof e=="function"?e({}):e;return Q={collection:V,queryClient:r,queryKey:pe,getKey:u,begin:A,write:R,commit:W,updateCacheData:B},b(T)},ze=nl(()=>Q),Ie=h?async T=>{const A=await h(T)??{};return A.refetch!==!1&&await E(),A}:void 0,Le=p?async T=>{const A=await p(T)??{};return A.refetch!==!1&&await E(),A}:void 0,fe=f?async T=>{const A=await f(T)??{};return A.refetch!==!1&&await E(),A}:void 0,me=new il(m,E,ze);return{...y,getKey:u,syncMode:g,sync:{sync:Be},onInsert:Ie,onUpdate:Le,onDelete:fe,utils:me}}const ol=os("07328c8ae0c7#getCollectionItems",as,void 0,void 0,"getCollectionItems"),al=os("07328c8ae0c7#getDocumentItems",as,void 0,void 0,"getDocumentItems"),cl=os("07328c8ae0c7#deleteDocumentAction",as,void 0,void 0,"deleteDocumentAction"),Pl=Ss(qn({queryClient:Sn,queryKey:["collections"],queryFn:()=>ol(),getKey:s=>s.id})),Dl=Ss(qn({queryClient:Sn,queryKey:["documents"],queryFn:()=>al(),getKey:s=>`${s.collectionId}-${s.id}`,onDelete:async({transaction:s})=>{const t=s.mutations[0].original;if(t.permissions.delete)try{await cl(t.id,t.collectionId)}catch(n){throw console.error("Delete failed, rolling back:",n),n}}}));function ll({...s}){return k.jsx(ir,{"data-slot":"sheet",...s})}function ul({...s}){return k.jsx(ur,{"data-slot":"sheet-portal",...s})}function hl({className:s,...e}){return k.jsx(hr,{"data-slot":"sheet-overlay",className:L("data-closed:fade-out-0 data-open:fade-in-0 fixed inset-0 z-50 bg-black/80 duration-100 data-closed:animate-out data-open:animate-in data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",s),...e})}function dl({className:s,children:e,side:t="right",showCloseButton:n=!0,...r}){return k.jsxs(ul,{children:[k.jsx(hl,{}),k.jsxs(or,{"data-slot":"sheet-content","data-side":t,className:L("data-[side=right]:data-closed:slide-out-to-right-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=top]:data-closed:slide-out-to-top-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:fade-out-0 data-open:fade-in-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=bottom]:data-open:slide-in-from-bottom-10 fixed z-50 flex flex-col bg-background bg-clip-padding text-sm shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=top]:inset-x-0 data-[side=left]:inset-y-0 data-[side=right]:inset-y-0 data-[side=top]:top-0 data-[side=right]:right-0 data-[side=bottom]:bottom-0 data-[side=left]:left-0 data-[side=bottom]:h-auto data-[side=left]:h-full data-[side=right]:h-full data-[side=top]:h-auto data-[side=left]:w-3/4 data-[side=right]:w-3/4 data-closed:animate-out data-open:animate-in data-[side=bottom]:border-t data-[side=left]:border-r data-[side=top]:border-b data-[side=right]:border-l data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",s),...r,children:[e,n&&k.jsx(ar,{"data-slot":"sheet-close",asChild:!0,children:k.jsxs(xn,{variant:"ghost",className:"absolute top-4 right-4",size:"icon-sm",children:[k.jsx(sr,{}),k.jsx("span",{className:"sr-only",children:"Close"})]})})]})]})}function fl({className:s,...e}){return k.jsx("div",{"data-slot":"sheet-header",className:L("flex flex-col gap-1.5 p-6",s),...e})}function pl({className:s,...e}){return k.jsx(cr,{"data-slot":"sheet-title",className:L("font-medium text-base text-foreground",s),...e})}function yl({className:s,...e}){return k.jsx(lr,{"data-slot":"sheet-description",className:L("text-muted-foreground text-sm",s),...e})}const zt=768;function gl(){const[s,e]=z.useState(void 0);return z.useEffect(()=>{const t=window.matchMedia(`(max-width: ${zt-1}px)`),n=()=>{e(window.innerWidth<zt)};return t.addEventListener("change",n),e(window.innerWidth<zt),()=>t.removeEventListener("change",n)},[]),!!s}const ml="sidebar_state",wl=3600*24*7,vl="16rem",bl="18rem",Sl="3rem",xl="b",Wn=z.createContext(null);function ks(){const s=z.useContext(Wn);if(!s)throw new Error("useSidebar must be used within a SidebarProvider.");return s}function Kl({defaultOpen:s=!0,open:e,onOpenChange:t,className:n,style:r,children:i,...o}){const a=gl(),[c,l]=z.useState(!1),[u,h]=z.useState(s),p=e??u,f=z.useCallback(m=>{const w=typeof m=="function"?m(p):m;t?t(w):h(w),document.cookie=`${ml}=${w}; path=/; max-age=${wl}`},[t,p]),d=z.useEffectEvent(()=>a?l(m=>!m):f(m=>!m));z.useEffect(()=>{const m=w=>{w.key===xl&&(w.metaKey||w.ctrlKey)&&(w.preventDefault(),d())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[]);const y=p?"expanded":"collapsed",g=z.useMemo(()=>({state:y,open:p,setOpen:f,isMobile:a,openMobile:c,setOpenMobile:l,toggleSidebar:d}),[y,p,f,a,c,l]);return k.jsx(Wn.Provider,{value:g,children:k.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":vl,"--sidebar-width-icon":Sl,...r},className:L("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",n),...o,children:i})})}function jl({side:s="left",variant:e="sidebar",collapsible:t="offExamples",className:n,children:r,...i}){const{isMobile:o,state:a,openMobile:c,setOpenMobile:l}=ks();return t==="none"?k.jsx("div",{"data-slot":"sidebar",className:L("flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",n),...i,children:r}):o?k.jsx(ll,{open:c,onOpenChange:l,...i,children:k.jsxs(dl,{"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":bl},side:s,children:[k.jsxs(fl,{className:"sr-only",children:[k.jsx(pl,{children:"Sidebar"}),k.jsx(yl,{children:"Displays the mobile sidebar."})]}),k.jsx("div",{className:"flex h-full w-full flex-col",children:r})]})}):k.jsxs("div",{className:"group peer hidden text-sidebar-foreground md:block","data-state":a,"data-collapsible":a==="collapsed"?t:"","data-variant":e,"data-side":s,"data-slot":"sidebar",children:[k.jsx("div",{"data-slot":"sidebar-gap",className:L("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offExamples]:w-0","group-data-[side=right]:rotate-180",e==="floating"||e==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),k.jsx("div",{"data-slot":"sidebar-container",className:L("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",s==="left"?"left-0 group-data-[collapsible=offExamples]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offExamples]:right-[calc(var(--sidebar-width)*-1)]",e==="floating"||e==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...i,children:k.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:L("flex size-full flex-col bg-sidebar",e==="floating"&&"rounded-lg shadow-sm ring-1 ring-sidebar-border"),children:r})})]})}function Fl({className:s,onClick:e,...t}){const{toggleSidebar:n}=ks();return k.jsxs(xn,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon-sm",className:L(s),onClick:r=>{e?.(r),n()},...t,children:[k.jsx(gr,{}),k.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function Bl({className:s,...e}){return k.jsx("main",{"data-slot":"sidebar-inset",className:L("relative flex min-w-0 w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm",s),...e})}function zl({className:s,...e}){return k.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:L("flex flex-col gap-2 p-2",s),...e})}function Ll({className:s,...e}){return k.jsx("div",{"data-slot":"sidebar-footer","data-sidebar":"footer",className:L("flex flex-col gap-2 p-2",s),...e})}function Nl({className:s,...e}){return k.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:L("no-scrollbar flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",s),...e})}function $l({className:s,...e}){return k.jsx("div",{"data-slot":"sidebar-group","data-sidebar":"group",className:L("relative flex w-full min-w-0 flex-col p-2",s),...e})}function Ul({className:s,...e}){return k.jsx("div",{"data-slot":"sidebar-group-content","data-sidebar":"group-content",className:L("w-full text-sm",s),...e})}function Vl({className:s,...e}){return k.jsx("ul",{"data-slot":"sidebar-menu","data-sidebar":"menu",className:L("flex w-full min-w-0 flex-col gap-1",s),...e})}function ql({className:s,...e}){return k.jsx("li",{"data-slot":"sidebar-menu-item","data-sidebar":"menu-item",className:L("group/menu-item relative",s),...e})}const Cl=rr("ring-sidebar-ring rounded-lg hover:text-sidebar-accent-foreground group-data-popup-open/menu-item:bg-sidebar-accent group-data-popup-open/menu-item:text-sidebar-accent-foreground gap-2 p-3 text-left text-sm transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 peer/menu-button flex w-full items-center overflow-hidden outline-hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground"},size:{default:"h-9 text-sm",sm:"h-8 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:p-0!"}},defaultVariants:{variant:"default",size:"default"}});function Wl({asChild:s=!1,isActive:e=!1,variant:t="default",size:n="default",tooltip:r,className:i,...o}){const a=s?nr:"button",{isMobile:c,state:l}=ks(),u=k.jsx(a,{"data-slot":"sidebar-menu-button","data-sidebar":"menu-button","data-size":n,"data-active":e,className:L(Cl({variant:t,size:n}),i),...o});return r?(typeof r=="string"&&(r={children:r}),k.jsxs(dr,{children:[k.jsx(fr,{asChild:!0,children:u}),k.jsx(pr,{side:"right",align:"center",hidden:l!=="collapsed"||c,...r})]})):u}export{Fl as S,Gt as a,jl as b,Pl as c,Dl as d,qt as e,zl as f,Wl as g,Nl as h,$l as i,Ul as j,Vl as k,Ll as l,Ml as m,ql as n,sa as o,Kl as p,Bl as q,Tl as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as r}from"./react-B8--K7an.js";import{S as a}from"./separator-tWFpvpUX.js";import{S as t}from"./sidebar-BBYit8gY.js";function m({children:e}){return r.jsxs("header",{className:"flex h-10 m-2 top-2 shrink-0 items-center gap-2 border rounded-lg sticky bg-card text-card-foreground z-30 px-3 shadow-md",children:[r.jsx(t,{className:"-mx-2"}),r.jsx(a,{orientation:"vertical",className:"mx-2 data-[orientation=vertical]:h-4"}),e]})}export{m as S};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as n,j as r,a as _e}from"./react-B8--K7an.js";import{c as Ie,j as Ee,h as Pe,R as nt,a as rt,k as Te,u as k,A as st,P as j,b as P,f as $,l as at,V as lt,e as ct,m as it,p as dt,n as ut,o as pt,F as ft,D as mt,C as ht,q as vt,t as J}from"./button-Bm94vje1.js";import{u as gt,a as xt,C as St}from"./index-CQRgqbuL.js";const wt=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Re=Ie("chevron-down",wt);const Ct=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],yt=Ie("chevron-up",Ct);const It=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Tt=Ie("loader-circle",It);function bt(t){const o=n.useRef({value:t,previous:t});return n.useMemo(()=>(o.current.value!==t&&(o.current.previous=o.current.value,o.current.value=t),o.current.previous),[t])}function Ne(t,[o,e]){return Math.min(e,Math.max(o,t))}var Pt=[" ","Enter","ArrowUp","ArrowDown"],Nt=[" ","Enter"],Q="Select",[ie,de,_t]=xt(Q),[oe]=rt(Q,[_t,Ee]),ue=Ee(),[Et,G]=oe(Q),[Rt,jt]=oe(Q),je=t=>{const{__scopeSelect:o,children:e,open:c,defaultOpen:a,onOpenChange:u,value:s,defaultValue:l,onValueChange:i,dir:f,name:g,autoComplete:w,disabled:N,required:T,form:y}=t,d=ue(o),[h,x]=n.useState(null),[m,v]=n.useState(null),[U,M]=n.useState(!1),ne=gt(f),[_,O]=Pe({prop:c,defaultProp:a??!1,onChange:u,caller:Q}),[z,q]=Pe({prop:s,defaultProp:l,onChange:i,caller:Q}),L=n.useRef(null),B=h?y||!!h.closest("form"):!0,[W,V]=n.useState(new Set),H=Array.from(W).map(E=>E.props.value).join(";");return r.jsx(nt,{...d,children:r.jsxs(Et,{required:T,scope:o,trigger:h,onTriggerChange:x,valueNode:m,onValueNodeChange:v,valueNodeHasChildren:U,onValueNodeHasChildrenChange:M,contentId:Te(),value:z,onValueChange:q,open:_,onOpenChange:O,dir:ne,triggerPointerDownPosRef:L,disabled:N,children:[r.jsx(ie.Provider,{scope:o,children:r.jsx(Rt,{scope:t.__scopeSelect,onNativeOptionAdd:n.useCallback(E=>{V(D=>new Set(D).add(E))},[]),onNativeOptionRemove:n.useCallback(E=>{V(D=>{const F=new Set(D);return F.delete(E),F})},[]),children:e})}),B?r.jsxs(Qe,{"aria-hidden":!0,required:T,tabIndex:-1,name:g,autoComplete:w,value:z,onChange:E=>q(E.target.value),disabled:N,form:y,children:[z===void 0?r.jsx("option",{value:""}):null,Array.from(W)]},H):null]})})};je.displayName=Q;var Me="SelectTrigger",Ae=n.forwardRef((t,o)=>{const{__scopeSelect:e,disabled:c=!1,...a}=t,u=ue(e),s=G(Me,e),l=s.disabled||c,i=k(o,s.onTriggerChange),f=de(e),g=n.useRef("touch"),[w,N,T]=tt(d=>{const h=f().filter(v=>!v.disabled),x=h.find(v=>v.value===s.value),m=ot(h,d,x);m!==void 0&&s.onValueChange(m.value)}),y=d=>{l||(s.onOpenChange(!0),T()),d&&(s.triggerPointerDownPosRef.current={x:Math.round(d.pageX),y:Math.round(d.pageY)})};return r.jsx(st,{asChild:!0,...u,children:r.jsx(j.button,{type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":et(s.value)?"":void 0,...a,ref:i,onClick:P(a.onClick,d=>{d.currentTarget.focus(),g.current!=="mouse"&&y(d)}),onPointerDown:P(a.onPointerDown,d=>{g.current=d.pointerType;const h=d.target;h.hasPointerCapture(d.pointerId)&&h.releasePointerCapture(d.pointerId),d.button===0&&d.ctrlKey===!1&&d.pointerType==="mouse"&&(y(d),d.preventDefault())}),onKeyDown:P(a.onKeyDown,d=>{const h=w.current!=="";!(d.ctrlKey||d.altKey||d.metaKey)&&d.key.length===1&&N(d.key),!(h&&d.key===" ")&&Pt.includes(d.key)&&(y(),d.preventDefault())})})})});Ae.displayName=Me;var Oe="SelectValue",De=n.forwardRef((t,o)=>{const{__scopeSelect:e,className:c,style:a,children:u,placeholder:s="",...l}=t,i=G(Oe,e),{onValueNodeHasChildrenChange:f}=i,g=u!==void 0,w=k(o,i.onValueNodeChange);return $(()=>{f(g)},[f,g]),r.jsx(j.span,{...l,ref:w,style:{pointerEvents:"none"},children:et(i.value)?r.jsx(r.Fragment,{children:s}):u})});De.displayName=Oe;var Mt="SelectIcon",ke=n.forwardRef((t,o)=>{const{__scopeSelect:e,children:c,...a}=t;return r.jsx(j.span,{"aria-hidden":!0,...a,ref:o,children:c||"▼"})});ke.displayName=Mt;var At="SelectPortal",Le=t=>r.jsx(at,{asChild:!0,...t});Le.displayName=At;var ee="SelectContent",Be=n.forwardRef((t,o)=>{const e=G(ee,t.__scopeSelect),[c,a]=n.useState();if($(()=>{a(new DocumentFragment)},[]),!e.open){const u=c;return u?_e.createPortal(r.jsx(Ve,{scope:t.__scopeSelect,children:r.jsx(ie.Slot,{scope:t.__scopeSelect,children:r.jsx("div",{children:t.children})})}),u):null}return r.jsx(He,{...t,ref:o})});Be.displayName=ee;var A=10,[Ve,Y]=oe(ee),Ot="SelectContentImpl",Dt=pt("SelectContent.RemoveScroll"),He=n.forwardRef((t,o)=>{const{__scopeSelect:e,position:c="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:u,onPointerDownOutside:s,side:l,sideOffset:i,align:f,alignOffset:g,arrowPadding:w,collisionBoundary:N,collisionPadding:T,sticky:y,hideWhenDetached:d,avoidCollisions:h,...x}=t,m=G(ee,e),[v,U]=n.useState(null),[M,ne]=n.useState(null),_=k(o,p=>U(p)),[O,z]=n.useState(null),[q,L]=n.useState(null),B=de(e),[W,V]=n.useState(!1),H=n.useRef(!1);n.useEffect(()=>{if(v)return it(v)},[v]),dt();const E=n.useCallback(p=>{const[I,...R]=B().map(b=>b.ref.current),[S]=R.slice(-1),C=document.activeElement;for(const b of p)if(b===C||(b?.scrollIntoView({block:"nearest"}),b===I&&M&&(M.scrollTop=0),b===S&&M&&(M.scrollTop=M.scrollHeight),b?.focus(),document.activeElement!==C))return},[B,M]),D=n.useCallback(()=>E([O,v]),[E,O,v]);n.useEffect(()=>{W&&D()},[W,D]);const{onOpenChange:F,triggerPointerDownPosRef:K}=m;n.useEffect(()=>{if(v){let p={x:0,y:0};const I=S=>{p={x:Math.abs(Math.round(S.pageX)-(K.current?.x??0)),y:Math.abs(Math.round(S.pageY)-(K.current?.y??0))}},R=S=>{p.x<=10&&p.y<=10?S.preventDefault():v.contains(S.target)||F(!1),document.removeEventListener("pointermove",I),K.current=null};return K.current!==null&&(document.addEventListener("pointermove",I),document.addEventListener("pointerup",R,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",I),document.removeEventListener("pointerup",R,{capture:!0})}}},[v,F,K]),n.useEffect(()=>{const p=()=>F(!1);return window.addEventListener("blur",p),window.addEventListener("resize",p),()=>{window.removeEventListener("blur",p),window.removeEventListener("resize",p)}},[F]);const[pe,ae]=tt(p=>{const I=B().filter(C=>!C.disabled),R=I.find(C=>C.ref.current===document.activeElement),S=ot(I,p,R);S&&setTimeout(()=>S.ref.current.focus())}),fe=n.useCallback((p,I,R)=>{const S=!H.current&&!R;(m.value!==void 0&&m.value===I||S)&&(z(p),S&&(H.current=!0))},[m.value]),me=n.useCallback(()=>v?.focus(),[v]),te=n.useCallback((p,I,R)=>{const S=!H.current&&!R;(m.value!==void 0&&m.value===I||S)&&L(p)},[m.value]),le=c==="popper"?xe:Fe,re=le===xe?{side:l,sideOffset:i,align:f,alignOffset:g,arrowPadding:w,collisionBoundary:N,collisionPadding:T,sticky:y,hideWhenDetached:d,avoidCollisions:h}:{};return r.jsx(Ve,{scope:e,content:v,viewport:M,onViewportChange:ne,itemRefCallback:fe,selectedItem:O,onItemLeave:me,itemTextRefCallback:te,focusSelectedItem:D,selectedItemText:q,position:c,isPositioned:W,searchRef:pe,children:r.jsx(ut,{as:Dt,allowPinchZoom:!0,children:r.jsx(ft,{asChild:!0,trapped:m.open,onMountAutoFocus:p=>{p.preventDefault()},onUnmountAutoFocus:P(a,p=>{m.trigger?.focus({preventScroll:!0}),p.preventDefault()}),children:r.jsx(mt,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:u,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:()=>m.onOpenChange(!1),children:r.jsx(le,{role:"listbox",id:m.contentId,"data-state":m.open?"open":"closed",dir:m.dir,onContextMenu:p=>p.preventDefault(),...x,...re,onPlaced:()=>V(!0),ref:_,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:P(x.onKeyDown,p=>{const I=p.ctrlKey||p.altKey||p.metaKey;if(p.key==="Tab"&&p.preventDefault(),!I&&p.key.length===1&&ae(p.key),["ArrowUp","ArrowDown","Home","End"].includes(p.key)){let S=B().filter(C=>!C.disabled).map(C=>C.ref.current);if(["ArrowUp","End"].includes(p.key)&&(S=S.slice().reverse()),["ArrowUp","ArrowDown"].includes(p.key)){const C=p.target,b=S.indexOf(C);S=S.slice(b+1)}setTimeout(()=>E(S)),p.preventDefault()}})})})})})})});He.displayName=Ot;var kt="SelectItemAlignedPosition",Fe=n.forwardRef((t,o)=>{const{__scopeSelect:e,onPlaced:c,...a}=t,u=G(ee,e),s=Y(ee,e),[l,i]=n.useState(null),[f,g]=n.useState(null),w=k(o,_=>g(_)),N=de(e),T=n.useRef(!1),y=n.useRef(!0),{viewport:d,selectedItem:h,selectedItemText:x,focusSelectedItem:m}=s,v=n.useCallback(()=>{if(u.trigger&&u.valueNode&&l&&f&&d&&h&&x){const _=u.trigger.getBoundingClientRect(),O=f.getBoundingClientRect(),z=u.valueNode.getBoundingClientRect(),q=x.getBoundingClientRect();if(u.dir!=="rtl"){const C=q.left-O.left,b=z.left-C,X=_.left-b,Z=_.width+X,he=Math.max(Z,O.width),ve=window.innerWidth-A,ge=Ne(b,[A,Math.max(A,ve-he)]);l.style.minWidth=Z+"px",l.style.left=ge+"px"}else{const C=O.right-q.right,b=window.innerWidth-z.right-C,X=window.innerWidth-_.right-b,Z=_.width+X,he=Math.max(Z,O.width),ve=window.innerWidth-A,ge=Ne(b,[A,Math.max(A,ve-he)]);l.style.minWidth=Z+"px",l.style.right=ge+"px"}const L=N(),B=window.innerHeight-A*2,W=d.scrollHeight,V=window.getComputedStyle(f),H=parseInt(V.borderTopWidth,10),E=parseInt(V.paddingTop,10),D=parseInt(V.borderBottomWidth,10),F=parseInt(V.paddingBottom,10),K=H+E+W+F+D,pe=Math.min(h.offsetHeight*5,K),ae=window.getComputedStyle(d),fe=parseInt(ae.paddingTop,10),me=parseInt(ae.paddingBottom,10),te=_.top+_.height/2-A,le=B-te,re=h.offsetHeight/2,p=h.offsetTop+re,I=H+E+p,R=K-I;if(I<=te){const C=L.length>0&&h===L[L.length-1].ref.current;l.style.bottom="0px";const b=f.clientHeight-d.offsetTop-d.offsetHeight,X=Math.max(le,re+(C?me:0)+b+D),Z=I+X;l.style.height=Z+"px"}else{const C=L.length>0&&h===L[0].ref.current;l.style.top="0px";const X=Math.max(te,H+d.offsetTop+(C?fe:0)+re)+R;l.style.height=X+"px",d.scrollTop=I-te+d.offsetTop}l.style.margin=`${A}px 0`,l.style.minHeight=pe+"px",l.style.maxHeight=B+"px",c?.(),requestAnimationFrame(()=>T.current=!0)}},[N,u.trigger,u.valueNode,l,f,d,h,x,u.dir,c]);$(()=>v(),[v]);const[U,M]=n.useState();$(()=>{f&&M(window.getComputedStyle(f).zIndex)},[f]);const ne=n.useCallback(_=>{_&&y.current===!0&&(v(),m?.(),y.current=!1)},[v,m]);return r.jsx(Bt,{scope:e,contentWrapper:l,shouldExpandOnScrollRef:T,onScrollButtonChange:ne,children:r.jsx("div",{ref:i,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:U},children:r.jsx(j.div,{...a,ref:w,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});Fe.displayName=kt;var Lt="SelectPopperPosition",xe=n.forwardRef((t,o)=>{const{__scopeSelect:e,align:c="start",collisionPadding:a=A,...u}=t,s=ue(e);return r.jsx(ht,{...s,...u,ref:o,align:c,collisionPadding:a,style:{boxSizing:"border-box",...u.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});xe.displayName=Lt;var[Bt,be]=oe(ee,{}),Se="SelectViewport",Ue=n.forwardRef((t,o)=>{const{__scopeSelect:e,nonce:c,...a}=t,u=Y(Se,e),s=be(Se,e),l=k(o,u.onViewportChange),i=n.useRef(0);return r.jsxs(r.Fragment,{children:[r.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:c}),r.jsx(ie.Slot,{scope:e,children:r.jsx(j.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:P(a.onScroll,f=>{const g=f.currentTarget,{contentWrapper:w,shouldExpandOnScrollRef:N}=s;if(N?.current&&w){const T=Math.abs(i.current-g.scrollTop);if(T>0){const y=window.innerHeight-A*2,d=parseFloat(w.style.minHeight),h=parseFloat(w.style.height),x=Math.max(d,h);if(x<y){const m=x+T,v=Math.min(y,m),U=m-v;w.style.height=v+"px",w.style.bottom==="0px"&&(g.scrollTop=U>0?U:0,w.style.justifyContent="flex-end")}}}i.current=g.scrollTop})})})]})});Ue.displayName=Se;var ze="SelectGroup",[Vt,Ht]=oe(ze),Ft=n.forwardRef((t,o)=>{const{__scopeSelect:e,...c}=t,a=Te();return r.jsx(Vt,{scope:e,id:a,children:r.jsx(j.div,{role:"group","aria-labelledby":a,...c,ref:o})})});Ft.displayName=ze;var We="SelectLabel",Ut=n.forwardRef((t,o)=>{const{__scopeSelect:e,...c}=t,a=Ht(We,e);return r.jsx(j.div,{id:a.id,...c,ref:o})});Ut.displayName=We;var ce="SelectItem",[zt,Ke]=oe(ce),$e=n.forwardRef((t,o)=>{const{__scopeSelect:e,value:c,disabled:a=!1,textValue:u,...s}=t,l=G(ce,e),i=Y(ce,e),f=l.value===c,[g,w]=n.useState(u??""),[N,T]=n.useState(!1),y=k(o,m=>i.itemRefCallback?.(m,c,a)),d=Te(),h=n.useRef("touch"),x=()=>{a||(l.onValueChange(c),l.onOpenChange(!1))};if(c==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return r.jsx(zt,{scope:e,value:c,disabled:a,textId:d,isSelected:f,onItemTextChange:n.useCallback(m=>{w(v=>v||(m?.textContent??"").trim())},[]),children:r.jsx(ie.ItemSlot,{scope:e,value:c,disabled:a,textValue:g,children:r.jsx(j.div,{role:"option","aria-labelledby":d,"data-highlighted":N?"":void 0,"aria-selected":f&&N,"data-state":f?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...s,ref:y,onFocus:P(s.onFocus,()=>T(!0)),onBlur:P(s.onBlur,()=>T(!1)),onClick:P(s.onClick,()=>{h.current!=="mouse"&&x()}),onPointerUp:P(s.onPointerUp,()=>{h.current==="mouse"&&x()}),onPointerDown:P(s.onPointerDown,m=>{h.current=m.pointerType}),onPointerMove:P(s.onPointerMove,m=>{h.current=m.pointerType,a?i.onItemLeave?.():h.current==="mouse"&&m.currentTarget.focus({preventScroll:!0})}),onPointerLeave:P(s.onPointerLeave,m=>{m.currentTarget===document.activeElement&&i.onItemLeave?.()}),onKeyDown:P(s.onKeyDown,m=>{i.searchRef?.current!==""&&m.key===" "||(Nt.includes(m.key)&&x(),m.key===" "&&m.preventDefault())})})})})});$e.displayName=ce;var se="SelectItemText",Ge=n.forwardRef((t,o)=>{const{__scopeSelect:e,className:c,style:a,...u}=t,s=G(se,e),l=Y(se,e),i=Ke(se,e),f=jt(se,e),[g,w]=n.useState(null),N=k(o,x=>w(x),i.onItemTextChange,x=>l.itemTextRefCallback?.(x,i.value,i.disabled)),T=g?.textContent,y=n.useMemo(()=>r.jsx("option",{value:i.value,disabled:i.disabled,children:T},i.value),[i.disabled,i.value,T]),{onNativeOptionAdd:d,onNativeOptionRemove:h}=f;return $(()=>(d(y),()=>h(y)),[d,h,y]),r.jsxs(r.Fragment,{children:[r.jsx(j.span,{id:i.textId,...u,ref:N}),i.isSelected&&s.valueNode&&!s.valueNodeHasChildren?_e.createPortal(u.children,s.valueNode):null]})});Ge.displayName=se;var Ye="SelectItemIndicator",qe=n.forwardRef((t,o)=>{const{__scopeSelect:e,...c}=t;return Ke(Ye,e).isSelected?r.jsx(j.span,{"aria-hidden":!0,...c,ref:o}):null});qe.displayName=Ye;var we="SelectScrollUpButton",Xe=n.forwardRef((t,o)=>{const e=Y(we,t.__scopeSelect),c=be(we,t.__scopeSelect),[a,u]=n.useState(!1),s=k(o,c.onScrollButtonChange);return $(()=>{if(e.viewport&&e.isPositioned){let l=function(){const f=i.scrollTop>0;u(f)};const i=e.viewport;return l(),i.addEventListener("scroll",l),()=>i.removeEventListener("scroll",l)}},[e.viewport,e.isPositioned]),a?r.jsx(Je,{...t,ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:i}=e;l&&i&&(l.scrollTop=l.scrollTop-i.offsetHeight)}}):null});Xe.displayName=we;var Ce="SelectScrollDownButton",Ze=n.forwardRef((t,o)=>{const e=Y(Ce,t.__scopeSelect),c=be(Ce,t.__scopeSelect),[a,u]=n.useState(!1),s=k(o,c.onScrollButtonChange);return $(()=>{if(e.viewport&&e.isPositioned){let l=function(){const f=i.scrollHeight-i.clientHeight,g=Math.ceil(i.scrollTop)<f;u(g)};const i=e.viewport;return l(),i.addEventListener("scroll",l),()=>i.removeEventListener("scroll",l)}},[e.viewport,e.isPositioned]),a?r.jsx(Je,{...t,ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:i}=e;l&&i&&(l.scrollTop=l.scrollTop+i.offsetHeight)}}):null});Ze.displayName=Ce;var Je=n.forwardRef((t,o)=>{const{__scopeSelect:e,onAutoScroll:c,...a}=t,u=Y("SelectScrollButton",e),s=n.useRef(null),l=de(e),i=n.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return n.useEffect(()=>()=>i(),[i]),$(()=>{l().find(g=>g.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[l]),r.jsx(j.div,{"aria-hidden":!0,...a,ref:o,style:{flexShrink:0,...a.style},onPointerDown:P(a.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(c,50))}),onPointerMove:P(a.onPointerMove,()=>{u.onItemLeave?.(),s.current===null&&(s.current=window.setInterval(c,50))}),onPointerLeave:P(a.onPointerLeave,()=>{i()})})}),Wt="SelectSeparator",Kt=n.forwardRef((t,o)=>{const{__scopeSelect:e,...c}=t;return r.jsx(j.div,{"aria-hidden":!0,...c,ref:o})});Kt.displayName=Wt;var ye="SelectArrow",$t=n.forwardRef((t,o)=>{const{__scopeSelect:e,...c}=t,a=ue(e),u=G(ye,e),s=Y(ye,e);return u.open&&s.position==="popper"?r.jsx(vt,{...a,...c,ref:o}):null});$t.displayName=ye;var Gt="SelectBubbleInput",Qe=n.forwardRef(({__scopeSelect:t,value:o,...e},c)=>{const a=n.useRef(null),u=k(c,a),s=bt(o);return n.useEffect(()=>{const l=a.current;if(!l)return;const i=window.HTMLSelectElement.prototype,g=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==o&&g){const w=new Event("change",{bubbles:!0});g.call(l,o),l.dispatchEvent(w)}},[s,o]),r.jsx(j.select,{...e,style:{...lt,...e.style},ref:u,defaultValue:o})});Qe.displayName=Gt;function et(t){return t===""||t===void 0}function tt(t){const o=ct(t),e=n.useRef(""),c=n.useRef(0),a=n.useCallback(s=>{const l=e.current+s;o(l),(function i(f){e.current=f,window.clearTimeout(c.current),f!==""&&(c.current=window.setTimeout(()=>i(""),1e3))})(l)},[o]),u=n.useCallback(()=>{e.current="",window.clearTimeout(c.current)},[]);return n.useEffect(()=>()=>window.clearTimeout(c.current),[]),[e,a,u]}function ot(t,o,e){const a=o.length>1&&Array.from(o).every(f=>f===o[0])?o[0]:o,u=e?t.indexOf(e):-1;let s=Yt(t,Math.max(u,0));a.length===1&&(s=s.filter(f=>f!==e));const i=s.find(f=>f.textValue.toLowerCase().startsWith(a.toLowerCase()));return i!==e?i:void 0}function Yt(t,o){return t.map((e,c)=>t[(o+c)%t.length])}var qt=je,Xt=Ae,Zt=De,Jt=ke,Qt=Le,eo=Be,to=Ue,oo=$e,no=Ge,ro=qe,so=Xe,ao=Ze;function fo({...t}){return r.jsx(qt,{"data-slot":"select",...t})}function mo({...t}){return r.jsx(Zt,{"data-slot":"select-value",...t})}function ho({className:t,size:o="default",children:e,...c}){return r.jsxs(Xt,{"data-slot":"select-trigger","data-size":o,className:J("flex w-fit items-center justify-between gap-1.5 whitespace-nowrap rounded-4xl border border-input bg-input/30 px-3 py-2 text-sm outline-none transition-colors focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-[3px] aria-invalid:ring-destructive/20 data-[size=default]:h-9 data-[size=sm]:h-8 data-placeholder:text-muted-foreground *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 dark:hover:bg-input/50 [&_svg]:shrink-0",t),...c,children:[e,r.jsx(Jt,{asChild:!0,children:r.jsx(Re,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function vo({className:t,children:o,position:e="item-aligned",align:c="center",...a}){return r.jsx(Qt,{children:r.jsxs(eo,{"data-slot":"select-content",className:J("data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-y-auto overflow-x-hidden rounded-2xl bg-popover text-popover-foreground shadow-2xl ring-1 ring-foreground/5 duration-100 data-closed:animate-out data-open:animate-in",e==="popper"&&"data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=bottom]:translate-y-1 data-[side=top]:-translate-y-1",t),position:e,align:c,...a,children:[r.jsx(lo,{}),r.jsx(to,{"data-position":e,className:J("data-[position=popper]:h-(--radix-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)",e==="popper"&&""),children:o}),r.jsx(co,{})]})})}function go({className:t,children:o,...e}){return r.jsxs(oo,{"data-slot":"select-item",className:J("flex w-full select-none items-center gap-2.5 ps-3 p-2 text-sm outline-hidden focus:bg-accent data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground data-disabled:opacity-50 [&_svg]:shrink-0 *:[span]:flex *:[span]:items-center *:[span]:gap-2 *:[span]:flex-1",t),...e,children:[r.jsx(no,{children:o}),r.jsx(ro,{asChild:!0,children:r.jsx(St,{className:"size-4"})})]})}function lo({className:t,...o}){return r.jsx(so,{"data-slot":"select-scroll-up-button",className:J("z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",t),...o,children:r.jsx(yt,{})})}function co({className:t,...o}){return r.jsx(ao,{"data-slot":"select-scroll-down-button",className:J("z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",t),...o,children:r.jsx(Re,{})})}function xo({className:t,...o}){return r.jsx(Tt,{role:"status","aria-label":"Loading",className:J("size-4 animate-spin",t),...o})}export{Re as C,Tt as L,fo as S,ho as a,mo as b,vo as c,go as d,xo as e,bt as u};
|