@undefineds.co/xpod 0.4.12 → 0.4.14
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/config/components-ignore.json +11 -7
- package/dist/acceptance/QleverSemanticConformance.js +7 -0
- package/dist/api/ai-gateway/providers/OfferingAuthorization.d.ts +6 -1
- package/dist/api/ai-gateway/providers/OfferingAuthorization.js +0 -3
- package/dist/api/ai-gateway/providers/ProviderRegistry.js +1 -1
- package/dist/api/container/index.js +1 -0
- package/dist/api/container/local.js +30 -12
- package/dist/api/container/routes.js +2 -0
- package/dist/api/container/types.d.ts +2 -0
- package/dist/api/handlers/AdminHandler.d.ts +17 -1
- package/dist/api/handlers/AdminHandler.js +40 -3
- package/dist/api/handlers/EdgeNodeSignalHandler.js +10 -2
- package/dist/api/handlers/NetworkSettingsHandler.d.ts +37 -5
- package/dist/api/handlers/NetworkSettingsHandler.js +39 -11
- package/dist/api/handlers/ProvisionHandler.d.ts +6 -1
- package/dist/api/handlers/ProvisionHandler.js +7 -2
- package/dist/api/handlers/ReachabilityHandler.d.ts +6 -0
- package/dist/api/handlers/ReachabilityHandler.js +22 -5
- package/dist/api/network/NetworkEnvironmentConfigurationStore.d.ts +6 -1
- package/dist/api/network/NetworkEnvironmentConfigurationStore.js +72 -16
- package/dist/api/runtime.d.ts +9 -0
- package/dist/api/runtime.js +15 -2
- package/dist/cli/commands/start.d.ts +19 -1
- package/dist/cli/commands/start.js +71 -5
- package/dist/components/context.jsonld +30 -0
- package/dist/edge/EdgeNodeAgent.d.ts +6 -0
- package/dist/edge/EdgeNodeAgent.js +1 -1
- package/dist/edge/EdgeNodeAgentInitializer.d.ts +2 -0
- package/dist/edge/EdgeNodeAgentInitializer.js +1 -0
- package/dist/edge/EdgeNodeAgentInitializer.jsonld +19 -0
- package/dist/edge/EdgeNodeDnsCoordinator.d.ts +11 -1
- package/dist/edge/EdgeNodeDnsCoordinator.js +12 -2
- package/dist/edge/EdgeNodeHealthProbeService.d.ts +15 -0
- package/dist/edge/EdgeNodeHealthProbeService.js +44 -12
- package/dist/edge/EdgeNodeHealthProbeService.jsonld +77 -0
- package/dist/edge/ProbeTargetGuard.d.ts +35 -0
- package/dist/edge/ProbeTargetGuard.js +142 -0
- package/dist/edge/reachability/NodeAccessResolver.d.ts +16 -0
- package/dist/edge/reachability/NodeAccessResolver.js +30 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +9 -3
- package/dist/main.js +7 -0
- package/dist/runtime/Proxy.d.ts +22 -0
- package/dist/runtime/Proxy.js +34 -7
- package/dist/runtime/bootstrap.d.ts +11 -0
- package/dist/runtime/bootstrap.js +21 -1
- package/dist/runtime/css-process.d.ts +1 -0
- package/dist/runtime/css-process.js +1 -0
- package/dist/runtime/host/node/NodeRuntimeHost.js +4 -1
- package/dist/runtime/host/types.d.ts +6 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +5 -1
- package/dist/runtime/lifecycle.js +1 -0
- package/dist/runtime/port-finder.d.ts +30 -0
- package/dist/runtime/port-finder.js +83 -0
- package/dist/runtime/runner/node/NodeGatewayRuntimeRunner.js +1 -0
- package/dist/runtime/runner/types.d.ts +5 -0
- package/dist/runtime/runtime-types.d.ts +1 -0
- package/dist/storage/rdf/PostgresRdfEngine.js +10 -4
- package/dist/storage/rdf/RdfAccessScope.js +15 -1
- package/dist/storage/rdf/RdfEngineRdfJsSource.js +10 -2
- package/dist/test-utils/local-managed-client-p2p-e2e-smoke.js +1 -1
- package/dist/tunnel/LocalTunnelProvider.d.ts +15 -0
- package/dist/tunnel/LocalTunnelProvider.js +87 -18
- package/dist/tunnel/LocalTunnelProvider.jsonld +27 -0
- package/dist/tunnel/NgrokTunnelProvider.d.ts +4 -0
- package/dist/tunnel/NgrokTunnelProvider.js +117 -43
- package/dist/tunnel/NgrokTunnelProvider.jsonld +4 -0
- package/dist/tunnel/SakuraFrpTunnelProvider.d.ts +65 -3
- package/dist/tunnel/SakuraFrpTunnelProvider.js +268 -25
- package/dist/tunnel/TunnelLifecycle.d.ts +14 -0
- package/dist/tunnel/TunnelLifecycle.js +34 -0
- package/dist/tunnel/TunnelProfiles.d.ts +33 -3
- package/dist/tunnel/TunnelProfiles.js +105 -78
- package/dist/tunnel/TunnelProvider.d.ts +15 -2
- package/dist/tunnel/TunnelProvider.jsonld +8 -0
- package/dist/tunnel/TunnelProviderCatalog.d.ts +62 -0
- package/dist/tunnel/TunnelProviderCatalog.js +130 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.js +3 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectDialog.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialRow.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiCustomProviderDialog.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiQuotaCard.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiSortableCredentialList.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.d.ts +13 -11
- package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.js +16 -13
- package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.js +3 -3
- package/node_modules/@undefineds.co/ai-connections/dist/collections.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/collections.js +3 -3
- package/node_modules/@undefineds.co/ai-connections/dist/{ai-connections-client.d.ts → contract/ai-connections-client.d.ts} +4 -2
- package/node_modules/@undefineds.co/ai-connections/dist/{ai-connections-client.js → contract/ai-connections-client.js} +4 -2
- package/node_modules/@undefineds.co/ai-connections/dist/{client → contract/client}/normalize.d.ts +17 -7
- package/node_modules/@undefineds.co/ai-connections/dist/{client → contract/client}/normalize.js +18 -213
- package/node_modules/@undefineds.co/ai-connections/dist/{client → contract/client}/request.js +3 -3
- package/node_modules/@undefineds.co/ai-connections/dist/{client → contract/client}/types.d.ts +11 -2
- package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/index.cjs +8 -8
- package/node_modules/@undefineds.co/ai-connections/dist/contract/index.d.ts +9 -0
- package/node_modules/@undefineds.co/ai-connections/dist/contract/index.js +9 -0
- package/node_modules/@undefineds.co/ai-connections/dist/{provider-catalog.cjs → contract/provider-catalog.cjs} +5 -28
- package/node_modules/@undefineds.co/ai-connections/dist/{provider-catalog.d.ts → contract/provider-catalog.d.ts} +9 -8
- package/node_modules/@undefineds.co/ai-connections/dist/{provider-catalog.js → contract/provider-catalog.js} +11 -31
- package/node_modules/@undefineds.co/ai-connections/dist/controller.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/controller.js +3 -2
- package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/display-wording.d.ts +20 -0
- package/node_modules/@undefineds.co/ai-connections/dist/display-wording.js +73 -0
- package/node_modules/@undefineds.co/ai-connections/dist/error-wording.d.ts +24 -0
- package/node_modules/@undefineds.co/ai-connections/dist/error-wording.js +253 -0
- package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +2 -3
- package/node_modules/@undefineds.co/ai-connections/dist/index.js +2 -3
- package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/offering-label.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/useAiConnectDialog.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/package.json +25 -18
- package/node_modules/@undefineds.co/shared-ui/dist/index.d.ts +4 -2
- package/node_modules/@undefineds.co/shared-ui/dist/index.js +4 -2
- package/node_modules/@undefineds.co/shared-ui/dist/login/LoginModal.d.ts +4 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/LoginModal.js +12 -6
- package/node_modules/@undefineds.co/shared-ui/dist/login/LoginView.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/host-types.d.ts +7 -1
- package/node_modules/@undefineds.co/shared-ui/dist/login/login-branding.d.ts +6 -0
- package/node_modules/@undefineds.co/shared-ui/dist/login/login-branding.js +18 -0
- package/node_modules/@undefineds.co/shared-ui/dist/user-facing-errors.d.ts +14 -2
- package/node_modules/@undefineds.co/shared-ui/dist/user-facing-errors.js +26 -17
- package/node_modules/@undefineds.co/solid-sdk/dist/login-store.d.ts +3 -3
- package/node_modules/@undefineds.co/solid-sdk/dist/login-store.js +3 -3
- package/package.json +4 -3
- package/static/auth-callback/assets/{AiConfigContext-DnQs1ZpW.js → AiConfigContext-DCXpjzpj.js} +1 -1
- package/static/auth-callback/assets/{AiConfigPage-DOtvlxH0.js → AiConfigPage-fe-xMIXa.js} +1 -1
- package/static/auth-callback/assets/{DocumentProcessingPanel-BS2voQgL.js → DocumentProcessingPanel-BGnkfMuU.js} +1 -1
- package/static/auth-callback/assets/{IndexLifecyclePanel-Cvt0cJtN.js → IndexLifecyclePanel-42Jups0j.js} +1 -1
- package/static/auth-callback/assets/{IndexSubjectPanel-Dhf01GqF.js → IndexSubjectPanel-CYyLOlQU.js} +1 -1
- package/static/auth-callback/assets/{ModelAssignmentsPanel-BJutWaAF.js → ModelAssignmentsPanel-BOvUH4yr.js} +1 -1
- package/static/auth-callback/assets/{ModelsPage-BRS0sje3.js → ModelsPage-DwyITxt7.js} +6 -6
- package/static/auth-callback/assets/NetworkPage-CG9RelJA.js +2 -0
- package/static/auth-callback/assets/{PaneListHeader-QQeJGTp4.js → PaneListHeader-yvd5ohs6.js} +1 -1
- package/static/auth-callback/assets/{SearchIndexingPanel-MyNUSEwT.js → SearchIndexingPanel-2_a6ezzj.js} +1 -1
- package/static/auth-callback/assets/{StatusSubjectPanel-DQkEVsFs.js → StatusSubjectPanel-8qtVxnzC.js} +1 -1
- package/static/auth-callback/assets/{StatusWorkspace-Dkv63Uwk.js → StatusWorkspace-CBdRahCF.js} +1 -1
- package/static/auth-callback/assets/{SystemSettingsPage-TIsUfX5d.js → SystemSettingsPage-BZJ6vWkg.js} +1 -1
- package/static/auth-callback/assets/{SystemSettingsSubjectPanel-BJWEt2-7.js → SystemSettingsSubjectPanel-xm08UhXP.js} +1 -1
- package/static/auth-callback/assets/XpodAiConnectionsPodStore-V6vgGfuw.js +3 -0
- package/static/auth-callback/assets/{activity-5hNeNKnL.js → activity-CeM7xly8.js} +1 -1
- package/static/auth-callback/assets/ai-connections-C6yaE6WQ.js +1 -0
- package/static/auth-callback/assets/{auth-callback-CAFZ3R0B.js → auth-callback-DTG8cSj7.js} +3 -3
- package/static/auth-callback/assets/{badge-CAIPI0CB.js → badge-qJo2Zr4d.js} +1 -1
- package/static/auth-callback/assets/{collection-runtime-D9s7h9YA.js → collection-runtime-Bztsz31a.js} +1 -1
- package/static/auth-callback/assets/{dialog-BjA109aX.js → dialog-D-h6x5x0.js} +1 -1
- package/static/auth-callback/assets/{download-B3Up5W2G.js → download-C2ir4lmR.js} +1 -1
- package/static/auth-callback/assets/{external-link-BTXgSPzB.js → external-link-THLDL4On.js} +1 -1
- package/static/auth-callback/assets/{index-CirW4CJf.js → index-BRpv4yO3.js} +1 -1
- package/static/auth-callback/assets/{index-BppXlxcp.js → index-BlVZb9A7.js} +1 -1
- package/static/auth-callback/assets/index-D983R1FV.js +4 -0
- package/static/auth-callback/assets/{index-browser-DtU38ni3.js → index-browser-3FvR0aaf.js} +1 -1
- package/static/auth-callback/assets/{key-round-CQCOrZ7x.js → key-round-C9U5j1Ly.js} +1 -1
- package/static/auth-callback/assets/{rotate-ccw-C1zM2KtS.js → rotate-ccw-DP45cD4o.js} +1 -1
- package/static/auth-callback/assets/{skeleton-Cqp7_M9-.js → skeleton-Dn4EiSCS.js} +1 -1
- package/static/auth-callback/assets/{waypoints-Bj6gAUSQ.js → waypoints-uqFQ3uEG.js} +1 -1
- package/static/auth-callback/assets/{workspace-layout-DK8mDzrY.js → workspace-layout-DLYK0Wwu.js} +1 -1
- package/static/auth-callback/auth-callback.html +1 -1
- package/static/dashboard/assets/{AiConfigContext-BsE7MqX8.js → AiConfigContext-DJcMECNw.js} +1 -1
- package/static/dashboard/assets/{AiConfigPage-DvM-lRXa.js → AiConfigPage-BvE7dOTy.js} +1 -1
- package/static/dashboard/assets/{DocumentProcessingPanel-BPfdlfuf.js → DocumentProcessingPanel-D9780krf.js} +1 -1
- package/static/dashboard/assets/{IndexLifecyclePanel--m0AGxvh.js → IndexLifecyclePanel-SjsUcnbM.js} +1 -1
- package/static/dashboard/assets/{IndexSubjectPanel-Bb7m1k3d.js → IndexSubjectPanel-C-ym2Tqi.js} +1 -1
- package/static/dashboard/assets/{ModelAssignmentsPanel-BLi_zbMa.js → ModelAssignmentsPanel-BRjZ-arB.js} +1 -1
- package/static/dashboard/assets/{ModelsPage-CxdpgnfR.js → ModelsPage-BtTU6du3.js} +6 -6
- package/static/dashboard/assets/NetworkPage-CV9qpkDg.js +2 -0
- package/static/dashboard/assets/{PaneListHeader-BBCMei0r.js → PaneListHeader-KyPTTBsv.js} +1 -1
- package/static/dashboard/assets/{SearchIndexingPanel-Ck4Y-xjR.js → SearchIndexingPanel-DolHGawg.js} +1 -1
- package/static/dashboard/assets/{StatusSubjectPanel-D1KWfAXE.js → StatusSubjectPanel-_YZvKiYi.js} +1 -1
- package/static/dashboard/assets/{StatusWorkspace-JbA5gzXx.js → StatusWorkspace-Dlbh_G40.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsPage-BbwQWsSR.js → SystemSettingsPage-Be7QSIoz.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsSubjectPanel-N117nMt5.js → SystemSettingsSubjectPanel-DBp0gja7.js} +1 -1
- package/static/dashboard/assets/{XpodAiConnectionsPodStore-CdDOb4SV.js → XpodAiConnectionsPodStore-ClpSjzpP.js} +7 -7
- package/static/dashboard/assets/{activity-DX1I96o_.js → activity-lsNbTXJu.js} +1 -1
- package/static/dashboard/assets/ai-connections-CXp5gd1J.js +1 -0
- package/static/dashboard/assets/{badge-k2vhtDqH.js → badge-CVatKjaG.js} +1 -1
- package/static/dashboard/assets/{collection-runtime-BFQ8teQJ.js → collection-runtime-Ec4UnY28.js} +1 -1
- package/static/dashboard/assets/{dashboard-DWZ-fmCT.js → dashboard-BEzsRsvF.js} +2 -2
- package/static/dashboard/assets/{dialog-1CCw-iHT.js → dialog-BuyelQ4V.js} +1 -1
- package/static/dashboard/assets/{download-C6-SNY1q.js → download-B4Nf678F.js} +1 -1
- package/static/dashboard/assets/{external-link-BgPcZ_j2.js → external-link-PYv9CvKL.js} +1 -1
- package/static/dashboard/assets/index-C9XPE-mI.js +4 -0
- package/static/dashboard/assets/{index-D7A8U6Pt.js → index-Cx69bTNh.js} +1 -1
- package/static/dashboard/assets/{index-6LcIUIYO.js → index-awr7ulur.js} +1 -1
- package/static/dashboard/assets/{key-round-BOd7Jo0Q.js → key-round-VsY80U1Z.js} +1 -1
- package/static/dashboard/assets/{rotate-ccw-CCgJqsvx.js → rotate-ccw-Cz1K4vE9.js} +1 -1
- package/static/dashboard/assets/{skeleton-Bc7abAn5.js → skeleton-BhNv_8tO.js} +1 -1
- package/static/dashboard/assets/{waypoints-s-opmJxx.js → waypoints-DYS9XFYV.js} +1 -1
- package/static/dashboard/assets/{workspace-layout-DqIQeTBV.js → workspace-layout-OZJAFx5V.js} +1 -1
- package/static/dashboard/dashboard.html +1 -1
- package/static/settings/assets/{AiConfigContext-BB9KZySa.js → AiConfigContext-B8JS3MXF.js} +1 -1
- package/static/settings/assets/{AiConfigPage-DGSXUkLs.js → AiConfigPage-C3Zl8LUl.js} +1 -1
- package/static/settings/assets/{DocumentProcessingPanel-Da2Re6Rg.js → DocumentProcessingPanel-DpDZAQvf.js} +1 -1
- package/static/settings/assets/{IndexLifecyclePanel-BSZuIzgr.js → IndexLifecyclePanel-Ec1XF88t.js} +1 -1
- package/static/settings/assets/{IndexSubjectPanel-CFd0ay-r.js → IndexSubjectPanel-BulT9BmO.js} +1 -1
- package/static/settings/assets/{ModelAssignmentsPanel-CSAryvWJ.js → ModelAssignmentsPanel-BcGSmYjb.js} +1 -1
- package/static/settings/assets/{ModelsPage-BQwCwLHU.js → ModelsPage-CvTCKy1T.js} +6 -6
- package/static/settings/assets/NetworkPage-DQF5u9Bn.js +2 -0
- package/static/settings/assets/{PaneListHeader-Bjh3hRdQ.js → PaneListHeader-D40hqcVl.js} +1 -1
- package/static/settings/assets/{SearchIndexingPanel-MjKL5QLU.js → SearchIndexingPanel-iCUPOx_0.js} +1 -1
- package/static/settings/assets/{StatusSubjectPanel-Bvl6K4mx.js → StatusSubjectPanel-E--ZHSql.js} +1 -1
- package/static/settings/assets/{StatusWorkspace-B0NzrP--.js → StatusWorkspace-YjDAx1II.js} +1 -1
- package/static/settings/assets/{SystemSettingsPage-D2z6Z4FE.js → SystemSettingsPage-CDdV3mC9.js} +1 -1
- package/static/settings/assets/{SystemSettingsSubjectPanel-4sxma4X4.js → SystemSettingsSubjectPanel-Br8WazDq.js} +1 -1
- package/static/settings/assets/XpodAiConnectionsPodStore-CLr38P_Z.js +3 -0
- package/static/settings/assets/{activity-CgJJGpjx.js → activity-C5DAHHTE.js} +1 -1
- package/static/settings/assets/ai-connections-C6yaE6WQ.js +1 -0
- package/static/settings/assets/{badge-C4NypVyT.js → badge-D8eIyxKt.js} +1 -1
- package/static/settings/assets/{collection-runtime-CTLCDxAi.js → collection-runtime-DLc9zil8.js} +1 -1
- package/static/settings/assets/{dialog-Csq0vWUi.js → dialog-CyuR7Va4.js} +1 -1
- package/static/settings/assets/{download-DaLJJ-Wp.js → download-c0oxZrCz.js} +1 -1
- package/static/settings/assets/{external-link--w_iW5Au.js → external-link-D3Z34fP_.js} +1 -1
- package/static/settings/assets/{index-BukHiu4y.js → index-CKGbRFlc.js} +1 -1
- package/static/settings/assets/index-CSr3-2Cj.js +4 -0
- package/static/settings/assets/{index-COmVnZi2.js → index-ComidxAm.js} +1 -1
- package/static/settings/assets/{index-browser-BGpvHwD0.js → index-browser-CAscEbae.js} +1 -1
- package/static/settings/assets/{key-round-Bk4YRjBu.js → key-round-DyjLmXuB.js} +1 -1
- package/static/settings/assets/{rotate-ccw-TCabbqsr.js → rotate-ccw-679HF_ec.js} +1 -1
- package/static/settings/assets/{settings-CJWpdbNC.js → settings-DKknqu4C.js} +3 -3
- package/static/settings/assets/{skeleton-JDHYVe7t.js → skeleton-CkopNkPB.js} +1 -1
- package/static/settings/assets/{waypoints-DDvEl-MU.js → waypoints-CrqfAftE.js} +1 -1
- package/static/settings/assets/{workspace-layout-DV5QU30U.js → workspace-layout-UN6c4qTG.js} +1 -1
- package/static/settings/settings.html +1 -1
- package/static/auth-callback/assets/NetworkPage-B3qBfANA.js +0 -2
- package/static/auth-callback/assets/XpodAiConnectionsPodStore-BJiXm-PF.js +0 -3
- package/static/auth-callback/assets/ai-connections-CryuHGKW.js +0 -1
- package/static/auth-callback/assets/index-DlLYWOhw.js +0 -4
- package/static/dashboard/assets/NetworkPage-BAIPw-D_.js +0 -2
- package/static/dashboard/assets/ai-connections-DwCRqOQa.js +0 -1
- package/static/dashboard/assets/index-UD6QOE7H.js +0 -4
- package/static/settings/assets/NetworkPage-BKymvsQc.js +0 -2
- package/static/settings/assets/XpodAiConnectionsPodStore-BkNQ8fZx.js +0 -3
- package/static/settings/assets/ai-connections-CryuHGKW.js +0 -1
- package/static/settings/assets/index-B0mQa59b.js +0 -4
- /package/node_modules/@undefineds.co/ai-connections/dist/{client → contract/client}/request.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client → contract/client}/types.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/base-adapter.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/base-adapter.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/codex.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/codex.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/index.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/index.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/json-env-adapter.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/json-env-adapter.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/pi.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/pi.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/transaction.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/transaction.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/types.d.ts +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{client-config → contract/client-config}/types.js +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{credential-storage.d.ts → contract/credential-storage.d.ts} +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{credential-storage.js → contract/credential-storage.js} +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{endpoint-urls.d.ts → contract/endpoint-urls.d.ts} +0 -0
- /package/node_modules/@undefineds.co/ai-connections/dist/{endpoint-urls.js → contract/endpoint-urls.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D983R1FV.js","assets/admin-C6qCRFiY.js","assets/activity-CeM7xly8.js","assets/external-link-THLDL4On.js","assets/index-BlVZb9A7.js","assets/index-BRpv4yO3.js","assets/download-C2ir4lmR.js","assets/key-round-C9U5j1Ly.js","assets/NetworkPage-CG9RelJA.js","assets/PaneListHeader-yvd5ohs6.js","assets/waypoints-uqFQ3uEG.js","assets/workspace-layout-DLYK0Wwu.js","assets/badge-qJo2Zr4d.js","assets/rotate-ccw-DP45cD4o.js","assets/StatusWorkspace-CBdRahCF.js","assets/StatusSubjectPanel-8qtVxnzC.js","assets/IndexSubjectPanel-CYyLOlQU.js","assets/skeleton-Dn4EiSCS.js","assets/ModelsPage-DwyITxt7.js","assets/ai-connections-C6yaE6WQ.js","assets/XpodAiConnectionsPodStore-V6vgGfuw.js","assets/index-browser-3FvR0aaf.js","assets/dialog-D-h6x5x0.js","assets/AiConfigPage-fe-xMIXa.js","assets/AiConfigContext-DCXpjzpj.js","assets/ModelAssignmentsPanel-BOvUH4yr.js","assets/DocumentProcessingPanel-BGnkfMuU.js","assets/SearchIndexingPanel-2_a6ezzj.js","assets/IndexLifecyclePanel-42Jups0j.js","assets/SystemSettingsPage-BZJ6vWkg.js","assets/settings-projection-CUkyprDQ.js","assets/SystemSettingsSubjectPanel-xm08UhXP.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
function _mergeNamespaces(n,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in n)){const a=Object.getOwnPropertyDescriptor(i,s);a&&Object.defineProperty(n,s,a.get?a:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function t(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=t(s);fetch(s.href,a)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function i(){var s=!1;try{s=this instanceof i}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var s=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return n[i]}})}),t}var jsxRuntime={exports:{}},reactJsxRuntime_production={};var hasRequiredReactJsxRuntime_production;function requireReactJsxRuntime_production(){if(hasRequiredReactJsxRuntime_production)return reactJsxRuntime_production;hasRequiredReactJsxRuntime_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,s,a){var l=null;if(a!==void 0&&(l=""+a),s.key!==void 0&&(l=""+s.key),"key"in s){a={};for(var u in s)u!=="key"&&(a[u]=s[u])}else a=s;return s=a.ref,{$$typeof:n,type:i,key:l,ref:s!==void 0?s:null,props:a}}return reactJsxRuntime_production.Fragment=e,reactJsxRuntime_production.jsx=t,reactJsxRuntime_production.jsxs=t,reactJsxRuntime_production}var hasRequiredJsxRuntime;function requireJsxRuntime(){return hasRequiredJsxRuntime||(hasRequiredJsxRuntime=1,jsxRuntime.exports=requireReactJsxRuntime_production()),jsxRuntime.exports}var jsxRuntimeExports=requireJsxRuntime(),client={exports:{}},reactDomClient_production={},scheduler={exports:{}},scheduler_production={};var hasRequiredScheduler_production;function requireScheduler_production(){return hasRequiredScheduler_production||(hasRequiredScheduler_production=1,(function(n){function e(he,Oe){var ce=he.length;he.push(Oe);e:for(;0<ce;){var Ue=ce-1>>>1,O=he[Ue];if(0<s(O,Oe))he[Ue]=Oe,he[ce]=O,ce=Ue;else break e}}function t(he){return he.length===0?null:he[0]}function i(he){if(he.length===0)return null;var Oe=he[0],ce=he.pop();if(ce!==Oe){he[0]=ce;e:for(var Ue=0,O=he.length,W=O>>>1;Ue<W;){var de=2*(Ue+1)-1,te=he[de],Te=de+1,je=he[Te];if(0>s(te,ce))Te<O&&0>s(je,te)?(he[Ue]=je,he[Te]=ce,Ue=Te):(he[Ue]=te,he[de]=ce,Ue=de);else if(Te<O&&0>s(je,ce))he[Ue]=je,he[Te]=ce,Ue=Te;else break e}}return Oe}function s(he,Oe){var ce=he.sortIndex-Oe.sortIndex;return ce!==0?ce:he.id-Oe.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;n.unstable_now=function(){return a.now()}}else{var l=Date,u=l.now();n.unstable_now=function(){return l.now()-u}}var h=[],d=[],p=1,g=null,m=3,v=!1,S=!1,E=!1,w=!1,A=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function F(he){for(var Oe=t(d);Oe!==null;){if(Oe.callback===null)i(d);else if(Oe.startTime<=he)i(d),Oe.sortIndex=Oe.expirationTime,e(h,Oe);else break;Oe=t(d)}}function P(he){if(E=!1,F(he),!S)if(t(h)!==null)S=!0,M||(M=!0,Se());else{var Oe=t(d);Oe!==null&&ke(P,Oe.startTime-he)}}var M=!1,$=-1,G=5,fe=-1;function B(){return w?!0:!(n.unstable_now()-fe<G)}function ee(){if(w=!1,M){var he=n.unstable_now();fe=he;var Oe=!0;try{e:{S=!1,E&&(E=!1,C($),$=-1),v=!0;var ce=m;try{t:{for(F(he),g=t(h);g!==null&&!(g.expirationTime>he&&B());){var Ue=g.callback;if(typeof Ue=="function"){g.callback=null,m=g.priorityLevel;var O=Ue(g.expirationTime<=he);if(he=n.unstable_now(),typeof O=="function"){g.callback=O,F(he),Oe=!0;break t}g===t(h)&&i(h),F(he)}else i(h);g=t(h)}if(g!==null)Oe=!0;else{var W=t(d);W!==null&&ke(P,W.startTime-he),Oe=!1}}break e}finally{g=null,m=ce,v=!1}Oe=void 0}}finally{Oe?Se():M=!1}}}var Se;if(typeof T=="function")Se=function(){T(ee)};else if(typeof MessageChannel<"u"){var re=new MessageChannel,Ae=re.port2;re.port1.onmessage=ee,Se=function(){Ae.postMessage(null)}}else Se=function(){A(ee,0)};function ke(he,Oe){$=A(function(){he(n.unstable_now())},Oe)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(he){he.callback=null},n.unstable_forceFrameRate=function(he){0>he||125<he?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):G=0<he?Math.floor(1e3/he):5},n.unstable_getCurrentPriorityLevel=function(){return m},n.unstable_next=function(he){switch(m){case 1:case 2:case 3:var Oe=3;break;default:Oe=m}var ce=m;m=Oe;try{return he()}finally{m=ce}},n.unstable_requestPaint=function(){w=!0},n.unstable_runWithPriority=function(he,Oe){switch(he){case 1:case 2:case 3:case 4:case 5:break;default:he=3}var ce=m;m=he;try{return Oe()}finally{m=ce}},n.unstable_scheduleCallback=function(he,Oe,ce){var Ue=n.unstable_now();switch(typeof ce=="object"&&ce!==null?(ce=ce.delay,ce=typeof ce=="number"&&0<ce?Ue+ce:Ue):ce=Ue,he){case 1:var O=-1;break;case 2:O=250;break;case 5:O=1073741823;break;case 4:O=1e4;break;default:O=5e3}return O=ce+O,he={id:p++,callback:Oe,priorityLevel:he,startTime:ce,expirationTime:O,sortIndex:-1},ce>Ue?(he.sortIndex=ce,e(d,he),t(h)===null&&he===t(d)&&(E?(C($),$=-1):E=!0,ke(P,ce-Ue))):(he.sortIndex=O,e(h,he),S||v||(S=!0,M||(M=!0,Se()))),he},n.unstable_shouldYield=B,n.unstable_wrapCallback=function(he){var Oe=m;return function(){var ce=m;m=Oe;try{return he.apply(this,arguments)}finally{m=ce}}}})(scheduler_production)),scheduler_production}var hasRequiredScheduler;function requireScheduler(){return hasRequiredScheduler||(hasRequiredScheduler=1,scheduler.exports=requireScheduler_production()),scheduler.exports}var react={exports:{}},react_production={};var hasRequiredReact_production;function requireReact_production(){if(hasRequiredReact_production)return react_production;hasRequiredReact_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),m=Symbol.iterator;function v(W){return W===null||typeof W!="object"?null:(W=m&&W[m]||W["@@iterator"],typeof W=="function"?W:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,w={};function A(W,de,te){this.props=W,this.context=de,this.refs=w,this.updater=te||S}A.prototype.isReactComponent={},A.prototype.setState=function(W,de){if(typeof W!="object"&&typeof W!="function"&&W!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,W,de,"setState")},A.prototype.forceUpdate=function(W){this.updater.enqueueForceUpdate(this,W,"forceUpdate")};function C(){}C.prototype=A.prototype;function T(W,de,te){this.props=W,this.context=de,this.refs=w,this.updater=te||S}var F=T.prototype=new C;F.constructor=T,E(F,A.prototype),F.isPureReactComponent=!0;var P=Array.isArray;function M(){}var $={H:null,A:null,T:null,S:null},G=Object.prototype.hasOwnProperty;function fe(W,de,te){var Te=te.ref;return{$$typeof:n,type:W,key:de,ref:Te!==void 0?Te:null,props:te}}function B(W,de){return fe(W.type,de,W.props)}function ee(W){return typeof W=="object"&&W!==null&&W.$$typeof===n}function Se(W){var de={"=":"=0",":":"=2"};return"$"+W.replace(/[=:]/g,function(te){return de[te]})}var re=/\/+/g;function Ae(W,de){return typeof W=="object"&&W!==null&&W.key!=null?Se(""+W.key):de.toString(36)}function ke(W){switch(W.status){case"fulfilled":return W.value;case"rejected":throw W.reason;default:switch(typeof W.status=="string"?W.then(M,M):(W.status="pending",W.then(function(de){W.status==="pending"&&(W.status="fulfilled",W.value=de)},function(de){W.status==="pending"&&(W.status="rejected",W.reason=de)})),W.status){case"fulfilled":return W.value;case"rejected":throw W.reason}}throw W}function he(W,de,te,Te,je){var He=typeof W;(He==="undefined"||He==="boolean")&&(W=null);var We=!1;if(W===null)We=!0;else switch(He){case"bigint":case"string":case"number":We=!0;break;case"object":switch(W.$$typeof){case n:case e:We=!0;break;case p:return We=W._init,he(We(W._payload),de,te,Te,je)}}if(We)return je=je(W),We=Te===""?"."+Ae(W,0):Te,P(je)?(te="",We!=null&&(te=We.replace(re,"$&/")+"/"),he(je,de,te,"",function(Be){return Be})):je!=null&&(ee(je)&&(je=B(je,te+(je.key==null||W&&W.key===je.key?"":(""+je.key).replace(re,"$&/")+"/")+We)),de.push(je)),1;We=0;var me=Te===""?".":Te+":";if(P(W))for(var ge=0;ge<W.length;ge++)Te=W[ge],He=me+Ae(Te,ge),We+=he(Te,de,te,He,je);else if(ge=v(W),typeof ge=="function")for(W=ge.call(W),ge=0;!(Te=W.next()).done;)Te=Te.value,He=me+Ae(Te,ge++),We+=he(Te,de,te,He,je);else if(He==="object"){if(typeof W.then=="function")return he(ke(W),de,te,Te,je);throw de=String(W),Error("Objects are not valid as a React child (found: "+(de==="[object Object]"?"object with keys {"+Object.keys(W).join(", ")+"}":de)+"). If you meant to render a collection of children, use an array instead.")}return We}function Oe(W,de,te){if(W==null)return W;var Te=[],je=0;return he(W,Te,"","",function(He){return de.call(te,He,je++)}),Te}function ce(W){if(W._status===-1){var de=W._result;de=de(),de.then(function(te){(W._status===0||W._status===-1)&&(W._status=1,W._result=te)},function(te){(W._status===0||W._status===-1)&&(W._status=2,W._result=te)}),W._status===-1&&(W._status=0,W._result=de)}if(W._status===1)return W._result.default;throw W._result}var Ue=typeof reportError=="function"?reportError:function(W){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var de=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof W=="object"&&W!==null&&typeof W.message=="string"?String(W.message):String(W),error:W});if(!window.dispatchEvent(de))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",W);return}console.error(W)},O={map:Oe,forEach:function(W,de,te){Oe(W,function(){de.apply(this,arguments)},te)},count:function(W){var de=0;return Oe(W,function(){de++}),de},toArray:function(W){return Oe(W,function(de){return de})||[]},only:function(W){if(!ee(W))throw Error("React.Children.only expected to receive a single React element child.");return W}};return react_production.Activity=g,react_production.Children=O,react_production.Component=A,react_production.Fragment=t,react_production.Profiler=s,react_production.PureComponent=T,react_production.StrictMode=i,react_production.Suspense=h,react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=$,react_production.__COMPILER_RUNTIME={__proto__:null,c:function(W){return $.H.useMemoCache(W)}},react_production.cache=function(W){return function(){return W.apply(null,arguments)}},react_production.cacheSignal=function(){return null},react_production.cloneElement=function(W,de,te){if(W==null)throw Error("The argument must be a React element, but you passed "+W+".");var Te=E({},W.props),je=W.key;if(de!=null)for(He in de.key!==void 0&&(je=""+de.key),de)!G.call(de,He)||He==="key"||He==="__self"||He==="__source"||He==="ref"&&de.ref===void 0||(Te[He]=de[He]);var He=arguments.length-2;if(He===1)Te.children=te;else if(1<He){for(var We=Array(He),me=0;me<He;me++)We[me]=arguments[me+2];Te.children=We}return fe(W.type,je,Te)},react_production.createContext=function(W){return W={$$typeof:l,_currentValue:W,_currentValue2:W,_threadCount:0,Provider:null,Consumer:null},W.Provider=W,W.Consumer={$$typeof:a,_context:W},W},react_production.createElement=function(W,de,te){var Te,je={},He=null;if(de!=null)for(Te in de.key!==void 0&&(He=""+de.key),de)G.call(de,Te)&&Te!=="key"&&Te!=="__self"&&Te!=="__source"&&(je[Te]=de[Te]);var We=arguments.length-2;if(We===1)je.children=te;else if(1<We){for(var me=Array(We),ge=0;ge<We;ge++)me[ge]=arguments[ge+2];je.children=me}if(W&&W.defaultProps)for(Te in We=W.defaultProps,We)je[Te]===void 0&&(je[Te]=We[Te]);return fe(W,He,je)},react_production.createRef=function(){return{current:null}},react_production.forwardRef=function(W){return{$$typeof:u,render:W}},react_production.isValidElement=ee,react_production.lazy=function(W){return{$$typeof:p,_payload:{_status:-1,_result:W},_init:ce}},react_production.memo=function(W,de){return{$$typeof:d,type:W,compare:de===void 0?null:de}},react_production.startTransition=function(W){var de=$.T,te={};$.T=te;try{var Te=W(),je=$.S;je!==null&&je(te,Te),typeof Te=="object"&&Te!==null&&typeof Te.then=="function"&&Te.then(M,Ue)}catch(He){Ue(He)}finally{de!==null&&te.types!==null&&(de.types=te.types),$.T=de}},react_production.unstable_useCacheRefresh=function(){return $.H.useCacheRefresh()},react_production.use=function(W){return $.H.use(W)},react_production.useActionState=function(W,de,te){return $.H.useActionState(W,de,te)},react_production.useCallback=function(W,de){return $.H.useCallback(W,de)},react_production.useContext=function(W){return $.H.useContext(W)},react_production.useDebugValue=function(){},react_production.useDeferredValue=function(W,de){return $.H.useDeferredValue(W,de)},react_production.useEffect=function(W,de){return $.H.useEffect(W,de)},react_production.useEffectEvent=function(W){return $.H.useEffectEvent(W)},react_production.useId=function(){return $.H.useId()},react_production.useImperativeHandle=function(W,de,te){return $.H.useImperativeHandle(W,de,te)},react_production.useInsertionEffect=function(W,de){return $.H.useInsertionEffect(W,de)},react_production.useLayoutEffect=function(W,de){return $.H.useLayoutEffect(W,de)},react_production.useMemo=function(W,de){return $.H.useMemo(W,de)},react_production.useOptimistic=function(W,de){return $.H.useOptimistic(W,de)},react_production.useReducer=function(W,de,te){return $.H.useReducer(W,de,te)},react_production.useRef=function(W){return $.H.useRef(W)},react_production.useState=function(W){return $.H.useState(W)},react_production.useSyncExternalStore=function(W,de,te){return $.H.useSyncExternalStore(W,de,te)},react_production.useTransition=function(){return $.H.useTransition()},react_production.version="19.2.8",react_production}var hasRequiredReact;function requireReact(){return hasRequiredReact||(hasRequiredReact=1,react.exports=requireReact_production()),react.exports}var reactDom={exports:{}},reactDom_production={};var hasRequiredReactDom_production;function requireReactDom_production(){if(hasRequiredReactDom_production)return reactDom_production;hasRequiredReactDom_production=1;var n=requireReact();function e(h){var d="https://react.dev/errors/"+h;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)d+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+h+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function t(){}var i={d:{f:t,r:function(){throw Error(e(522))},D:t,C:t,L:t,m:t,X:t,S:t,M:t},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(h,d,p){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:g==null?null:""+g,children:h,containerInfo:d,implementation:p}}var l=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function u(h,d){if(h==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,reactDom_production.createPortal=function(h,d){var p=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return a(h,d,null,p)},reactDom_production.flushSync=function(h){var d=l.T,p=i.p;try{if(l.T=null,i.p=2,h)return h()}finally{l.T=d,i.p=p,i.d.f()}},reactDom_production.preconnect=function(h,d){typeof h=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,i.d.C(h,d))},reactDom_production.prefetchDNS=function(h){typeof h=="string"&&i.d.D(h)},reactDom_production.preinit=function(h,d){if(typeof h=="string"&&d&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin),m=typeof d.integrity=="string"?d.integrity:void 0,v=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;p==="style"?i.d.S(h,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:g,integrity:m,fetchPriority:v}):p==="script"&&i.d.X(h,{crossOrigin:g,integrity:m,fetchPriority:v,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},reactDom_production.preinitModule=function(h,d){if(typeof h=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var p=u(d.as,d.crossOrigin);i.d.M(h,{crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&i.d.M(h)},reactDom_production.preload=function(h,d){if(typeof h=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin);i.d.L(h,p,{crossOrigin:g,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},reactDom_production.preloadModule=function(h,d){if(typeof h=="string")if(d){var p=u(d.as,d.crossOrigin);i.d.m(h,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else i.d.m(h)},reactDom_production.requestFormReset=function(h){i.d.r(h)},reactDom_production.unstable_batchedUpdates=function(h,d){return h(d)},reactDom_production.useFormState=function(h,d,p){return l.H.useFormState(h,d,p)},reactDom_production.useFormStatus=function(){return l.H.useHostTransitionStatus()},reactDom_production.version="19.2.8",reactDom_production}var hasRequiredReactDom;function requireReactDom(){if(hasRequiredReactDom)return reactDom.exports;hasRequiredReactDom=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),reactDom.exports=requireReactDom_production(),reactDom.exports}var hasRequiredReactDomClient_production;function requireReactDomClient_production(){if(hasRequiredReactDomClient_production)return reactDomClient_production;hasRequiredReactDomClient_production=1;var n=requireScheduler(),e=requireReact(),t=requireReactDom();function i(o){var c="https://react.dev/errors/"+o;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)c+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+o+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(o){return!(!o||o.nodeType!==1&&o.nodeType!==9&&o.nodeType!==11)}function a(o){var c=o,f=o;if(o.alternate)for(;c.return;)c=c.return;else{o=c;do c=o,(c.flags&4098)!==0&&(f=c.return),o=c.return;while(o)}return c.tag===3?f:null}function l(o){if(o.tag===13){var c=o.memoizedState;if(c===null&&(o=o.alternate,o!==null&&(c=o.memoizedState)),c!==null)return c.dehydrated}return null}function u(o){if(o.tag===31){var c=o.memoizedState;if(c===null&&(o=o.alternate,o!==null&&(c=o.memoizedState)),c!==null)return c.dehydrated}return null}function h(o){if(a(o)!==o)throw Error(i(188))}function d(o){var c=o.alternate;if(!c){if(c=a(o),c===null)throw Error(i(188));return c!==o?null:o}for(var f=o,y=c;;){var R=f.return;if(R===null)break;var D=R.alternate;if(D===null){if(y=R.return,y!==null){f=y;continue}break}if(R.child===D.child){for(D=R.child;D;){if(D===f)return h(R),o;if(D===y)return h(R),c;D=D.sibling}throw Error(i(188))}if(f.return!==y.return)f=R,y=D;else{for(var Z=!1,ue=R.child;ue;){if(ue===f){Z=!0,f=R,y=D;break}if(ue===y){Z=!0,y=R,f=D;break}ue=ue.sibling}if(!Z){for(ue=D.child;ue;){if(ue===f){Z=!0,f=D,y=R;break}if(ue===y){Z=!0,y=D,f=R;break}ue=ue.sibling}if(!Z)throw Error(i(189))}}if(f.alternate!==y)throw Error(i(190))}if(f.tag!==3)throw Error(i(188));return f.stateNode.current===f?o:c}function p(o){var c=o.tag;if(c===5||c===26||c===27||c===6)return o;for(o=o.child;o!==null;){if(c=p(o),c!==null)return c;o=o.sibling}return null}var g=Object.assign,m=Symbol.for("react.element"),v=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),C=Symbol.for("react.consumer"),T=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),$=Symbol.for("react.memo"),G=Symbol.for("react.lazy"),fe=Symbol.for("react.activity"),B=Symbol.for("react.memo_cache_sentinel"),ee=Symbol.iterator;function Se(o){return o===null||typeof o!="object"?null:(o=ee&&o[ee]||o["@@iterator"],typeof o=="function"?o:null)}var re=Symbol.for("react.client.reference");function Ae(o){if(o==null)return null;if(typeof o=="function")return o.$$typeof===re?null:o.displayName||o.name||null;if(typeof o=="string")return o;switch(o){case E:return"Fragment";case A:return"Profiler";case w:return"StrictMode";case P:return"Suspense";case M:return"SuspenseList";case fe:return"Activity"}if(typeof o=="object")switch(o.$$typeof){case S:return"Portal";case T:return o.displayName||"Context";case C:return(o._context.displayName||"Context")+".Consumer";case F:var c=o.render;return o=o.displayName,o||(o=c.displayName||c.name||"",o=o!==""?"ForwardRef("+o+")":"ForwardRef"),o;case $:return c=o.displayName||null,c!==null?c:Ae(o.type)||"Memo";case G:c=o._payload,o=o._init;try{return Ae(o(c))}catch{}}return null}var ke=Array.isArray,he=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Oe=t.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ce={pending:!1,data:null,method:null,action:null},Ue=[],O=-1;function W(o){return{current:o}}function de(o){0>O||(o.current=Ue[O],Ue[O]=null,O--)}function te(o,c){O++,Ue[O]=o.current,o.current=c}var Te=W(null),je=W(null),He=W(null),We=W(null);function me(o,c){switch(te(He,c),te(je,o),te(Te,null),c.nodeType){case 9:case 11:o=(o=c.documentElement)&&(o=o.namespaceURI)?Of(o):0;break;default:if(o=c.tagName,c=c.namespaceURI)c=Of(c),o=Mf(c,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}de(Te),te(Te,o)}function ge(){de(Te),de(je),de(He)}function Be(o){o.memoizedState!==null&&te(We,o);var c=Te.current,f=Mf(c,o.type);c!==f&&(te(je,o),te(Te,f))}function ie(o){je.current===o&&(de(Te),de(je)),We.current===o&&(de(We),ao._currentValue=ce)}var q,N;function k(o){if(q===void 0)try{throw Error()}catch(f){var c=f.stack.trim().match(/\n( *(at )?)/);q=c&&c[1]||"",N=-1<f.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<f.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+q+o+N}var H=!1;function ne(o,c){if(!o||H)return"";H=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var y={DetermineComponentFrameRoot:function(){try{if(c){var ft=function(){throw Error()};if(Object.defineProperty(ft.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ft,[])}catch(st){var rt=st}Reflect.construct(o,[],ft)}else{try{ft.call()}catch(st){rt=st}o.call(ft.prototype)}}else{try{throw Error()}catch(st){rt=st}(ft=o())&&typeof ft.catch=="function"&&ft.catch(function(){})}}catch(st){if(st&&rt&&typeof st.stack=="string")return[st.stack,rt.stack]}return[null,null]}};y.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var R=Object.getOwnPropertyDescriptor(y.DetermineComponentFrameRoot,"name");R&&R.configurable&&Object.defineProperty(y.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var D=y.DetermineComponentFrameRoot(),Z=D[0],ue=D[1];if(Z&&ue){var $e=Z.split(`
|
|
@@ -120,7 +120,7 @@ LIMIT 50`,prefixes:{}},d=s.kind==="sparql"?await this.dialect.executeOnResource(
|
|
|
120
120
|
VALUES ?linkPred { ${u} }
|
|
121
121
|
?parent ?linkPred ?child .
|
|
122
122
|
OPTIONAL { ?child ?pred ?obj . }
|
|
123
|
-
}`,prefixes:{}},F=await h.executeQueryWithSource(T,w);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(w=>{const A=this.normalizeInlineIri(w.parent),C=this.normalizeInlineIri(w.linkPred),T=this.normalizeInlineIri(w.child),F=this.normalizeInlineIri(w.pred),P=this.normalizeInlineObjectValue(w.obj);if(!A||!C)return;const M=a.get(C);if(M){const B=m.get(A)??new Map,ee=B.get(M.name)??[];T&&!ee.includes(T)&&ee.push(T),B.set(M.name,ee),m.set(A,B)}if(!T||!F)return;const $=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},G=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,$);return}const fe=$[G];fe===void 0?$[G]=P:Array.isArray(fe)?$[G]=[...fe,P]:$[G]=[fe,P],v.set(T,$)});const S=w=>{if(Array.isArray(w))return w.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(w);return A?[A]:[]},E=(w,A,C)=>{const T=w?m.get(w)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(M=>v.get(M)??{"@id":M,id:this.extractIdFromSubject(M,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(w=>{const A=this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id);s.forEach(C=>{w[C.name]=E(A,w[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const a of this.orderByClauses){const l=this.getOrderByValue(i,a.column),u=this.getOrderByValue(s,a.column),h=this.compareOrderByValues(l,u);if(h!==0)return a.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const a=this.serializeValueForKey(s);t.has(a)||(t.add(a),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(a=>{const l=this.normalizeInlineIri(a["@id"])??this.normalizeInlineIri(a.subject)??this.normalizeInlineIri(a.uri)??(typeof a.id=="string"?a.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...a});return}if(!t.has(l)){const d={...a};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(a).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=h(A);S.some(T=>h(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),w=E?.options?.isArray||E?.dataType==="array";!w&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):w?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(a=>t.get(a))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const w=this.serializeValueForKey(E);u.has(w)||u.set(w,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(a.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const w=d(),C=await(conditionTargetsReservedIdentifier(E)?w.applyInternalQueryCondition(E):w.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,h);if(m){const S=d(),w=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,w)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=a.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],w=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,M=this.getRowValueForColumn(m,P);if(M==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(G=>{const fe=d.get(G);if(!fe)return!0;const ee=(fe.left.alias===e.alias?fe.left:fe.right)===fe.left?fe.right:fe.left,Se=this.getRowValueForColumn(m,ee);return Se==null})));A=!0;break}const $=e.table.getColumn(F.column);if(!$){A=!0;break}E.push(eq($,M)),w.push(`${F.column}:${this.serializeValueForKey(M)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const $=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,G=this.getRowValueForColumn(m,$);return G==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=w.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),a=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${a}, join.${a})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const a=this.extractSubjectValue(i);if(a){s.subject=a,s["@id"]=a,s.uri=a,s[`${e.alias}.subject`]=a,s[`${e.alias}.@id`]=a,s[`${e.alias}.uri`]=a;const l=this.extractIdFromSubject(a,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[a]=s,l=a.left.alias===t.alias?a.left:a.right,u=l===a.left?a.right:a.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);h.has(m)||h.set(m,[]),h.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?h.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(a=>{const l=a.left.alias===i?a.left:a.right,u=l===a.left?a.right:a.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,a=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(a.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const a=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return a==null;case"IS NOT NULL":return a!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(a=>this.evaluateCondition(e,a)):i.toUpperCase()==="OR"?s.some(a=>this.evaluateCondition(e,a)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const a=parsePodResourceRef(t,e);if(a)return a.templateValues.id??a.resourceId}if(t){const a=this.session.getDialect?.(),u=(a?.getUriResolver?.()??new UriResolverImpl(a?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const a=e.slice(s+1);if(a.length>0)return a}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(a=>a.id||a["@id"]).filter(a=>typeof a=="string"&&a.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),a=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(a),a}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(a){console.error("[InsertQueryBuilder] afterInsert hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[a,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);for(const[a,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const a=e;return a.length===0?a():a(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):a;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,a])=>Array.isArray(a));return s.length===0?i:i.map(a=>{const l={...a};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const a of e)try{await t.afterUpdate(i,a,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):a;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(a){console.error("[DeleteQueryBuilder] afterDelete hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(a=>i.unregisterResourceSubject?.(e.table,a));return}s.forEach(a=>i.registerResourceSubject?.(e.table,a))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const a=this.getKnownRowIri(s);a&&i.add(a)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,a,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,a,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-DtU38ni3.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),a=new Map;s.headers&&s.headers.forEach((h,d)=>{a.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return a.get(d)||null},has:h=>{const d=h.toLowerCase();return a.has(d)},forEach:h=>{a.forEach((d,p)=>h(d,p))},entries:()=>a.entries(),keys:()=>a.keys(),values:()=>a.values(),[Symbol.iterator]:()=>a.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(a=>{const l=a,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let a=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(a=d.headers.get("ETag"),this.logging&&a&&console.log(`[UPDATE] Got ETag for ${s}: ${a}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":a??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(a){i.push({success:!1,source:s,error:this.formatError(a)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
|
|
123
|
+
}`,prefixes:{}},F=await h.executeQueryWithSource(T,w);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(w=>{const A=this.normalizeInlineIri(w.parent),C=this.normalizeInlineIri(w.linkPred),T=this.normalizeInlineIri(w.child),F=this.normalizeInlineIri(w.pred),P=this.normalizeInlineObjectValue(w.obj);if(!A||!C)return;const M=a.get(C);if(M){const B=m.get(A)??new Map,ee=B.get(M.name)??[];T&&!ee.includes(T)&&ee.push(T),B.set(M.name,ee),m.set(A,B)}if(!T||!F)return;const $=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},G=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,$);return}const fe=$[G];fe===void 0?$[G]=P:Array.isArray(fe)?$[G]=[...fe,P]:$[G]=[fe,P],v.set(T,$)});const S=w=>{if(Array.isArray(w))return w.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(w);return A?[A]:[]},E=(w,A,C)=>{const T=w?m.get(w)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(M=>v.get(M)??{"@id":M,id:this.extractIdFromSubject(M,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(w=>{const A=this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id);s.forEach(C=>{w[C.name]=E(A,w[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const a of this.orderByClauses){const l=this.getOrderByValue(i,a.column),u=this.getOrderByValue(s,a.column),h=this.compareOrderByValues(l,u);if(h!==0)return a.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const a=this.serializeValueForKey(s);t.has(a)||(t.add(a),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(a=>{const l=this.normalizeInlineIri(a["@id"])??this.normalizeInlineIri(a.subject)??this.normalizeInlineIri(a.uri)??(typeof a.id=="string"?a.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...a});return}if(!t.has(l)){const d={...a};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(a).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=h(A);S.some(T=>h(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),w=E?.options?.isArray||E?.dataType==="array";!w&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):w?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(a=>t.get(a))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const w=this.serializeValueForKey(E);u.has(w)||u.set(w,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(a.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const w=d(),C=await(conditionTargetsReservedIdentifier(E)?w.applyInternalQueryCondition(E):w.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,h);if(m){const S=d(),w=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,w)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=a.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],w=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,M=this.getRowValueForColumn(m,P);if(M==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(G=>{const fe=d.get(G);if(!fe)return!0;const ee=(fe.left.alias===e.alias?fe.left:fe.right)===fe.left?fe.right:fe.left,Se=this.getRowValueForColumn(m,ee);return Se==null})));A=!0;break}const $=e.table.getColumn(F.column);if(!$){A=!0;break}E.push(eq($,M)),w.push(`${F.column}:${this.serializeValueForKey(M)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const $=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,G=this.getRowValueForColumn(m,$);return G==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=w.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),a=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${a}, join.${a})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const a=this.extractSubjectValue(i);if(a){s.subject=a,s["@id"]=a,s.uri=a,s[`${e.alias}.subject`]=a,s[`${e.alias}.@id`]=a,s[`${e.alias}.uri`]=a;const l=this.extractIdFromSubject(a,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[a]=s,l=a.left.alias===t.alias?a.left:a.right,u=l===a.left?a.right:a.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);h.has(m)||h.set(m,[]),h.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?h.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(a=>{const l=a.left.alias===i?a.left:a.right,u=l===a.left?a.right:a.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,a=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(a.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const a=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return a==null;case"IS NOT NULL":return a!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(a=>this.evaluateCondition(e,a)):i.toUpperCase()==="OR"?s.some(a=>this.evaluateCondition(e,a)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const a=parsePodResourceRef(t,e);if(a)return a.templateValues.id??a.resourceId}if(t){const a=this.session.getDialect?.(),u=(a?.getUriResolver?.()??new UriResolverImpl(a?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const a=e.slice(s+1);if(a.length>0)return a}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(a=>a.id||a["@id"]).filter(a=>typeof a=="string"&&a.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),a=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(a),a}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(a){console.error("[InsertQueryBuilder] afterInsert hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[a,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);for(const[a,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const a=e;return a.length===0?a():a(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):a;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,a])=>Array.isArray(a));return s.length===0?i:i.map(a=>{const l={...a};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const a of e)try{await t.afterUpdate(i,a,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):a;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(a){console.error("[DeleteQueryBuilder] afterDelete hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(a=>i.unregisterResourceSubject?.(e.table,a));return}s.forEach(a=>i.registerResourceSubject?.(e.table,a))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const a=this.getKnownRowIri(s);a&&i.add(a)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,a,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,a,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-3FvR0aaf.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),a=new Map;s.headers&&s.headers.forEach((h,d)=>{a.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return a.get(d)||null},has:h=>{const d=h.toLowerCase();return a.has(d)},forEach:h=>{a.forEach((d,p)=>h(d,p))},entries:()=>a.entries(),keys:()=>a.keys(),values:()=>a.values(),[Symbol.iterator]:()=>a.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(a=>{const l=a,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let a=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(a=d.headers.get("ETag"),this.logging&&a&&console.log(`[UPDATE] Got ETag for ${s}: ${a}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":a??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(a){i.push({success:!1,source:s,error:this.formatError(a)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
|
|
124
124
|
SELECT ?subject ?predicate ?object WHERE {
|
|
125
125
|
?subject ?predicate ?object .
|
|
126
126
|
FILTER(STRSTARTS(STR(?subject), "${i}"))
|
|
@@ -303,4 +303,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
303
303
|
`,prefixes:{ldp:"http://www.w3.org/ns/ldp#"}},a=await this.sparqlExecutor.queryContainer(t,s);for(const l of a){const u=l.resource;if(u){const h=hasStringValue(u)?u.value:String(u);i.push(h)}}}catch(s){console.warn("[listContainerResources] SPARQL query failed:",s)}return i}}_a=entityKind;PodDialect[_a]="PodDialect";function drizzle(n,e){if(!n||!n.info.isLoggedIn)throw new Error("需要有效的已认证Session");const t={session:n,preferredChannels:e?.notifications?.preferredChannels,createQueryEngine:e?.sparql?.createQueryEngine,disableInteropDiscovery:e?.disableInteropDiscovery,podUrl:e?.podUrl??n.info.podUrl,resourcePreparation:e?.resourcePreparation,storageTTL:e?.storageTTL,debug:e?.debug??e?.logger},i=new PodDialect(t);e?.schema&&i.setSchema(e.schema);const s=new PodAsyncSession(i);return new PodDatabase(i,s,e?.schema)}function createRepositoryDescriptor(n){const{namespace:e,table:t,searchableFields:i,defaultSort:s,cache:a}=n,l=n.searchAccessor??(A=>{const C=A?A.search:void 0;return typeof C=="string"?C:void 0}),u=n.transform??(A=>A),h={create:n.invalidations?.create??["list"],update:n.invalidations?.update??["list","detail"],remove:n.invalidations?.remove??["list","detail"]},d=A=>{const C=t[A];if(C)return C;const T=t.config?.name;return T?`${T}.${A}`:A},p=A=>{const C=[],T=l(A)?.trim();if(T&&i?.length){const P=`%${T}%`,M=i.map($=>like(d($),P));M.length===1?C.push(M[0]):M.length>1&&C.push(or(...M))}const F=n.filter?.({table:t,filters:A});if(F&&C.push(F),C.length!==0)return C.length===1?C[0]:and(...C)},g=async(A,C)=>{let T=A.select().from(t);const F=p(C);return F&&(T=T.where(F)),s&&(T=T.orderBy(d(s.field),s.direction)),(await T.execute()).map(M=>u(M))},m=async(A,C)=>{const T=await A.findByIri(t,C);return T?u(T):null},v=n.disableMutations?.create?void 0:async(A,C)=>{const T=C.id,F=typeof T=="string"&&T.length>0?T:crypto.randomUUID(),P={...C,id:F},M=await A.insert(t).values(P).execute(),$=Array.isArray(M)?M?.[0]:M;if($&&typeof $=="object"&&!("success"in $))return u($);const G=$&&typeof $=="object"&&"source"in $?$.source:null,fe=G?A.resolveRowIri(t,{...P,source:G}):A.resolveRowIri(t,P);return{...P,id:A.resolveRowId(t,{...P,"@id":fe}),"@id":fe,subject:fe,uri:fe,source:G??fe}},S=n.disableMutations?.update?void 0:async(A,C,T)=>{const F=await A.updateByIri(t,C,T);if(F)return u(F);const P=await m(A,C);if(!P)throw new Error(`Failed to load ${e} record after update`);return P},E=n.disableMutations?.remove?void 0:async(A,C)=>(await A.deleteByIri(t,C),{id:C}),w=typeof t.getResourcePath=="function"?t.getResourcePath():t.config?.base??"";return{namespace:e,resourcePath:w,searchableFields:i,defaultSort:s,cache:a,invalidations:h,list:g,detail:m,create:v,update:S,remove:E}}var _NAMESPACE$x="http://purl.org/dc/terms/";function _NS$x(n){return _NAMESPACE$x+n}var DCTERMS={modified:_NS$x("modified"),title:_NS$x("title"),issued:_NS$x("issued"),description:_NS$x("description"),relation:_NS$x("relation"),abstract:_NS$x("abstract"),conformsTo:_NS$x("conformsTo"),created:_NS$x("created"),creator:_NS$x("creator"),isReplacedBy:_NS$x("isReplacedBy"),source:_NS$x("source"),type:_NS$x("type")},_NAMESPACE$u="http://xmlns.com/foaf/0.1/";function _NS$u(n){return _NAMESPACE$u+n}var FOAF={PREFIX:"foaf",NAMESPACE:_NAMESPACE$u,PREFIX_AND_NAMESPACE:{foaf:"http://xmlns.com/foaf/0.1/"},NS:_NS$u,Agent:_NS$u("Agent"),Document:_NS$u("Document"),Organization:_NS$u("Organization"),Project:_NS$u("Project"),Person:_NS$u("Person"),Group:_NS$u("Group"),Image:_NS$u("Image"),LabelProperty:_NS$u("LabelProperty"),OnlineAccount:_NS$u("OnlineAccount"),OnlineChatAccount:_NS$u("OnlineChatAccount"),OnlineEcommerceAccount:_NS$u("OnlineEcommerceAccount"),OnlineGamingAccount:_NS$u("OnlineGamingAccount"),PersonalProfileDocument:_NS$u("PersonalProfileDocument"),account:_NS$u("account"),accountName:_NS$u("accountName"),accountServiceHomepage:_NS$u("accountServiceHomepage"),age:_NS$u("age"),aimChatID:_NS$u("aimChatID"),nick:_NS$u("nick"),based_near:_NS$u("based_near"),birthday:_NS$u("birthday"),currentProject:_NS$u("currentProject"),depiction:_NS$u("depiction"),depicts:_NS$u("depicts"),dnaChecksum:_NS$u("dnaChecksum"),familyName:_NS$u("familyName"),family_name:_NS$u("family_name"),firstName:_NS$u("firstName"),focus:_NS$u("focus"),fundedBy:_NS$u("fundedBy"),geekcode:_NS$u("geekcode"),gender:_NS$u("gender"),givenName:_NS$u("givenName"),givenname:_NS$u("givenname"),holdsAccount:_NS$u("holdsAccount"),homepage:_NS$u("homepage"),page:_NS$u("page"),isPrimaryTopicOf:_NS$u("isPrimaryTopicOf"),topic:_NS$u("topic"),primaryTopic:_NS$u("primaryTopic"),icqChatID:_NS$u("icqChatID"),img:_NS$u("img"),interest:_NS$u("interest"),jabberID:_NS$u("jabberID"),knows:_NS$u("knows"),lastName:_NS$u("lastName"),logo:_NS$u("logo"),made:_NS$u("made"),maker:_NS$u("maker"),mbox:_NS$u("mbox"),mbox_sha1sum:_NS$u("mbox_sha1sum"),member:_NS$u("member"),membershipClass:_NS$u("membershipClass"),msnChatID:_NS$u("msnChatID"),myersBriggs:_NS$u("myersBriggs"),name:_NS$u("name"),openid:_NS$u("openid"),pastProject:_NS$u("pastProject"),phone:_NS$u("phone"),plan:_NS$u("plan"),publications:_NS$u("publications"),schoolHomepage:_NS$u("schoolHomepage"),sha1:_NS$u("sha1"),skypeID:_NS$u("skypeID"),status:_NS$u("status"),surname:_NS$u("surname"),theme:_NS$u("theme"),thumbnail:_NS$u("thumbnail"),tipjar:_NS$u("tipjar"),title:_NS$u("title"),topic_interest:_NS$u("topic_interest"),weblog:_NS$u("weblog"),workInfoHomepage:_NS$u("workInfoHomepage"),workplaceHomepage:_NS$u("workplaceHomepage"),yahooChatID:_NS$u("yahooChatID")},_NAMESPACE$o="http://www.w3.org/ns/ldp#";function _NS$o(n){return _NAMESPACE$o+n}var LDP={inbox:_NS$o("inbox")},_NAMESPACE$h="http://www.w3.org/1999/02/22-rdf-syntax-ns#";function _NS$h(n){return _NAMESPACE$h+n}var RDF$2={type:_NS$h("type")},_NAMESPACE$3="http://www.w3.org/2006/vcard/ns#";function _NS$3(n){return _NAMESPACE$3+n}var VCARD={PREFIX:"vcard",NAMESPACE:_NAMESPACE$3,PREFIX_AND_NAMESPACE:{vcard:"http://www.w3.org/2006/vcard/ns#"},NS:_NS$3,Acquaintance:_NS$3("Acquaintance"),RelatedType:_NS$3("RelatedType"),Agent:_NS$3("Agent"),BBS:_NS$3("BBS"),TelephoneType:_NS$3("TelephoneType"),Car:_NS$3("Car"),Cell:_NS$3("Cell"),Child:_NS$3("Child"),Colleague:_NS$3("Colleague"),Contact:_NS$3("Contact"),Coresident:_NS$3("Coresident"),Coworker:_NS$3("Coworker"),Crush:_NS$3("Crush"),Date:_NS$3("Date"),Dom:_NS$3("Dom"),Type:_NS$3("Type"),Emergency:_NS$3("Emergency"),Fax:_NS$3("Fax"),Female:_NS$3("Female"),Gender:_NS$3("Gender"),Friend:_NS$3("Friend"),Home:_NS$3("Home"),ISDN:_NS$3("ISDN"),Internet:_NS$3("Internet"),Intl:_NS$3("Intl"),Kin:_NS$3("Kin"),Label:_NS$3("Label"),Male:_NS$3("Male"),Me:_NS$3("Me"),Met:_NS$3("Met"),Modem:_NS$3("Modem"),Msg:_NS$3("Msg"),Muse:_NS$3("Muse"),Neighbor:_NS$3("Neighbor"),None:_NS$3("None"),Other:_NS$3("Other"),PCS:_NS$3("PCS"),Pager:_NS$3("Pager"),Parcel:_NS$3("Parcel"),Parent:_NS$3("Parent"),Postal:_NS$3("Postal"),Pref:_NS$3("Pref"),Sibling:_NS$3("Sibling"),Spouse:_NS$3("Spouse"),Sweetheart:_NS$3("Sweetheart"),Tel:_NS$3("Tel"),Text:_NS$3("Text"),TextPhone:_NS$3("TextPhone"),Unknown:_NS$3("Unknown"),Video:_NS$3("Video"),Voice:_NS$3("Voice"),Work:_NS$3("Work"),X400:_NS$3("X400"),Address:_NS$3("Address"),Email:_NS$3("Email"),Group:_NS$3("Group"),Kind:_NS$3("Kind"),Individual:_NS$3("Individual"),Location:_NS$3("Location"),Organization:_NS$3("Organization"),VCard:_NS$3("VCard"),Name:_NS$3("Name"),adr:_NS$3("adr"),hasAddress:_NS$3("hasAddress"),agent:_NS$3("agent"),anniversary:_NS$3("anniversary"),bday:_NS$3("bday"),category:_NS$3("category"),class:_NS$3("class"),email:_NS$3("email"),hasEmail:_NS$3("hasEmail"),extended_address:_NS$3("extended-address"),geo:_NS$3("geo"),hasGeo:_NS$3("hasGeo"),hasAdditionalName:_NS$3("hasAdditionalName"),hasCalendarBusy:_NS$3("hasCalendarBusy"),hasCalendarLink:_NS$3("hasCalendarLink"),hasCalendarRequest:_NS$3("hasCalendarRequest"),hasCategory:_NS$3("hasCategory"),hasCountryName:_NS$3("hasCountryName"),hasFN:_NS$3("hasFN"),hasFamilyName:_NS$3("hasFamilyName"),hasGender:_NS$3("hasGender"),hasGivenName:_NS$3("hasGivenName"),hasHonorificPrefix:_NS$3("hasHonorificPrefix"),hasHonorificSuffix:_NS$3("hasHonorificSuffix"),hasInstantMessage:_NS$3("hasInstantMessage"),hasLanguage:_NS$3("hasLanguage"),hasLocality:_NS$3("hasLocality"),hasNickname:_NS$3("hasNickname"),nickname:_NS$3("nickname"),hasNote:_NS$3("hasNote"),hasOrganizationName:_NS$3("hasOrganizationName"),hasOrganizationUnit:_NS$3("hasOrganizationUnit"),hasPostalCode:_NS$3("hasPostalCode"),hasRegion:_NS$3("hasRegion"),hasRelated:_NS$3("hasRelated"),hasRole:_NS$3("hasRole"),hasSource:_NS$3("hasSource"),hasStreetAddress:_NS$3("hasStreetAddress"),hasTitle:_NS$3("hasTitle"),hasUID:_NS$3("hasUID"),hasValue:_NS$3("hasValue"),label:_NS$3("label"),language:_NS$3("language"),latitude:_NS$3("latitude"),longitude:_NS$3("longitude"),mailer:_NS$3("mailer"),note:_NS$3("note"),org:_NS$3("org"),organization_name:_NS$3("organization-name"),organization_unit:_NS$3("organization-unit"),post_office_box:_NS$3("post-office-box"),prodid:_NS$3("prodid"),rev:_NS$3("rev"),role:_NS$3("role"),sort_string:_NS$3("sort-string"),title:_NS$3("title"),tz:_NS$3("tz"),value:_NS$3("value"),country_name:_NS$3("country-name"),locality:_NS$3("locality"),postal_code:_NS$3("postal-code"),region:_NS$3("region"),street_address:_NS$3("street-address"),fn:_NS$3("fn"),hasMember:_NS$3("hasMember"),additional_name:_NS$3("additional-name"),family_name:_NS$3("family-name"),given_name:_NS$3("given-name"),honorific_prefix:_NS$3("honorific-prefix"),honorific_suffix:_NS$3("honorific-suffix"),hasKey:_NS$3("hasKey"),key:_NS$3("key"),hasLogo:_NS$3("hasLogo"),logo:_NS$3("logo"),hasName:_NS$3("hasName"),n:_NS$3("n"),hasPhoto:_NS$3("hasPhoto"),photo:_NS$3("photo"),hasSound:_NS$3("hasSound"),sound:_NS$3("sound"),hasTelephone:_NS$3("hasTelephone"),tel:_NS$3("tel"),hasURL:_NS$3("hasURL"),url:_NS$3("url")};const ABSOLUTE_IRI$1=/^[a-zA-Z][a-zA-Z\d+.-]*:/,createNamespace=(n,e,t)=>{const i=(s=>ABSOLUTE_IRI$1.test(s)?s:`${e}${s}`);return i.prefix=n,i.uri=e,i.NAMESPACE=e,i.term=s=>i(s),Object.entries(t).forEach(([s,a])=>{Object.defineProperty(i,s,{value:i(a),enumerable:!0})}),i},DCTerms=DCTERMS,RDF$1=RDF$2,ODRL=createNamespace("odrl","http://www.w3.org/ns/odrl/2/",{Policy:"Policy",target:"target",action:"action"});createNamespace("rdfs","http://www.w3.org/2000/01/rdf-schema#",{Class:"Class",label:"label",comment:"comment",subClassOf:"subClassOf",domain:"domain",range:"range"});createNamespace("owl","http://www.w3.org/2002/07/owl#",{Ontology:"Ontology",Class:"Class",ObjectProperty:"ObjectProperty",DatatypeProperty:"DatatypeProperty"});const SCHEMA=createNamespace("schema","http://schema.org/",{CreativeWork:"CreativeWork",MediaObject:"MediaObject",PropertyValue:"PropertyValue",about:"about",author:"author",dateCreated:"dateCreated",dateDeleted:"dateDeleted",description:"description",encodingFormat:"encodingFormat",fileSize:"fileSize",image:"image",name:"name",participant:"participant",reviewedBy:"reviewedBy",text:"text",url:"url"}),SIOC=createNamespace("sioc","http://rdfs.org/sioc/ns#",{Container:"Container",Post:"Post",Thread:"Thread",Forum:"Forum",content:"content",richContent:"richContent",hasReply:"has_reply",replyOf:"reply_of",hasCreator:"has_creator",createdAt:"created_at",hasContainer:"has_container",has_parent:"has_parent",numReplies:"num_replies",has_member:"has_member",about:"about"}),MEETING=createNamespace("mee","http://www.w3.org/ns/pim/meeting#",{LongChat:"LongChat",Message:"Message"}),WF=createNamespace("wf","http://www.w3.org/2005/01/wf/flow-1.0#",{message:"message",participation:"participation",participant:"participant"}),AS=createNamespace("as","https://www.w3.org/ns/activitystreams#",{Activity:"Activity",Announce:"Announce",Public:"Public",audience:"audience",actor:"actor",object:"object",target:"target"}),UDFS=createNamespace("udfs","https://undefineds.co/ns#",{ApprovalRequest:"ApprovalRequest",InputRequest:"InputRequest",CaptureCandidate:"CaptureCandidate",CaptureEvent:"CaptureEvent",AuditEntry:"AuditEntry",AutonomyGrant:"AutonomyGrant",Idea:"Idea",Issue:"Issue",Task:"Task",Schedule:"Schedule",AutomationRule:"AutomationRule",Delivery:"Delivery",Run:"Run",RunStep:"RunStep",Evidence:"Evidence",Report:"Report",Credential:"Credential",ApiKeyCredential:"ApiKeyCredential",OAuthCredential:"OAuthCredential",Provider:"Provider",Model:"Model",AIModel:"AIModel",ChatModel:"ChatModel",EmbeddingModel:"EmbeddingModel",DocumentUnderstandingModel:"DocumentUnderstandingModel",RerankingModel:"RerankingModel",ImageGenerationModel:"ImageGenerationModel",SpeechRecognitionModel:"SpeechRecognitionModel",SpeechSynthesisModel:"SpeechSynthesisModel",VideoGenerationModel:"VideoGenerationModel",ModelCapability:"ModelCapability",ChatCapability:"ChatCapability",EmbeddingCapability:"EmbeddingCapability",RerankingCapability:"RerankingCapability",ToolCallCapability:"ToolCallCapability",ReasoningCapability:"ReasoningCapability",WebCapability:"WebCapability",VisionCapability:"VisionCapability",OCRCapability:"OCRCapability",DocumentUnderstandingCapability:"DocumentUnderstandingCapability",StructuredOutputCapability:"StructuredOutputCapability",IndexingCapability:"IndexingCapability",ImageGenerationCapability:"ImageGenerationCapability",SpeechRecognitionCapability:"SpeechRecognitionCapability",SpeechSynthesisCapability:"SpeechSynthesisCapability",VideoGenerationCapability:"VideoGenerationCapability",AIConfig:"AIConfig",Note:"Note",VectorStore:"VectorStore",IndexedFile:"IndexedFile",AgentStatus:"AgentStatus",GatewayAccessKey:"GatewayAccessKey",QuotaSnapshot:"QuotaSnapshot",ChatProjectContext:"ChatProjectContext",ProjectMemory:"ProjectMemory",ConversationShare:"ConversationShare",Skill:"Skill",name:"name",favorite:"favorite",favoriteType:"favoriteType",favoriteTarget:"favoriteTarget",favoredAt:"favoredAt",conversation:"conversation",conversationType:"conversationType",conversationTitle:"conversationTitle",lastMessage:"lastMessage",lastActiveAt:"lastActiveAt",lastSyncedAt:"lastSyncedAt",sortKey:"sortKey",hasThread:"hasThread",inThread:"inThread",inScope:"inScope",participants:"participants",message:"message",messageContent:"messageContent",messageType:"messageType",messageStatus:"messageStatus",readBy:"readBy",Contact:"Contact",PersonContact:"PersonContact",AgentContact:"AgentContact",GroupContact:"GroupContact",hasContact:"hasContact",contactType:"contactType",externalPlatform:"externalPlatform",externalId:"externalId",alias:"alias",aiAssistant:"aiAssistant",aiModel:"aiModel",aiModels:"aiModels",aiProvider:"aiProvider",credential:"credential",systemPrompt:"systemPrompt",temperature:"temperature",maxTokens:"maxTokens",systemMessage:"systemMessage",provider:"provider",model:"model",displayName:"displayName",proxyUrl:"proxyUrl",hasModel:"hasModel",defaultModel:"defaultModel",modelType:"modelType",isProvidedBy:"isProvidedBy",inputModality:"inputModality",outputModality:"outputModality",capability:"capability",hasCapability:"hasCapability",contextLength:"contextLength",maxOutputTokens:"maxOutputTokens",pricingInput:"pricingInput",pricingOutput:"pricingOutput",apiKeyUrl:"apiKeyUrl",connectMode:"connectMode",homepage:"homepage",dimension:"dimension",supportsBackend:"supportsBackend",rotationPolicy:"rotationPolicy",metadata:"metadata",root:"root",webId:"webId",hasSkill:"hasSkill",skill:"skill",enabled:"enabled",memoryEnabled:"memoryEnabled",includeToolDetails:"includeToolDetails",excludedMessage:"excludedMessage",version:"version",checksum:"checksum",loadPolicy:"loadPolicy",credentialSource:"credentialSource",backend:"backend",runtime:"runtime",transport:"transport",endpoint:"endpoint",authorityPolicy:"authorityPolicy",toolPolicy:"toolPolicy",runtimeSnapshot:"runtimeSnapshot",tools:"tools",contextWindow:"contextWindow",contextRound:"contextRound",Agent:"Agent",agentCapability:"agentCapability",agentTool:"agentTool",agentConfig:"agentConfig",fileHash:"fileHash",syncStatus:"syncStatus",localPath:"localPath",isDefault:"isDefault",service:"service",label:"label",owner:"owner",secretHash:"secretHash",deployment:"deployment",balance:"balance",windows:"windows",observedAt:"observedAt",lastUsedAt:"lastUsedAt",failCount:"failCount",rateLimitResetAt:"rateLimitResetAt",authMode:"authMode",offeringId:"offeringId",storageMode:"storageMode",secretPayload:"secretPayload",encryptedSecret:"encryptedSecret",wrappedDataKey:"wrappedDataKey",encryptionAlgorithm:"encryptionAlgorithm",keyVersion:"keyVersion",scopes:"scopes",accountLabel:"accountLabel",lastRefreshAt:"lastRefreshAt",reauthRequired:"reauthRequired",oauthRefreshToken:"oauthRefreshToken",oauthAccessToken:"oauthAccessToken",oauthExpiresAt:"oauthExpiresAt",projectId:"projectId",organizationId:"organizationId",secretType:"secretType",settingKey:"settingKey",settingValue:"settingValue",settingType:"settingType",apiKey:"apiKey",baseUrl:"baseUrl",inbox:"inbox",issue:"issue",task:"task",schedule:"schedule",automationRule:"automationRule",delivery:"delivery",deliveryKind:"deliveryKind",scheduleKind:"scheduleKind",ruleKind:"ruleKind",instruction:"instruction",input:"input",inputRequest:"inputRequest",captureCandidate:"captureCandidate",captureEvent:"captureEvent",captureDecision:"captureDecision",targetResource:"targetResource",suggestedType:"suggestedType",suggestedTarget:"suggestedTarget",confidence:"confidence",userCorrection:"userCorrection",trigger:"trigger",condition:"condition",actions:"actions",objective:"objective",payload:"payload",projection:"projection",target:"target",targetThread:"targetThread",targetSession:"targetSession",projectedRole:"projectedRole",consumedAt:"consumedAt",priority:"priority",commitment:"commitment",affectedArea:"affectedArea",currentUnderstanding:"currentUnderstanding",openQuestions:"openQuestions",conflicts:"conflicts",nextStep:"nextStep",promotedTo:"promotedTo",sourceMessage:"sourceMessage",parentIssue:"parentIssue",session:"session",status:"status",risk:"risk",assignedTo:"assignedTo",reason:"reason",resolvedAt:"resolvedAt",closedAt:"closedAt",action:"action",actor:"actor",actorRole:"actorRole",entry:"entry",context:"context",policy:"policy",pageKind:"pageKind",summary:"summary",body:"body",tags:"tags",source:"source",sourceKind:"sourceKind",sourceKey:"sourceKey",sourceHash:"sourceHash",fingerprint:"fingerprint",compiledAt:"compiledAt",compiledFrom:"compiledFrom",related:"related",approval:"approval",approvalOptions:"approvalOptions",inputOptions:"inputOptions",requestKind:"requestKind",requester:"requester",response:"response",answeredBy:"answeredBy",effect:"effect",expiresAt:"expiresAt",riskCeiling:"riskCeiling",revokedAt:"revokedAt",disabledAt:"disabledAt",archivedAt:"archivedAt",deletedAt:"deletedAt",pinnedAt:"pinnedAt",pinned:"pinned",muted:"muted",mutedAt:"mutedAt",unreadCount:"unreadCount",ttsModel:"ttsModel",videoModel:"videoModel",chatType:"chatType",workspace:"workspace",container:"container",policyRef:"policyRef",policyVersion:"policyVersion",parentThread:"parentThread",sessionStatus:"sessionStatus",runner:"runner",prompt:"prompt",externalRunId:"externalRunId",clientCredentialId:"clientCredentialId",appliedTo:"appliedTo",appliedOn:"appliedOn",appliedAt:"appliedAt",leaseOwner:"leaseOwner",leaseExpiresAt:"leaseExpiresAt",heartbeatAt:"heartbeatAt",cancelRequestedAt:"cancelRequestedAt",startedAt:"startedAt",startsAt:"startsAt",createdAt:"createdAt",updatedAt:"updatedAt",completedAt:"completedAt",nextRunAt:"nextRunAt",lastRunAt:"lastRunAt",lastTriggeredAt:"lastTriggeredAt",lastRunStatus:"lastRunStatus",cron:"cron",intervalSeconds:"intervalSeconds",timezone:"timezone",error:"error",run:"run",stepType:"stepType",evidence:"evidence",evidenceKind:"evidenceKind",report:"report",reportKind:"reportKind",outcome:"outcome",metricFacts:"metricFacts",publishedAt:"publishedAt",reviewer:"reviewer",sessionTool:"sessionTool",tokenUsage:"tokenUsage",noteKind:"noteKind",representationMediaType:"representationMediaType",readerEngine:"readerEngine",readerVersion:"readerVersion",generatedWithModel:"generatedWithModel",readerOptionsHash:"readerOptionsHash",representationHash:"representationHash",coverageUnit:"coverageUnit",coveredRange:"coveredRange",readUnits:"readUnits",totalUnits:"totalUnits",failureCategory:"failureCategory",chatModel:"chatModel",ocrModel:"ocrModel",readerModel:"readerModel",embeddingModel:"embeddingModel",indexerModel:"indexerModel",rerankerModel:"rerankerModel",ocrEnabled:"ocrEnabled",automaticOcr:"automaticOcr",imageRecognition:"imageRecognition",pdfRecognition:"pdfRecognition",tableRecognition:"tableRecognition",processingMode:"processingMode",readerPolicy:"readerPolicy",readerPriority:"readerPriority",maxFileSizeMb:"maxFileSizeMb",maxPages:"maxPages",chunkingStrategy:"chunkingStrategy",fileUrl:"fileUrl",vectorId:"vectorId",usageBytes:"usageBytes",lastError:"lastError",indexedAt:"indexedAt",lastActivityAt:"lastActivityAt",errorMessage:"errorMessage",groupOwner:"groupOwner",groupAdmin:"groupAdmin",senderName:"senderName",senderAvatarUrl:"senderAvatarUrl",mentions:"mentions",replyTo:"replyTo",routedBy:"routedBy",routeTargetAgent:"routeTargetAgent",coordinationId:"coordinationId",agent:"agent",toolCallId:"toolCallId",toolName:"toolName",toolArguments:"toolArguments",toolStatus:"toolStatus",toolResult:"toolResult",toolError:"toolError",toolDuration:"toolDuration",toolRisk:"toolRisk",approvalStatus:"approvalStatus",decisionBy:"decisionBy",decisionRole:"decisionRole",onBehalfOf:"onBehalfOf",approvalReason:"approvalReason",inboxItemId:"inboxItemId",taskProgressId:"taskProgressId",taskSteps:"taskSteps",currentStep:"currentStep",totalSteps:"totalSteps",sourceModule:"sourceModule",searchText:"searchText",snapshotMeta:"snapshotMeta"});UDFS.NAMESPACE;SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt,UDFS.disabledAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;function extractProfileUsernameFromWebId(n){try{const t=new URL(n).pathname.split("/").filter(Boolean).map(a=>decodeURIComponent(a)),i=t.indexOf("profile");if(i>0)return t[i-1];const s=t.find(a=>a!=="profile"&&a!=="card");if(s)return s}catch{}return"there"}function createResourceRepositoryDescriptor(n){const{resource:e,filter:t,...i}=n;return createRepositoryDescriptor({...i,table:e,filter:t?({table:s,filters:a})=>t({resource:s,filters:a}):void 0})}const definePodRepository=createResourceRepositoryDescriptor,solidProfileResource=podTable("profile",{id:id("id"),name:string$2("name").predicate(VCARD.fn),nick:string$2("nick").predicate(FOAF.nick),avatar:string$2("avatar").predicate(VCARD.hasPhoto),note:string$2("note").predicate(VCARD.note),email:string$2("email").predicate(VCARD.hasEmail),phone:string$2("phone").predicate(VCARD.hasTelephone),region:string$2("region").predicate(VCARD.region),gender:string$2("gender").predicate(VCARD.hasGender),favorite:string$2("favorite").predicate(UDFS.favorite),inbox:string$2("inbox").predicate(LDP.inbox)},{base:"idp:///profile/card",type:FOAF.Person,namespace:UDFS});definePodRepository({namespace:"profile",resource:solidProfileResource,searchableFields:["name","nick"],disableMutations:{create:!0,update:!0,remove:!0}});function pickSolidProfileDisplayName(n){return normalizeDisplayName(n?.name)??normalizeDisplayName(n?.nick)??null}function normalizeDisplayName(n){if(typeof n!="string")return null;const e=n.trim();return e||null}const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/",namespaces={xsd:{decimal:`${XSD}decimal`,boolean:`${XSD}boolean`,double:`${XSD}double`,integer:`${XSD}integer`,string:`${XSD}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}},{xsd:xsd$1}=namespaces,escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,escapeReplacements={"\\":"\\","'":"'",'"':'"',n:`
|
|
304
304
|
`,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/,lineModeRegExps={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},invalidRegExp=/$0^/;class N3Lexer{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in lineModeRegExps)&&this[t]instanceof RegExp&&(this[t]=invalidRegExp)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let i=this._input,s=i.length;for(;;){let u,h;for(;u=this._newline.exec(i);)this.comments&&(h=this._comment.exec(u[0]))&&a("comment",h[1],"",this._line,u[0].length),i=i.substr(u[0].length,i.length),s=i.length,this._line++;if(!u&&(u=this._whitespace.exec(i))&&(i=i.substr(u[0].length,i.length)),this._endOfFile.test(i))return t&&(this.comments&&(h=this._comment.exec(i))&&a("comment",h[1],"",this._line,i.length),i=null,a("eof","","",this._line,0)),this._input=i;const d=this._line,p=i[0];let g="",m="",v="",S=null,E=0,w=!1;switch(p){case"^":if(i.length<3)break;if(i[1]==="^"){if(this._previousMarker="^^",i=i.substr(2),i[0]!=="<"){w=!0;break}}else{this._n3Mode&&(E=1,g="^");break}case"<":if(S=this._unescapedIri.exec(i))g="IRI",m=S[1];else if(S=this._iri.exec(i)){if(m=this._unescape(S[1]),m===null||illegalIriChars.test(m))return l(this);g="IRI"}else i.length>1&&i[1]==="<"?(g="<<",E=2):this._n3Mode&&i.length>1&&i[1]==="="&&(E=2,this._isImpliedBy?(g="abbreviation",m="<"):(g="inverse",m=">"));break;case">":i.length>1&&i[1]===">"&&(g=">>",E=2);break;case"_":((S=this._blank.exec(i))||t&&(S=this._blank.exec(`${i} `)))&&(g="blank",v="_",m=S[1]);break;case'"':if(S=this._simpleQuotedString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(S=this._simpleApostropheString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(S=this._variable.exec(i))&&(g="var",m=S[0]);break;case"@":this._previousMarker==="literal"&&(S=this._langcode.exec(i))?(g="langcode",m=S[1]):(S=this._keyword.exec(i))&&(g=S[0]);break;case".":if(i.length===1?t:i[1]<"0"||i[1]>"9"){g=".",E=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(S=this._number.exec(i)||t&&(S=this._number.exec(`${i} `)))&&(g="literal",m=S[0],v=typeof S[1]=="string"?xsd$1.double:typeof S[2]=="string"?xsd$1.decimal:xsd$1.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(S=this._sparqlKeyword.exec(i))?g=S[0].toUpperCase():w=!0;break;case"f":case"t":(S=this._boolean.exec(i))?(g="literal",m=S[0],v=xsd$1.boolean):w=!0;break;case"a":(S=this._shortPredicates.exec(i))?(g="abbreviation",m="a"):w=!0;break;case"=":this._n3Mode&&i.length>1&&(g="abbreviation",i[1]!==">"?(E=1,m="="):(E=2,m=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(E=1,g=p);break;case"{":!this._lineMode&&i.length>=2&&(i[1]==="|"?(g="{|",E=2):(g=p,E=1));break;case"|":i.length>=2&&i[1]==="}"&&(g="|}",E=2);break;default:w=!0}if(w&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(S=this._prefix.exec(i))?(g="prefix",m=S[1]||""):((S=this._prefixed.exec(i))||t&&(S=this._prefixed.exec(`${i} `)))&&(g="prefixed",v=S[1]||"",m=this._unescape(S[2]))),this._previousMarker==="^^")switch(g){case"prefixed":g="type";break;case"IRI":g="typeIRI";break;default:g=""}if(!g)return t||!/^'''|^"""/.test(i)&&/\n|\r/.test(i)?l(this):this._input=i;const A=E||S[0].length,C=a(g,m,v,d,A);this.previousToken=C,this._previousMarker=g,i=i.substr(A,i.length)}function a(u,h,d,p,g){const m=i?s-i.length:s,v=m+g,S={type:u,value:h,prefix:d,line:p,start:m,end:v};return e(null,S),S}function l(u){e(u._syntaxError(/^\S*/.exec(i)[0]))}}_unescape(e){let t=!1;const i=e.replace(escapeSequence,(s,a,l,u)=>{if(typeof a=="string")return String.fromCharCode(Number.parseInt(a,16));if(typeof l=="string"){let h=Number.parseInt(l,16);return h<=65535?String.fromCharCode(Number.parseInt(l,16)):String.fromCharCode(55296+((h-=65536)>>10),56320+(h&1023))}return u in escapeReplacements?escapeReplacements[u]:(t=!0,"")});return t?null:i}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],i=t.length;let s=Math.max(this._literalClosingPos,i);for(;(s=e.indexOf(t,s))>0;){let a=0;for(;e[s-a-1]==="\\";)a++;if(a%2===0){const l=e.substring(i,s),u=l.split(/\r\n|\r|\n/).length-1,h=s+i;if(i===1&&u!==0||i===3&&this._lineMode)break;return this._line+=u,{value:this._unescape(l),matchLength:h}}s++}this._literalClosingPos=e.length-i+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const i=[];let s;if(this._tokenizeToEnd((a,l)=>a?s=a:i.push(l),!0),s)throw s;return i}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",i=>{this._input!==null&&i.length!==0&&(this._pendingBuffer&&(i=bufferExports.Buffer.concat([this._pendingBuffer,i]),this._pendingBuffer=null),i[i.length-1]&128?this._pendingBuffer=i:(typeof this._input>"u"?this._input=this._readStartingBom(typeof i=="string"?i:i.toString()):this._input+=i,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf,xsd}=namespaces;let DEFAULTGRAPH,_blankNodeCounter=0;const DataFactory={namedNode,blankNode,variable,literal,defaultGraph,quad,triple:quad,fromTerm,fromQuad};class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class NamedNode extends Term{get termType(){return"NamedNode"}}class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&e[t++]==="@"?e.substr(t).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,i=t<e.length?e[t]:"";return i==="^"?e.substr(t+2):i!=="@"?xsd.string:rdf.langString}equals(e){return e instanceof Literal?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class BlankNode extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Variable extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}class DefaultGraph extends Term{constructor(){return super(""),DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}DEFAULTGRAPH=new DefaultGraph;class Quad extends Term{constructor(e,t,i,s){super(""),this._subject=e,this._predicate=t,this._object=i,this._graph=s||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function namedNode(n){return new NamedNode(n)}function blankNode(n){return new BlankNode(n||`n3-${_blankNodeCounter++}`)}function literal(n,e){if(typeof e=="string")return new Literal(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=xsd.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd.integer:xsd.double:(t=xsd.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd.string?new Literal(`"${n}"`):new Literal(`"${n}"^^${t}`)}function variable(n){return new Variable(n)}function defaultGraph(){return DEFAULTGRAPH}function quad(n,e,t,i){return new Quad(n,e,t,i)}function fromTerm(n){if(n instanceof Term)return n;switch(n.termType){case"NamedNode":return namedNode(n.value);case"BlankNode":return blankNode(n.value);case"Variable":return variable(n.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(n.value,n.language||n.datatype);case"Quad":return fromQuad(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function fromQuad(n){if(n instanceof Quad)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return quad(fromTerm(n.subject),fromTerm(n.predicate),fromTerm(n.object),fromTerm(n.graph))}let blankNodePrefix=0;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&initDataFactory(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",i=/turtle/.test(t),s=/trig/.test(t),a=/triple/.test(t),l=/quad/.test(t),u=this._n3Mode=/n3/.test(t),h=a||l;(this._supportsNamedGraphs=!(i||u))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(i||s||a||u),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),h&&(this._resolveRelativeIRI=d=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer({lineMode:h,n3:u,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,i,s,a){const l=this._n3Mode;this._contextStack.push({type:e,subject:i,predicate:s,object:a,graph:t,inverse:l?this._inversePredicate:!1,blankPrefix:l?this._prefixes._:"",quantified:l?this._quantified:null}),l&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const i=this._contextStack.pop();if(!i||i.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=i.subject,this._predicate=i.predicate,this._object=i.object,this._graph=i.graph,this._n3Mode&&(this._inversePredicate=i.inverse,this._prefixes._=i.blankPrefix,this._quantified=i.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let i;switch(e.type){case"IRI":case"typeIRI":const s=this._resolveIRI(e.value);if(s===null)return this._error("Invalid IRI",e);i=this._factory.namedNode(s);break;case"type":case"prefixed":const a=this._prefixes[e.prefix];if(a===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);i=this._factory.namedNode(a+e.value);break;case"blank":i=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":i=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&i.id in this._quantified&&(i=this._quantified[i.id]),i}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,i=null,s=this._readListItem;const a=this._subject,l=this._contextStack,u=l[l.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),s=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),l.length!==0&&l[l.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(s=this._readPredicate,this._subject===this.RDF_NIL)return s}else if(s=this._getContextEndReader(),this._object===this.RDF_NIL)return s;i=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,s=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),s=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(i===null&&(this._subject=i=this._factory.blankNode()),a===null?u.predicate===null?u.subject=i:u.object=i:this._emit(a,this.RDF_REST,i,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,i,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(i,this.RDF_FIRST,t,this._graph)}return s}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const i=this._readEntity(e);if(i===void 0)return;t=this._factory.literal(this._literalValue,i),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const i=this._completeLiteral(e);if(i)return this._object=i.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),i.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(i.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,i=this._graph;const s=this._subject,a=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,a&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const l=this._predicate,u=this._object;this._subject=this._factory.quad(s,l,u,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(i=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(s!==null){const l=this._predicate,u=this._object;a?this._emit(u,l,s,i):this._emit(s,l,u,i)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,i=t.length&&t[t.length-1];if(i&&i.type==="item"){const s=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,s,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,i;const s=this._factory.blankNode();if((i=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=s):(t=this._object,this._object=s),this._emit(t,i,s,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let i,s;if((i=this._readEntity(e))!==void 0)return this._predicate===null?(s=this._subject,this._subject=t):(s=this._object,this._object=t),this._emit(t,i,s,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,i,s){this._callback(null,this._factory.quad(e,t,i,s||this.DEFAULTGRAPH))}_error(e,t){const i=new Error(`${e} on line ${t.line}.`);i.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(i),this._callback=noop}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let i="",s=-1,a=-1,l=0,u="/";for(;s<t;){switch(u){case":":if(a<0&&e[++s]==="/"&&e[++s]==="/")for(;(a=s+1)<t&&e[a]!=="/";)s=a;break;case"?":case"#":s=t;break;case"/":if(e[s+1]===".")switch(u=e[++s+1],u){case"/":i+=e.substring(l,s-1),l=s+1;break;case void 0:case"?":case"#":return i+e.substring(l,s)+e.substr(s+1);case".":if(u=e[++s+1],u===void 0||u==="/"||u==="?"||u==="#"){if(i+=e.substring(l,s-2),(l=i.lastIndexOf("/"))>=a&&(i=i.substr(0,l)),u!=="/")return`${i}/${e.substr(s+1)}`;l=s+1}}}u=e[++s]}return i+e.substring(l)}parse(e,t,i){let s,a,l;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(s=t.onQuad,a=t.onPrefix,l=t.onComment):(s=t,a=i),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`,this._prefixCallback=a||noop,this._inversePredicate=!1,this._quantified=Object.create(null),!s){const h=[];let d;if(this._callback=(p,g)=>{p?d=p:g&&h.push(g)},this._lexer.tokenize(e).every(p=>this._readCallback=this._readCallback(p)),d)throw d;return h}let u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(this._readCallback=this._readCallback(d))};l&&(this._lexer.comments=!0,u=(h,d)=>{h!==null?(this._callback(h),this._callback=noop):this._readCallback&&(d.type==="comment"?l(d.value):this._readCallback=this._readCallback(d))}),this._callback=s,this._lexer.tokenize(e,u)}}function noop(){}function initDataFactory(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces.rdf.first),n.RDF_REST=e.namedNode(namespaces.rdf.rest),n.RDF_NIL=e.namedNode(namespaces.rdf.nil),n.N3_FORALL=e.namedNode(namespaces.r.forAll),n.N3_FORSOME=e.namedNode(namespaces.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces.rdf.type),"=":e.namedNode(namespaces.owl.sameAs),">":e.namedNode(namespaces.log.implies),"<":e.namedNode(namespaces.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,DataFactory);async function resolveSolidProfileIdentityFromWebIdDocument(n,e={}){const t=e.webId??n.info?.webId;if(!t?.trim()||typeof n.fetch!="function")return null;const i=stripHash(t),s=await n.fetch(i,{headers:{Accept:"text/turtle, application/ld+json;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!s.ok)throw new Error(`Failed to fetch WebID profile: ${s.status} ${s.statusText}`.trim());const a=s.headers.get("content-type")??"",l=await s.text();if(!l.trim())return buildSolidProfileIdentity(t,null);const u=await parseSolidProfileDocument(l,{contentType:a,profileDocumentUrl:i,webId:t});return buildSolidProfileIdentity(t,u)}async function parseSolidProfileDocument(n,e){return(e.contentType?.toLowerCase()??"").includes("application/ld+json")||n.trimStart().startsWith("{")?parseJsonLdProfileDocument(n,e.webId):await parseTurtleProfileDocument(n,e)}async function parseTurtleProfileDocument(n,e){const t=N3Parser,s=new t({baseIRI:e.profileDocumentUrl}).parse(n);return pickProfileFromQuads(s,e.webId)}function parseJsonLdProfileDocument(n,e){try{const t=JSON.parse(n),i=Array.isArray(t)?t:isRecord$2(t)&&Array.isArray(t["@graph"])?t["@graph"]:[t],s=i.find(l=>isRecord$2(l)&&l["@id"]===e),a=isRecord$2(s)?s:i.find(isRecord$2);return a?normalizeProfileRow({id:e,name:pickJsonLdString(a,VCARD.fn),nick:pickJsonLdString(a,FOAF.nick),avatar:pickJsonLdString(a,VCARD.hasPhoto),note:pickJsonLdString(a,VCARD.note),email:pickJsonLdString(a,VCARD.hasEmail),phone:pickJsonLdString(a,VCARD.hasTelephone),region:pickJsonLdString(a,VCARD.region),gender:pickJsonLdString(a,VCARD.hasGender)}):null}catch{return null}}function pickProfileFromQuads(n,e){const t={id:e};for(const i of n){if(i.subject.value!==e)continue;const s=i.predicate.value,a=i.object.value;!s||!a||(s===VCARD.fn?t.name=a:s===FOAF.nick?t.nick=a:s===VCARD.hasPhoto?t.avatar=a:s===VCARD.note?t.note=a:s===VCARD.hasEmail?t.email=a:s===VCARD.hasTelephone?t.phone=a:s===VCARD.region?t.region=a:s===VCARD.hasGender&&(t.gender=a))}return normalizeProfileRow(t)}function buildSolidProfileIdentity(n,e){return{webId:n,profile:e,displayName:pickSolidProfileDisplayName(e),username:extractProfileUsernameFromWebId(n)}}function normalizeProfileRow(n){const e=Object.fromEntries(Object.entries(n).filter(([,t])=>typeof t=="string"&&t.trim()));return Object.keys(e).length>1?e:null}function pickJsonLdString(n,e){return normalizeJsonLdValue(n[e])}function normalizeJsonLdValue(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(normalizeJsonLdValue).find(Boolean);if(isRecord$2(n))return normalizeJsonLdValue(n["@value"]??n["@id"])}function stripHash(n){const e=n.indexOf("#");return e>=0?n.slice(0,e):n}function isRecord$2(n){return typeof n=="object"&&n!==null}const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),offeringId:string$2("offeringId").predicate(UDFS.offeringId),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId),metadata:json("metadata").predicate(UDFS.metadata)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:a}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=a.getTitle(t),h={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:a.getContent?.(t),snapshotAuthor:a.getAuthor?.(t),sourceModule:s,searchText:a.getSearchText?.(t)??u,snapshotMeta:a.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,a=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,a)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const a={};for(const l of s)a[l]=l;return a},n.getValidEnumValues=s=>{const a=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of a)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(a){return s[a]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&a.push(l);return a},n.find=(s,a)=>{for(const l of s)if(a(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,a=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(a)}n.joinValues=i,n.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},i={_errors:[]},s=a=>{for(const l of a.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,h=0;for(;h<l.path.length;){const d=l.path[h];h===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],h++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,a=[...t,...s.path||[]],l={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let u="";const h=i.filter(d=>!!d).slice().reverse();for(const d of h)u=d(l,{data:e,defaultError:u}).message;return{...s,path:a,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const a=await s.key,l=await s.value;i.push({key:a,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:a,value:l}=s;if(a.status==="aborted"||l.status==="aborted")return INVALID;a.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[a.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:h}=n;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:h??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:h??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),a=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,a)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{const l=e(s),u=()=>a.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(h=>h?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:a.parsedType}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="length"){const l=e.data.length>a.value,u=e.data.length<a.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),i.dirty())}else if(a.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),i.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:a.value},message:a.message}),i.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:a.value},message:a.message}),i.dirty()):a.kind==="datetime"?datetimeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:a.message}),i.dirty()):a.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:a.message}),i.dirty()):a.kind==="time"?timeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:a.message}),i.dirty()):a.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="ip"?isValidIP(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="jwt"?isValidJWT(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="cidr"?isValidCidr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):util.assertNever(a);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,a=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return a%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:a.parsedType}),INVALID}let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?floatSafeRemainder(e.data,a.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:a.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),i.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),i.dirty()):util.assertNever(a);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const a=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,a)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:a,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const h=[];for(const d of l){const p=a[d],g=s.data[d];h.push({key:{status:"valid",value:d},value:p._parse(new ParseInputLazyPath(s,g,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of u)h.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")u.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:u}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of u){const g=s.data[p];h.push({key:{status:"valid",value:p},value:d._parse(new ParseInputLazyPath(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of h){const g=await p.key,m=await p.value;d.push({key:g,value:m,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let a=this.shape[i];for(;a instanceof ZodOptional;)a=a._def.innerType;t[i]=a}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(a){for(const u of a)if(u.result.status==="valid")return u.result;for(const u of a)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=a.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async a=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let a;const l=[];for(const h of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=h._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const u=l.map(h=>new ZodError(h));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),a=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of a){const h=mergeValues(n[u],e[u]);if(!h.valid)return{valid:!1};l[u]=h.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<n.length;a++){const l=n[a],u=e[a],h=mergeValues(l,u);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(a,l)=>{if(isAborted(a)||isAborted(l))return INVALID;const u=mergeValues(a.value,l.value);return u.valid?((isDirty(a)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([a,l])=>s(a,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...i.data].map((l,u)=>{const h=this._def.items[u]||this._def.rest;return h?h._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(a).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],a=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:a._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,a=this._def.valueType,l=[...i.data.entries()].map(([u,h],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:a._parse(new ParseInputLazyPath(i,h,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const h of l){const d=await h.key,p=await h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}})}else{const u=new Map;for(const h of l){const d=h.key,p=h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function l(h){const d=new Set;for(const p of h){if(p.status==="aborted")return INVALID;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const u=[...i.data.values()].map((h,d)=>a._parse(new ParseInputLazyPath(i,h,i.path,d)));return i.common.async?Promise.all(u).then(h=>l(h)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const l=s.transform(i.data,a);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const h=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return h.status==="aborted"?INVALID:h.status==="dirty"||t.value==="dirty"?DIRTY(h.value):h});{if(t.value==="aborted")return INVALID;const u=this._def.schema._parseSync({data:l,path:i.path,parent:i});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u}}if(s.type==="refinement"){const l=u=>{const h=s.refinement(u,a);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,a);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,a)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?INVALID:a.status==="dirty"?(t.dirty(),DIRTY(a.value)):this._def.out._parseAsync({data:a.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function buildAIConfigModelStorageId(n,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(n)})}function aiConfigProviderRef(n){const e=normalizeAIConfigProviderId(n);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`settings/providers/${buildAIConfigModelStorageId(t,i)}`:i}function definePodModelDescriptor(n){return n}const credentialDescriptor={uri:UDFS.Credential,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Credential,resourceKind:"credential",description:"Generic credential material required by runtimes, tools, MCP servers, and providers.",storage:{base:"/settings/credentials.ttl",resourceIdPattern:"#{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative credential row id. Every credential in a provider pool keeps its own id."},provider:{type:"uri",predicate:UDFS.provider,references:{resource:"provider",key:"id"},description:"Provider resource URI this credential connects through, as a URI relation to the provider row."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},offeringId:{type:"string",predicate:UDFS.offeringId,description:"Offering id this credential connects through. Offerings are catalog content, so this stays a plain attribute, not a relation."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},storageMode:{type:"string",predicate:UDFS.storageMode,description:"Credential storage format, for example plaintext-v1 or secret-cell-v1."},secretPayload:{type:"string",predicate:UDFS.secretPayload,secret:!0,description:"Storage-mode-specific credential payload. plaintext-v1 stores a JSON payload here."},encryptedSecret:{type:"string",predicate:UDFS.encryptedSecret,secret:!0,description:"Encrypted credential payload stored in the Pod."},wrappedDataKey:{type:"string",predicate:UDFS.wrappedDataKey,secret:!0,description:"Wrapped data-encryption key for encrypted credential payloads."},encryptionAlgorithm:{type:"string",predicate:UDFS.encryptionAlgorithm,description:"Credential encryption algorithm identifier."},keyVersion:{type:"string",predicate:UDFS.keyVersion,description:"Key-management version used to encrypt the credential."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Credential scopes granted by the provider."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Credential expiry timestamp."},accountLabel:{type:"string",predicate:UDFS.accountLabel,description:"Provider account label associated with the credential."},lastRefreshAt:{type:"timestamp",predicate:UDFS.lastRefreshAt,description:"Last successful credential refresh timestamp."},reauthRequired:{type:"boolean",predicate:UDFS.reauthRequired,description:"Whether this credential requires user reauthentication."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL recorded on the credential."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for requests made with this credential."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},isDefault:{type:"boolean",predicate:UDFS.isDefault,description:"Whether this credential is the default credential for its provider."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp, set by the store."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful use timestamp."},clientCredentialId:{type:"string",predicate:UDFS.clientCredentialId,description:"Client the issued credential belongs to. An external runtime identifier, not an RDF link."},appliedTo:{type:"string",predicate:UDFS.appliedTo,description:"Client application id the credential is in effect for. A runtime identifier, not an RDF link."},appliedOn:{type:"string",predicate:UDFS.appliedOn,description:"Device id that wrote the applied configuration. A runtime identifier, not an RDF link."},appliedAt:{type:"timestamp",predicate:UDFS.appliedAt,description:"Timestamp when the credential was applied."},failCount:{type:"number",predicate:UDFS.failCount,description:"Failed use count recorded for the credential."},rateLimitResetAt:{type:"timestamp",predicate:UDFS.rateLimitResetAt,description:"Timestamp when the provider rate limit is expected to reset."},oauthRefreshToken:{type:"string",predicate:UDFS.oauthRefreshToken,secret:!0,description:"OAuth refresh token."},oauthAccessToken:{type:"string",predicate:UDFS.oauthAccessToken,secret:!0,description:"OAuth access token."},oauthExpiresAt:{type:"timestamp",predicate:UDFS.oauthExpiresAt,description:"OAuth access token expiry timestamp."},projectId:{type:"string",predicate:UDFS.projectId,description:"Provider project identifier recorded for the credential."},organizationId:{type:"string",predicate:UDFS.organizationId,description:"Provider organization identifier recorded for the credential."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata bag; shared relations must be explicit fields."}},uniqueBy:["id"],writableFields:["provider","authMode","offeringId","service","status","apiKey","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","baseUrl","proxyUrl","label","isDefault","lastUsedAt","clientCredentialId","appliedTo","appliedOn","appliedAt","failCount","rateLimitResetAt","oauthRefreshToken","oauthAccessToken","oauthExpiresAt","projectId","organizationId","metadata"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{id:"cloudflare-5f2c9a1e"}},{request:"保存 OpenAI API key",match:{id:"openai-2b7d4e10"}}]},gatewayAccessKeyDescriptor={uri:UDFS.GatewayAccessKey,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.GatewayAccessKey,resourceKind:"gateway-access-key",description:"Control-primary Pod AI Gateway access key. The key owner is a semantic WebID/URI relation, while the secret itself is represented only by a hash.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/access-keys.ttl#key_1."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID or principal URI that owns this Gateway access key."},secretHash:{type:"string",predicate:UDFS.secretHash,required:!0,secret:!0,description:"Hash of the Gateway secret. Raw access key material must not be stored here."},name:{type:"string",predicate:UDFS.name,description:"User-visible label for distinguishing this Gateway access key."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment target: local or cloud."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Gateway scopes granted to this key."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Key expiry timestamp."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful Gateway use timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."}},uniqueBy:["id"],writableFields:["owner","secretHash","name","deployment","scopes","createdAt","expiresAt","lastUsedAt","revokedAt","disabledAt"],mergePolicy:"upsert",examples:[{request:"Create a local Gateway access key for a user",match:{id:"ai/gateway/access-keys.ttl#key_1"}}]},quotaSnapshotDescriptor={uri:UDFS.QuotaSnapshot,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.QuotaSnapshot,resourceKind:"quota-snapshot",description:"Observed Pod AI Gateway quota state for a provider credential. The credential field is a semantic URI relation, and normalized windows are stored as a serialized literal.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/quota.ttl#quota_1."},credential:{type:"uri",predicate:UDFS.credential,references:{resource:"credential",key:"id"},required:!0,description:"Credential resource URI this quota snapshot describes."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID that owns the credential and quota snapshot."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment scope: local or cloud."},provider:{type:"string",predicate:UDFS.provider,required:!0,description:"Normalized provider id for the quota snapshot."},status:{type:"string",predicate:UDFS.status,required:!0,description:"Quota availability status: available, unsupported, or error."},balance:{type:"number",predicate:UDFS.balance,description:"Normalized remaining quota balance when the provider exposes one."},windows:{type:"text",predicate:UDFS.windows,description:"Serialized normalized quota windows literal, for example JSON produced by Gateway normalization."},observedAt:{type:"timestamp",predicate:UDFS.observedAt,description:"Observation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Snapshot freshness expiry timestamp."},source:{type:"string",predicate:UDFS.source,description:"Observation source such as provider, gateway-cache, or manual."}},uniqueBy:["id"],writableFields:["credential","status","balance","windows","observedAt","expiresAt","source"],mergePolicy:"upsert",examples:[{request:"Record a fresh quota snapshot for a provider credential",match:{id:"ai/gateway/quota.ttl#quota_1"}}]},aiProviderDescriptor={uri:UDFS.Provider,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Provider,resourceKind:"provider",description:"AI provider endpoint configured in the Pod: endpoint, proxy, console entry, backend support, and the models it exposes. Its model rows live in the same provider document and are linked from here through hasModel.",storage:{base:"/settings/providers/",resourceIdPattern:"{key}.ttl"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative provider row id, for example openai.ttl."},displayName:{type:"string",predicate:UDFS.displayName,description:"Provider display name stored on the provider row."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for provider requests."},homepage:{type:"string",predicate:UDFS.homepage,description:"Provider homepage URL."},apiKeyUrl:{type:"string",predicate:UDFS.apiKeyUrl,description:"URL where a user creates an API key for this provider."},connectMode:{type:"string",predicate:UDFS.connectMode,description:"Connection mode recorded for the provider authorization method."},hasModel:{type:"uri",predicate:UDFS.hasModel,references:{resource:"ai-model",key:"id"},array:!0,description:"Model rows this provider exposes, as subjects inside the provider document."},defaultModel:{type:"uri",predicate:UDFS.defaultModel,references:{resource:"ai-model",key:"id"},description:"Default model for this provider when a request does not select one."},supportsBackend:{type:"string",predicate:UDFS.supportsBackend,description:"Backends this provider can serve, read as a backend list by the AI config selector."},capabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Provider capability tags."},rotationPolicy:{type:"string",predicate:UDFS.rotationPolicy,description:"Credential rotation policy recorded for the provider."}},uniqueBy:["id"],writableFields:["displayName","baseUrl","proxyUrl","homepage","apiKeyUrl","connectMode","hasModel","defaultModel","supportsBackend","capabilities","rotationPolicy"],mergePolicy:"upsert",examples:[{request:"Describe the provider document a Pod AI connection writes",match:{id:"openai.ttl"}}]},aiModelDescriptor={uri:UDFS.AIModel,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AIModel,resourceKind:"ai-model",description:"AI model exposed by a provider, stored as a subject inside that provider document. The provider relation and model capabilities are URI facts, while pricing and modality facts stay literals.",storage:{base:"/settings/providers/",resourceIdPattern:"{isProvidedBy.doc}#{key}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative model row id: provider document plus model key, for example openai.ttl#gpt-4o."},rdfType:{type:"uri",predicate:RDF$1.type,array:!0,description:"RDF class of the model row. The base table defaults to AIModel, and subclass tables narrow it."},displayName:{type:"string",predicate:UDFS.displayName,description:"Model display name stored on the model row."},isProvidedBy:{type:"uri",predicate:UDFS.isProvidedBy,references:{resource:"provider",key:"id"},description:"Provider document this model row belongs to, as a URI relation to the provider row."},inputModalities:{type:"text",predicate:UDFS.inputModality,array:!0,description:"Input modalities the model accepts."},outputModalities:{type:"text",predicate:UDFS.outputModality,array:!0,description:"Output modalities the model produces."},runtimeCapabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Adapter/runtime endpoint capabilities, kept separate from semantic model capabilities."},capabilities:{type:"uri",predicate:UDFS.hasCapability,array:!0,description:"Semantic capabilities of the model, as URIs."},pricingInput:{type:"number",predicate:UDFS.pricingInput,description:"Input token price recorded for the model."},pricingOutput:{type:"number",predicate:UDFS.pricingOutput,description:"Output token price recorded for the model."},status:{type:"string",predicate:UDFS.status,description:"Model availability status."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp, set by the store."},updatedAt:{type:"timestamp",predicate:UDFS.updatedAt,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["displayName","isProvidedBy","inputModalities","outputModalities","runtimeCapabilities","capabilities","pricingInput","pricingOutput","status","updatedAt"],mergePolicy:"upsert",examples:[{request:"Describe a model row inside a provider document",match:{id:"openai.ttl#gpt-4o"}}]},approvalDescriptor={uri:UDFS.ApprovalRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ApprovalRequest,resourceKind:"approval",description:"Durable approval request control item. Solid inbox notifications may point at this resource, but lifecycle and claim state live here.",storage:{base:"/.data/approvals/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Approval request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource that requested approval."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},toolCallId:{type:"string",predicate:UDFS.toolCallId,required:!0,description:"Opaque runtime tool-call identifier; not an RDF resource link."},toolName:{type:"string",predicate:UDFS.toolName,required:!0,description:"Runtime tool name that requires approval."},target:{type:"uri",predicate:ODRL.target,required:!0,description:"Target resource for the requested action. Schema field uses ODRL target in the executable resource."},action:{type:"uri",predicate:ODRL.action,required:!0,description:"Requested action URI. Schema field uses ODRL action in the executable resource."},risk:{type:"string",predicate:UDFS.risk,required:!0,description:"Risk level assigned by the runtime or policy layer."},status:{type:"string",predicate:UDFS.status,description:"Approval lifecycle status such as pending, handling, approved, rejected, resolved, or expired."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/approval handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to decide the request."},decisionBy:{type:"uri",predicate:UDFS.decisionBy,description:"WebID or agent resource that made the decision."},decisionRole:{type:"string",predicate:UDFS.decisionRole,description:"Role of the decision maker, for example human or secretary."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the decision applies."},reason:{type:"text",predicate:UDFS.reason,description:"Decision reason or policy explanation."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},approvalOptions:{type:"text",predicate:UDFS.approvalOptions,description:"Serialized approval options offered by the runtime."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version used to create or resolve this approval."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Decision timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","toolCallId","toolName","target","action","risk","status","leaseOwner","leaseExpiresAt","assignedTo","decisionBy","decisionRole","onBehalfOf","reason","context","approvalOptions","policyVersion","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending approval from Inbox subscription",match:{id:"2026/06/12.ttl#approval_1"}}]},inputRequestDescriptor={uri:UDFS.InputRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.InputRequest,resourceKind:"input-request",description:"Durable input request control item. It asks for missing information or a choice; approval/authority decisions remain ApprovalRequest.",storage:{base:"/.data/input-requests/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Input request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource waiting for input."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(n="/.data/"){return{base:n,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that created the candidate."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["source","summary","suggestedType","suggestedTarget","confidence","reason","status","sourceHash","chat","thread","task","run","actor","metadata","updatedAt"],mergePolicy:"upsert",examples:[{request:"Create a capture candidate from an observed chat message",match:{id:"candidates/2026/06/16.ttl#candidate_1"}}]},captureEventDescriptor={uri:UDFS.CaptureEvent,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureEvent,resourceKind:"capture-event",description:"Append-only capture decision ledger. It records direct commits, optimistic commits, candidate creation, promotion, rejection, correction, rollback, duplicate detection, and ignored decisions.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource considered by capture."},captureCandidate:{type:"uri",predicate:UDFS.captureCandidate,references:{resource:"capture-candidate",key:"id"},description:"Candidate resource involved in this event, when applicable."},targetResource:{type:"uri",predicate:UDFS.targetResource,description:"Formal resource affected by this capture decision."},decision:{type:"string",predicate:UDFS.captureDecision,required:!0,description:"Decision such as direct_commit, optimistic_commit, candidate_created, promoted, rejected, corrected, rollback, duplicate, or ignored."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Type suggested at decision time."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Target suggested at decision time."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence at decision time."},reason:{type:"text",predicate:UDFS.reason,description:"Explanation for the capture decision."},userCorrection:{type:"text",predicate:UDFS.userCorrection,description:"User correction to type, target, title, summary, or content."},approval:{type:"uri",predicate:UDFS.approval,references:{resource:"approval",key:"id"},description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,references:{resource:"input-request",key:"id"},description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$1.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,references:{resource:"contact",key:"id"},description:"Optional counterpart/contact represented by this channel."},participants:{type:"uri",predicate:WF.participant,array:!0,description:"Participant resource URIs."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},lastActiveAt:{type:"timestamp",predicate:UDFS.lastActiveAt,description:"Last activity timestamp."},lastMessage:{type:"uri",predicate:UDFS.lastMessage,description:"Latest message pointer."},lastMessagePreview:{type:"text",predicate:SCHEMA.text,description:"Latest message preview."}},uniqueBy:["id"],writableFields:["title","description","avatarUrl","author","status","starred","muted","unreadCount","contact","participants","metadata","lastActiveAt","lastMessage","lastMessagePreview"],mergePolicy:"upsert",examples:[{request:"Create a team chat surface",match:{id:"team/index.ttl#this"}}]},threadDescriptor={uri:SIOC.Thread,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:SIOC.Thread,resourceKind:"thread",description:"Concrete timeline/place under one parent command surface. Ownership is thread.parent via sioc:has_parent.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container."},title:{type:"string",predicate:DCTerms.title,description:"Thread title."},status:{type:"string",predicate:UDFS.status,description:"Thread lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},workspace:{type:"uri",predicate:UDFS.workspace,description:"Storage-layer workspace/container URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."}},uniqueBy:["id"],writableFields:["parent","title","status","starred","workspace","metadata"],mergePolicy:"upsert",examples:[{request:"Create a thread under a chat surface",match:{id:"chat/team/index.ttl#thread"}}]},messageDescriptor={uri:MEETING.Message,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.Message,resourceKind:"message",description:"Human/runtime communication item under one parent command surface and optionally a concrete thread timeline.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container URI."},chat:{type:"uri",predicate:WF.message,references:{resource:"chat",key:"id"},description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,references:{resource:"thread",key:"id"},description:"Thread containment relation."},maker:{type:"uri",predicate:FOAF.maker,description:"Author resource IRI."},role:{type:"string",predicate:UDFS.messageType,description:"Message role."},content:{type:"text",predicate:SIOC.content,required:!0,description:"Plain text content."},richContent:{type:"text",predicate:SIOC.richContent,description:"Structured/rich content payload."},status:{type:"string",predicate:UDFS.messageStatus,description:"Message lifecycle status."},toolName:{type:"string",predicate:UDFS.toolName,description:"Tool name for tool messages."},toolCallId:{type:"string",predicate:UDFS.toolCallId,description:"Opaque tool call id; not a resource relation."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},replacedBy:{type:"string",predicate:DCTerms.isReplacedBy,description:"Replacement message reference."},deletedAt:{type:"timestamp",predicate:SCHEMA.dateDeleted,description:"Deletion timestamp."},senderName:{type:"string",predicate:UDFS.senderName,description:"Display sender name."},senderAvatarUrl:{type:"uri",predicate:UDFS.senderAvatarUrl,description:"Display sender avatar."},mentions:{type:"uri",predicate:UDFS.mentions,array:!0,description:"Mentioned resource URIs."},replyTo:{type:"uri",predicate:UDFS.replyTo,description:"Original message URI."},routedBy:{type:"uri",predicate:UDFS.routedBy,description:"Routing agent URI."},routeTargetAgent:{type:"uri",predicate:UDFS.routeTargetAgent,description:"Target agent URI."},coordinationId:{type:"string",predicate:UDFS.coordinationId,description:"Opaque multi-agent coordination id."}},uniqueBy:["id"],writableFields:["parent","chat","thread","maker","role","content","richContent","status","toolName","toolCallId","metadata","replacedBy","deletedAt","senderName","senderAvatarUrl","mentions","replyTo","routedBy","routeTargetAgent","coordinationId"],mergePolicy:"append",examples:[{request:"Append a message under a team chat",match:{id:"chat/team/2026/06/14/messages.ttl#msg_1"}}]},chatProjectContextDescriptor={uri:UDFS.ChatProjectContext,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ChatProjectContext,resourceKind:"chat-project-context",description:"Workspace-scoped instructions and explicit memory-use preference shared by related chat threads.",storage:exactIdStorage("/.data/chat-projects/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this context."},instructions:{type:"text",predicate:UDFS.systemMessage,description:"User-maintained project instructions."},memoryEnabled:{type:"boolean",predicate:UDFS.memoryEnabled,description:"Whether explicit project memories may be injected into model context."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","instructions","memoryEnabled","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Save shared instructions for a workspace",match:{id:"workspace-key.ttl"}}]},chatProjectMemoryDescriptor={uri:UDFS.ProjectMemory,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ProjectMemory,resourceKind:"chat-project-memory",description:"One user-approved, workspace-scoped memory entry with optional message provenance.",storage:exactIdStorage("/.data/chat-project-memories/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this memory."},text:{type:"text",predicate:SCHEMA.text,required:!0,description:"Explicit memory text."},sourceMessage:{type:"uri",predicate:UDFS.sourceMessage,description:"Optional source message URI."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","text","sourceMessage","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Remember an explicit project fact",match:{id:"memory-id.ttl"}}]},conversationShareDescriptor={uri:UDFS.ConversationShare,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ConversationShare,resourceKind:"conversation-share",description:"Revocable metadata record for a sanitized, read-only conversation export.",storage:exactIdStorage("/.data/chat-shares/"),fields:{id:idField,thread:{type:"uri",predicate:UDFS.targetThread,required:!0,description:"Shared thread URI."},resourceUrl:{type:"uri",predicate:SCHEMA.url,required:!0,description:"Public read-only HTML resource URL."},includeToolDetails:{type:"boolean",predicate:UDFS.includeToolDetails,description:"Whether sanitized tool details were included."},excludedMessageIds:{type:"string",predicate:UDFS.excludedMessage,array:!0,description:"Messages excluded by the user before sharing."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp."}},uniqueBy:["id"],writableFields:["thread","resourceUrl","includeToolDetails","excludedMessageIds","createdAt","revokedAt"],mergePolicy:"upsert",examples:[{request:"Record a read-only conversation share",match:{id:"share-id.ttl"}}]},ideaDescriptor={uri:UDFS.Idea,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Idea,resourceKind:"idea",description:"File-primary candidate extracted from conversation before it is promoted to committed work. The document owns human-readable content; meta owns status and routing facts.",storage:exactIdStorage("/.data/ideas/"),fields:{id:idField,summary:{type:"string",predicate:DCTerms.abstract,required:!0,description:"Short summary of the idea."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the idea body."},input:{type:"text",predicate:DCTerms.description,description:"Original or synthesized input text."},status:{type:"string",predicate:UDFS.status,description:"Idea lifecycle status."},commitment:{type:"string",predicate:UDFS.commitment,description:"Commitment level such as thought, direction, tentative_decision, or committed."},affectedArea:{type:"string",predicate:UDFS.affectedArea,description:"System or product area the idea may affect."},currentUnderstanding:{type:"text",predicate:UDFS.currentUnderstanding,description:"Current synthesized understanding."},openQuestions:{type:"text",predicate:UDFS.openQuestions,array:!0,description:"Open questions before promotion."},related:{type:"uri",predicate:DCTerms.relation,array:!0,description:"Related control records or resources."},conflicts:{type:"text",predicate:UDFS.conflicts,array:!0,description:"Potential semantic conflicts."},nextStep:{type:"text",predicate:UDFS.nextStep,description:"Suggested next action."},promotedTo:{type:"uri",predicate:UDFS.promotedTo,description:"Committed resource created from the idea."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},sourceMessages:{type:"uri",predicate:DCTerms.source,array:!0,description:"Source messages."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["summary","document","input","status","commitment","affectedArea","currentUnderstanding","openQuestions","related","conflicts","nextStep","promotedTo","chat","thread","sourceMessages","createdBy","metadata"],mergePolicy:"upsert",examples:[{request:"Capture a fragmented product idea for later triage",match:{id:"2026/05/28.ttl#idea_symphony_quality_metrics"}}]},issueDescriptor={uri:UDFS.Issue,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Issue,resourceKind:"issue",description:"File-primary user-facing work item for a requirement, bug, support item, investigation, or feature request. The document owns human-readable content; meta owns status and routing facts.",storage:{base:"/.data/issues/",resourceIdPattern:"{id}"},fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Compact issue label for list/search surfaces; the file owns the full title/body."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the issue body."},description:{type:"text",predicate:DCTerms.description,description:"Issue description."},status:{type:"string",predicate:UDFS.status,description:"Issue lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Issue priority."},labels:{type:"text",predicate:UDFS.tags,array:!0,description:"Tags or labels."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,references:{resource:"issue",key:"id"},description:"Parent issue."},tasks:{type:"uri",predicate:UDFS.task,array:!0,description:"Executable task slices."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},closedAt:{type:"timestamp",predicate:UDFS.closedAt,description:"Closure timestamp."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."}},uniqueBy:["id"],writableFields:["title","document","description","status","priority","labels","chat","thread","parentIssue","tasks","createdBy","assignedTo","closedAt","deletedAt"],mergePolicy:"upsert",examples:[{request:"Create a Symphony issue for a delegated implementation slice",match:{id:"issue_symphony_runtime_projection.ttl"}}]},taskDescriptor={uri:UDFS.Task,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Task,resourceKind:"task",description:"Durable executable work unit. Scheduling, runner selection, and concrete attempts live outside Task.",storage:exactIdStorage("/.data/task/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,description:"Task title."},instruction:{type:"text",predicate:UDFS.instruction,required:!0,description:"Executable instruction."},prompt:{type:"text",predicate:UDFS.prompt,description:"Runtime prompt projection."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},required:!0,description:"Scheduled task."},status:{type:"string",predicate:UDFS.status,description:"Schedule lifecycle status."},scheduleKind:{type:"string",predicate:UDFS.scheduleKind,description:"Schedule kind: once, interval, or cron."},cron:{type:"string",predicate:UDFS.cron,description:"Cron expression."},intervalSeconds:{type:"number",predicate:UDFS.intervalSeconds,description:"Interval in seconds."},timezone:{type:"string",predicate:UDFS.timezone,description:"Timezone."},startsAt:{type:"timestamp",predicate:UDFS.startsAt,description:"Start timestamp."},nextRunAt:{type:"timestamp",predicate:UDFS.nextRunAt,description:"Next run timestamp."},lastRunAt:{type:"timestamp",predicate:UDFS.lastRunAt,description:"Last run timestamp."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["task","status","scheduleKind","cron","intervalSeconds","timezone","startsAt","nextRunAt","lastRunAt","metadata"],mergePolicy:"upsert",examples:[{request:"Create a time trigger for a task",match:{id:"schedules/schedule_1.ttl"}}]},automationRuleDescriptor={uri:UDFS.AutomationRule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AutomationRule,resourceKind:"automation_rule",description:"Policy, condition, and action wiring that can dispatch tasks or scheduled work.",storage:exactIdStorage(),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Rule title."},description:{type:"text",predicate:DCTerms.description,description:"Rule description."},status:{type:"string",predicate:UDFS.status,description:"Rule lifecycle status."},ruleKind:{type:"string",predicate:UDFS.ruleKind,description:"Rule kind: event, schedule, or manual."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,references:{resource:"schedule",key:"id"},description:"Schedule that triggers this rule."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},condition:{type:"json",predicate:UDFS.condition,description:"Structured condition."},actions:{type:"json",predicate:UDFS.actions,description:"Structured actions."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},lastTriggeredAt:{type:"timestamp",predicate:UDFS.lastTriggeredAt,description:"Last trigger timestamp."},lastRunStatus:{type:"string",predicate:UDFS.lastRunStatus,description:"Last run status."}},uniqueBy:["id"],writableFields:["title","description","status","ruleKind","task","schedule","source","target","condition","actions","metadata","lastTriggeredAt","lastRunStatus"],mergePolicy:"upsert",examples:[{request:"Create an automation rule that dispatches a task",match:{id:"automation/rule_1.ttl"}}]},deliveryDescriptor={uri:UDFS.Delivery,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Delivery,resourceKind:"delivery",description:"Internal handoff envelope between threads, sessions, agents, and runtimes.",storage:exactIdStorage(),fields:{id:idField,kind:{type:"string",predicate:UDFS.deliveryKind,description:"Delivery kind."},status:{type:"string",predicate:UDFS.status,description:"Delivery lifecycle status."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being delivered."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,references:{resource:"thread",key:"id"},description:"Target thread."},targetSession:{type:"uri",predicate:UDFS.targetSession,description:"Target session."},actor:{type:"uri",predicate:AS.actor,description:"Actor."},object:{type:"uri",predicate:AS.object,description:"Object resource."},objective:{type:"text",predicate:UDFS.objective,description:"Short objective."},payload:{type:"json",predicate:UDFS.payload,description:"Structured payload."},projection:{type:"json",predicate:UDFS.projection,description:"Runtime projection."},projectedRole:{type:"string",predicate:UDFS.projectedRole,description:"Projected runtime role."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},error:{type:"text",predicate:UDFS.error,description:"Failure detail."},dispatchedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Dispatch timestamp."},consumedAt:{type:"timestamp",predicate:UDFS.consumedAt,description:"Consumption timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["kind","status","task","source","target","chat","thread","targetThread","targetSession","actor","object","objective","payload","projection","projectedRole","metadata","error","dispatchedAt","consumedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Create a worker delivery package",match:{id:"task/symphony/2026/05/28/deliveries.ttl#delivery_1"}}]},runDescriptor={uri:UDFS.Run,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Run,resourceKind:"run",description:"One concrete execution attempt by an agent runtime.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Delivery that caused or carries this run."},trigger:{type:"uri",predicate:UDFS.trigger,description:"Resource that triggered the run."},input:{type:"uri",predicate:UDFS.input,description:"Concrete input/context projection resource."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},required:!0,description:"Runtime thread."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Run lifecycle status."},runner:{type:"string",predicate:UDFS.runner,required:!0,description:"Runtime implementation."},prompt:{type:"string",predicate:UDFS.prompt,description:"Prompt or prompt version."},externalRunId:{type:"string",predicate:UDFS.externalRunId,description:"Opaque external runtime id; not a resource relation."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Lease owner."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Lease expiration timestamp."},heartbeatAt:{type:"timestamp",predicate:UDFS.heartbeatAt,description:"Heartbeat timestamp."},cancelRequestedAt:{type:"timestamp",predicate:UDFS.cancelRequestedAt,description:"Cancel request timestamp."},error:{type:"string",predicate:UDFS.error,description:"Failure detail."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},startedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Start timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["task","delivery","trigger","input","thread","workspace","status","runner","prompt","externalRunId","leaseOwner","leaseExpiresAt","heartbeatAt","cancelRequestedAt","error","metadata","startedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Record a runtime execution attempt",match:{id:"task/symphony/2026/05/28/runs.ttl#run_1"}}]},runStepDescriptor={uri:UDFS.RunStep,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.RunStep,resourceKind:"run_step",description:"Append-only execution fact emitted while a run executes.",storage:exactIdStorage(),fields:{id:idField,run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},required:!0,description:"Run this step belongs to."},stepType:{type:"string",predicate:UDFS.stepType,required:!0,description:"RunStep event type."},message:{type:"string",predicate:DCTerms.description,description:"Human-readable step message."},payload:{type:"json",predicate:UDFS.payload,description:"Structured step payload."}},uniqueBy:["id"],writableFields:["run","stepType","message","payload"],mergePolicy:"append",examples:[{request:"Append a runtime tool call step",match:{id:"task/symphony/2026/05/28/runs.ttl#run-step_1"}}]},evidenceDescriptor={uri:UDFS.Evidence,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Evidence,resourceKind:"evidence",description:"Append-only proof or finding for a workflow control object.",storage:exactIdStorage(),fields:{id:idField,evidenceKind:{type:"string",predicate:UDFS.evidenceKind,required:!0,description:"Evidence kind."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object this evidence supports."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},summary:{type:"text",predicate:DCTerms.abstract,description:"Evidence summary."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the evidence."},outcome:{type:"string",predicate:UDFS.outcome,description:"Evidence outcome."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["evidenceKind","about","issue","task","delivery","run","thread","summary","source","actor","outcome","metadata"],mergePolicy:"append",examples:[{request:"Record test evidence for a task",match:{id:"task/symphony/2026/05/28/evidence.ttl#evidence_1"}}]},reportDescriptor={uri:UDFS.Report,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Report,resourceKind:"report",description:"Closure, review, handoff, status, or quality summary for a control object.",storage:exactIdStorage(),fields:{id:idField,reportKind:{type:"string",predicate:UDFS.reportKind,required:!0,description:"Report kind."},status:{type:"string",predicate:UDFS.status,description:"Report lifecycle status."},outcome:{type:"string",predicate:UDFS.outcome,description:"Reported outcome."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object being summarized."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,references:{resource:"evidence",key:"id"},array:!0,description:"Evidence summarized by this report."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Report summary."},reviewer:{type:"uri",predicate:SCHEMA.reviewedBy,description:"Reviewer."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the report."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},metricFacts:{type:"json",predicate:UDFS.metricFacts,description:"Structured metric facts."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},publishedAt:{type:"timestamp",predicate:DCTerms.issued,description:"Publication timestamp."}},uniqueBy:["id"],writableFields:["reportKind","status","outcome","about","issue","task","delivery","run","thread","evidence","summary","reviewer","actor","source","metricFacts","metadata","publishedAt"],mergePolicy:"upsert",examples:[{request:"Publish a worker handoff report",match:{id:"task/symphony/2026/05/28/reports.ttl#report_1"}}]},sessionDescriptor={uri:UDFS.term("Session"),version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.term("Session"),resourceKind:"session",description:"Runtime or collaboration session lifecycle projection for a concrete thread.",storage:exactIdStorage("/.data/sessions/"),fields:{id:idField,owner:{type:"uri",predicate:UDFS.actor,required:!0,description:"Session owner."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},status:{type:"string",predicate:UDFS.sessionStatus,description:"Session lifecycle status."},tool:{type:"string",predicate:UDFS.sessionTool,description:"Runtime tool or backend."},tokenUsage:{type:"number",predicate:UDFS.tokenUsage,description:"Token usage."},messages:{type:"uri",predicate:UDFS.message,array:!0,description:"Messages in this session."},policy:{type:"uri",predicate:UDFS.policy,description:"Policy resource."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},archivedAt:{type:"timestamp",predicate:UDFS.archivedAt,description:"Archive timestamp."}},uniqueBy:["id"],writableFields:["owner","chat","thread","status","tool","tokenUsage","messages","policy","policyVersion","metadata","archivedAt"],mergePolicy:"upsert",examples:[{request:"Record a worker runtime session",match:{id:"2026/05/28/sess_1.ttl"}}]},officialPodModelDescriptors=[credentialDescriptor,gatewayAccessKeyDescriptor,quotaSnapshotDescriptor,aiProviderDescriptor,aiModelDescriptor,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(n=officialPodModelDescriptors){const e=new Map(n.map(t=>[t.uri,t]));return{list(t={}){return n.filter(i=>!(t.source&&i.source!==t.source||t.resourceKind&&i.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const i=t.uri??t.schemaUri;if(!i)return n.list();const s=n.describe(i);return s?[s]:[]};return{list:n.list,describe(t){const i=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(i)},classes(t={}){return e(t).map(i=>({schemaUri:i.uri,resourceKind:i.resourceKind,class:i.class,namespace:i.namespace,source:i.source,trustLevel:i.trustLevel,description:i.description}))},search(t){const i=normalizeSearchTerms(t.query);return i.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(s=>scoreDescriptorSearch(s,i)).filter(s=>s!==null).sort((s,a)=>a.score-s.score||s.uri.localeCompare(a.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,a])=>({schemaUri:i.uri,field:s,predicate:a.predicate,type:a.type,required:!!a.required,secret:!!a.secret,array:!!a.array,description:a.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(a,l,u)=>{if(!l)return;const h=l.toLowerCase();for(const d of e)h.includes(d)&&(t.add(a),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[a,l]of Object.entries(n.fields))s(`field:${a}`,a,6),s(`predicate:${a}`,l.predicate,6),s(`description:${a}`,l.description,3);for(const a of n.examples){s("example",a.request,3);for(const[l,u]of Object.entries(a.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const CLOUD_PROVISIONING_UNAVAILABLE="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",localProvisionResolvers=new WeakMap;function isManagedLocalProvisionHost(){return typeof window<"u"&&localProvisionResolvers.has(window)}function unregisterLocalProvisionResolver(){typeof window<"u"&&localProvisionResolvers.delete(window)}function registerLocalProvisionResolver(n){typeof window<"u"&&localProvisionResolvers.set(window,n)}function readStoredProvisionCodeRaw(){try{const n=sessionStorage.getItem("provisionCode")?.trim();return n||void 0}catch{return}}function isProvisionCodeCurrent(n){const e=n.split(".")[0];if(!e)return!0;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return!0;const s=JSON.parse(globalThis.atob(i));return typeof s.exp=="number"?s.exp>Math.floor(Date.now()/1e3):!0}catch{return!0}}function normalizeProvisionCode(n){const e=n?.trim();if(e)return isProvisionCodeCurrent(e)?e:void 0}function getStoredProvisionCode(){return normalizeProvisionCode(readStoredProvisionCodeRaw())}function setStoredProvisionCode(n){try{sessionStorage.setItem("provisionCode",n)}catch{}}function clearStoredProvisionCode(){try{sessionStorage.removeItem("provisionCode")}catch{}}function buildPodCreatePayload(n,e=getStoredProvisionCode(),t){const i={name:n.trim()};return e&&(i.settings={provisionCode:e,...t?{provisionReceipt:t}:{}}),i}async function resolveProvisionCodeForCurrentScope(n){const e=await resolveCurrentProvisionTargetState(n);if(e.activeProvisionCode)return e.activeProvisionCode;if(e.hasProvisionOperation)throw new Error(CLOUD_PROVISIONING_UNAVAILABLE)}async function resolveCurrentProvisionTargetState(n){const e=typeof window<"u"?window.__XPOD__:void 0;if(e?.authenticating===!0){const l=typeof e.provisionCode=="string"?e.provisionCode.trim():void 0,u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):(clearStoredProvisionCode(),l?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}:{hasProvisionOperation:!1})}const t=n?.trim()||(typeof e?.provisionCode=="string"?e.provisionCode.trim():void 0),i=typeof window<"u"?localProvisionResolvers.get(window):void 0;if(!t&&i){const l=await i(),u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}}const s=t||readStoredProvisionCodeRaw(),a=normalizeProvisionCode(s);return a?{activeProvisionCode:a,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(a)?.storageRoot}:s?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(s)?.storageRoot}:{hasProvisionOperation:!1}}async function resolveProvisionCodeForPodCreate(n){return resolveProvisionCodeForCurrentScope(n)}function decodeProvisionScopePayload(n){const e=parseProvisionScopePayload(n);if(!e)return;const t=typeof e.serviceAccessToken=="string"?e.serviceAccessToken:typeof e.serviceToken=="string"?e.serviceToken:void 0;if(!(typeof e.spUrl!="string"||!t)&&!(typeof e.exp=="number"&&e.exp<Math.floor(Date.now()/1e3))&&!(typeof e.serviceAccessTokenExp=="number"&&e.serviceAccessTokenExp<Math.floor(Date.now()/1e3)))return{spUrl:ensureTrailingSlash(e.spUrl),serviceToken:t,serviceAccessToken:typeof e.serviceAccessToken=="string"?e.serviceAccessToken:void 0,serviceAccessTokenExp:typeof e.serviceAccessTokenExp=="number"?e.serviceAccessTokenExp:void 0,spDomain:typeof e.spDomain=="string"?e.spDomain:void 0,exp:typeof e.exp=="number"?e.exp:void 0}}function parseProvisionScopePayload(n){if(!n)return;const e=n.split(".")[0];if(e)try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return;const s=Uint8Array.from(globalThis.atob(i),a=>a.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return}}function resolveProvisionScope(n){const e=decodeProvisionScopePayload(n);if(!e)return;const t=e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl);return{lookupUrl:t,storageRoot:t,serviceToken:e.serviceToken}}function resolveProvisionStorageTarget(n){const e=parseProvisionScopePayload(n);if(typeof e?.spUrl=="string")return{storageRoot:e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl)}}async function prepareProvisionedPod(n,e,t){const i=resolveProvisionScope(t);if(!i||!t)return t?{provisionCode:t}:void 0;const s=await n(new URL("/provision/pods",resolveProvisionApiBaseUrl(i)).toString(),{method:"POST",headers:{Authorization:`Bearer ${i.serviceToken}`,"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({podName:e})});if(!s.ok)throw new Error(await readResponseMessage(s)??"Failed to prepare Local Pod");const a=await s.json().catch(()=>{}),l=typeof a?.provisionReceipt=="string"?a.provisionReceipt:void 0;if(!l)throw new Error("Local Pod preparation did not return a provision receipt");return{provisionCode:t,provisionReceipt:l}}function resolveProvisionApiBaseUrl(n){return(isManagedLocalProvisionHost()?currentLoopbackLookupUrl():void 0)??n.lookupUrl}function currentLoopbackLookupUrl(){if(!(typeof window>"u"))try{const n=new URL(window.location.href);return isLoopbackHostname$3(n.hostname)?ensureTrailingSlash(n.origin):void 0}catch{return}}function isLoopbackHostname$3(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}async function readResponseMessage(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}async function filterWebIdsByStorageRoot(n,e,t){const i=normalizeStorageRoot(t);if(!i)return[];const s=Array.from(new Set(e.filter(l=>typeof l=="string"&&l.length>0)));return(await Promise.all(s.map(async l=>{const h=(await fetchProfileStorageUrls(n,l)).find(d=>storageUrlBelongsToRoot(d,i));return h?{webId:l,storageUrl:ensureTrailingSlash(h)}:void 0}))).filter(l=>!!l)}function storageUrlBelongsToRoot(n,e){const t=normalizeStorageUrl(n),i=normalizeStorageRoot(e);return!!(t&&i&&t.startsWith(i))}function normalizeStorageRoot(n){if(n)try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,a=!1)=>{if(typeof s=="string"){a&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,a);return}for(const[l,u]of Object.entries(s)){const h=SOLID_STORAGE_KEYS.has(l);if(a&&l==="@id"){i(u,!0);continue}i(u,a||h)}}};return i(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const i=normalizeStorageUrl(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let a=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:h,fetch:d})=>drizzle({get info(){return s.info},fetch:d},{podUrl:h,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:l,pod:u,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??a??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>a??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:h=>{const d=normalizeXpodOidcIssuer(h);a=d,d&&writeStoredOidcIssuer(d,e.issuer)},setLocalPodRoute:h=>{t=h?[h,...["/api/","/v1/","/.notifications/"].map(d=>({canonicalBaseUrl:new URL(d,h.canonicalBaseUrl).href,localBaseUrl:new URL(d,h.localBaseUrl).href}))]:[]},resolveLocalUrl:h=>resolveSolidLocalRouteUrl(h,t)?.href??h}}function createInruptSession(n=getOptionalPersistentStorage(),e=globalThis.fetch){return new Session({fetch:e,...n?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(n,"insecure")}:{}})}function toInruptStorage(n,e){const t=i=>inruptStorageKey(e,i);return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(n)};const i=t?.ok?await t.json().catch(()=>{}):void 0,s=normalizeXpodOidcIssuer(i?.oidcIssuer);if(i?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(n)};const a=typeof i?.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0;if(!s||i?.managed===!0&&!a)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:a}}function safeAuthError(n){if(n.name==="SolidSessionPendingError"){const e=new Error("上次登录尚未结束,请刷新页面后重新登录。");return e.name=n.name,e}return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage()){try{return normalizeXpodOidcIssuer(n?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(n){try{n?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage();return{oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function currentProvisionLocalOriginRoute(n){if(!(typeof window>"u")&&!(n.managed!==!0||typeof n.storageRoot!="string")&&isLoopbackHostname$2(window.location.hostname))try{const e=new URL(n.storageRoot);return!["http:","https:"].includes(e.protocol)||e.username||e.password||e.origin===window.location.origin?void 0:{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:new URL(e.pathname,window.location.origin).href}}catch{return}}function isLoopbackHostname$2(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}const CALLBACK_IDENTITY_PREFIX="xpod.auth.callback.identity.v1.",RETRYABLE_STORAGE_FAILURE_CODES=new Set(["provision-status-unavailable","profile-read-failed","pod-open-failed"]),CALLBACK_COMPLETION_PREFIX="xpod.auth.callback.completed.v1.",CALLBACK_COMPLETION_TTL_MS=600*1e3,INRUPT_CURRENT_URL_KEY="solidClientAuthn:currentUrl",callbackRuns=new Map,AUTO_RESET_FAILURE_CODES=new Set(["webid-mismatch","binding-mismatch"]),FAILURE_MESSAGES={"missing-transaction":{title:"登录请求已失效",message:"这次登录请求已经失效,请重新登录。",action:"重新登录"},"replayed-transaction":{title:"登录请求已使用",message:"这次登录请求已经完成,不能再次使用。请重新登录。",action:"重新登录"},"expired-transaction":{title:"登录请求已过期",message:"登录等待时间过长,请重新登录。",action:"重新登录"},"malformed-transaction":{title:"登录请求无效",message:"登录信息不完整或已被修改,请重新登录。",action:"重新登录"},"oidc-state-invalid":{title:"登录验证已失效",message:"登录页面与当前会话不再匹配,请重新登录。",action:"重新登录"},"oidc-provider-error":{title:"授权未完成",message:"身份服务未能完成此次授权,请重新登录。",action:"重新登录"},unauthenticated:{title:"登录没有完成",message:"Xpod 没有收到有效的 WebID,请重新登录。",action:"重新登录"},"unsafe-route":{title:"登录请求不安全",message:"Xpod 已阻止异常的登录来源,请从应用内重新登录。",action:"重新登录"},"unsafe-return-to":{title:"登录请求不安全",message:"Xpod 已阻止异常的返回地址,请从应用内重新登录。",action:"重新登录"},"missing-storage":{title:"没有可用的 Pod",message:"当前账号还没有可用于本次登录的 Pod,请返回后重试。",action:"返回并重试"},"provision-status-unavailable":{title:"暂时无法确认本机 Pod",message:"Xpod 暂时无法读取存储服务状态,请稍后重试。",action:"重试连接"},"local-binding-missing":{title:"本机绑定尚未完成",message:"当前账号还没有绑定到这台 Xpod。请先修复本机初始化,再重新登录。",action:"修复本机绑定"},"webid-mismatch":{title:"身份与 Pod 不匹配",message:"本次登录身份与所选 Pod 不一致,请重新登录。",action:"重新登录"},"binding-mismatch":{title:"身份与 Pod 不匹配",message:"Xpod 无法确认当前身份拥有所选 Pod,请重新登录。",action:"重新登录"},"profile-read-failed":{title:"暂时无法读取身份资料",message:"未能读取你的 WebID 资料,暂时无法确认 Pod 地址。请稍后重试,不需要重新创建 Pod。",action:"重试连接"},"pod-open-failed":{title:"暂时无法打开 Pod",message:"Xpod 无法连接到你的 Pod,请检查服务状态后重试。",action:"重试连接"},"storage-unavailable":{title:"无法保存登录状态",message:"当前环境无法保存本次登录状态,请重新打开 Xpod 后重试。",action:"重新登录"},"redirect-failed":{title:"登录已完成",message:"身份验证已经完成,但目标页面没有正常打开。",action:"返回概览"}};async function completeXpodOidcCallback(n){const e=new URL(n.href),t=e.origin,i=captureRecoveryPointers(),s=findCompletedCallbackDestination(e,n.storage,n.now);if(s)return n.locationReplace?.(s),{status:"redirected",destination:s};let a=e.searchParams.get("transaction");const l=e.searchParams.has("code")||e.searchParams.has("state")||e.searchParams.has("error"),u=l?readInruptCurrentDestination(e):void 0;let h,d,p;try{h=n.transactionStore??createXpodLoginTransactionStore({storage:n.storage,origin:t});const A=h.readSinglePending();!a&&A&&(a=A.id),a?!A||A.id!==a?(h.consume(a),p=failure("missing-transaction")):d=A:p=failure("missing-transaction")}catch(A){p=failure(transactionFailureCode(A))}const g=a?readCompletedDestination(e,a,n.storage,n.now):void 0;if(g){if(l&&u&&!d){const A=await handleIncomingRedirect(n.runtime,n.href);if(A.status==="failure"){const C=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return C||A}return n.locationReplace?.(u),{status:"redirected",destination:u}}return n.locationReplace?.(g),{status:"redirected",destination:g}}if(!d){if(u){const A=await handleIncomingRedirect(n.runtime,n.href);if(A.status==="failure"){const C=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return C||A}return n.locationReplace?.(u),{status:"redirected",destination:u}}return p??failure("missing-transaction")}if(!h||!a)return failure("missing-transaction");const m=await resumeOrCompleteIdentity(n,d);if(m.status==="failure"){const A=await recoverFailedOidcCallback({callbackUrl:e,destination:productDestinationForTransaction(d,t),recoveryPointers:i,transactionStore:h,transactionId:a,storage:n.storage,locationReplace:n.locationReplace});return A||m}const v=m.webId,S=n.runtime.session.createAuthenticatedFetch(v);let E=!1;const w=n.runtime.session.subscribe(()=>{E=!0,n.runtime.pod.clear({webId:v})});try{try{assertXpodLoginRoute(d.route,t)}catch{return failure("unsafe-route")}let A;try{A=normalizeXpodReturnTo(d.returnTo)}catch{return failure("unsafe-return-to")}const C=d.selectedStorage&&new URL(d.selectedStorage.storageUrl).origin===t?{storageRoot:t,available:!0}:await resolveCurrentXpodProvisionStatus(n.fetch??fetch,t);if(E)return failure("pod-open-failed");if(!C.available)return failure("provision-status-unavailable");const T=C.storageRoot,F=currentProvisionLocalOriginRoute(C);F&&n.runtime.setLocalPodRoute(F);let P;try{P=d.selectedStorage??await discoverCurrentXpodStorage(S,v,T)}catch{return failure("profile-read-failed")}if(E)return failure("pod-open-failed");if(P&&!isSafeSelectedStorage(P,t,T))return failure("binding-mismatch");if(P&&P.webId!==v)return failure("webid-mismatch");if(!P)return C.managed?failure("local-binding-missing",C.provisionUrl):failure("missing-storage");let M;try{n.runtime.setLocalPodRoute(currentProvisionLocalPodRoute(P.storageUrl,C)),M=await n.runtime.pod.open({webId:v,podUrl:P.storageUrl,fetch:S})}catch{return{...failure("pod-open-failed")}}if(E)return failure("pod-open-failed");const $=P;if(!isSafeSelectedStorage($,t,T)||M.webId!==$.webId||!sameUrl$3(M.podUrl,$.storageUrl))return failure("binding-mismatch");try{rememberXpodSelectedStorage($,{storage:n.storage,origin:t,storageRoot:T,now:n.now})}catch{return failure("storage-unavailable")}const G=new URL(A??XPOD_DEFAULT_RETURN_PATH,t).href;try{h.consume(a),rememberCompletedDestination(a,G,e,n.storage,n.now),(n.storage??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${a}`),n.locationReplace?.(G)}catch{return clearXpodSelectedStorage({storage:n.storage}),failure("redirect-failed")}return{status:"redirected",destination:G,transaction:d,selectedStorage:$,pod:M}}finally{w()}}async function resumeOrCompleteIdentity(n,e){const t=new URL(n.href),i=n.storage??window.sessionStorage,s=`${CALLBACK_IDENTITY_PREFIX}${e.id}`,a=callbackIdentity(t),l=n.now??Date.now;try{const h=i.getItem(s);if(h){const d=JSON.parse(h);if(!isRecord$1(d)||d.callback!==a||typeof d.webId!="string"||typeof d.completedAt!="number"||!Number.isFinite(d.completedAt))return failure("oidc-state-invalid");if(l()<d.completedAt||l()-d.completedAt>CALLBACK_COMPLETION_TTL_MS)return failure("expired-transaction");const p=n.runtime.session.getSnapshot();return p.status!=="authenticated"?failure("unauthenticated"):p.webId!==d.webId?failure("webid-mismatch"):{status:"success",webId:p.webId}}}catch{return failure("storage-unavailable")}const u=await handleIncomingRedirect(n.runtime,n.href);if(u.status==="failure")return u;try{i.setItem(s,JSON.stringify({callback:a,webId:u.webId,completedAt:l()}))}catch{return failure("storage-unavailable")}return u}function completeXpodOidcCallbackOnce(n){const e=new URL(n.href);if(findCompletedCallbackDestination(e,n.storage,n.now))return completeXpodOidcCallback(n);const t=callbackRunKey(e,n.transactionStore),i=callbackRuns.get(t);if(i)return i;const s=completeXpodOidcCallback(n);return callbackRuns.set(t,s),s}function callbackRunKey(n,e){let t=n.searchParams.get("transaction");if(!t)try{t=e?.readSinglePending()?.id??createXpodLoginTransactionStore({origin:n.origin}).readSinglePending()?.id??(readInruptCurrentDestination(n)?"<silent>":"<missing>")}catch{t=readInruptCurrentDestination(n)?"<silent>":"<missing>"}return`${n.origin}:${t}`}function callbackIdentity(n){return`${n.origin}${n.pathname}?state=${encodeURIComponent(n.searchParams.get("state")??"")}`}function findCompletedCallbackDestination(n,e,t){if(n.searchParams.get("state"))try{const i=e??window.sessionStorage,s=n.searchParams.get("transaction");for(let a=0;a<i.length;a+=1){const l=i.key(a);if(!l?.startsWith(CALLBACK_COMPLETION_PREFIX))continue;const u=l.slice(CALLBACK_COMPLETION_PREFIX.length);if(s&&s!==u)continue;const h=i.getItem(l);if(!h)continue;const d=JSON.parse(h);if(isRecord$1(d)&&d.callback===callbackIdentity(n))return readCompletedDestination(n,u,i,t)}}catch{}}function readCompletedDestination(n,e,t,i=()=>Date.now()){try{const s=t??window.sessionStorage,a=`${CALLBACK_COMPLETION_PREFIX}${e}`,l=s.getItem(a);if(!l)return;const u=JSON.parse(l);if(u.callback!==void 0&&u.callback!==callbackIdentity(n)||typeof u.destination!="string"||typeof u.completedAt!="number"||!Number.isFinite(u.completedAt))return;if(i()<u.completedAt||i()-u.completedAt>CALLBACK_COMPLETION_TTL_MS){s.removeItem(a);return}const h=new URL(u.destination);if(h.origin!==n.origin||h.username||h.password)return;const d=normalizeXpodReturnTo(`${h.pathname}${h.search}${h.hash}`);return d?new URL(d,n.origin).href:void 0}catch{return}}function readInruptCurrentDestination(n){try{const e=window.localStorage.getItem(INRUPT_CURRENT_URL_KEY);if(!e)return;const t=new URL(e,n.origin);if(t.origin!==n.origin)return;const i=`${t.pathname}${t.search}`,s=normalizeXpodReturnTo(i);return s===void 0?void 0:new URL(s,n.origin).href}catch{return}}function rememberCompletedDestination(n,e,t,i,s=()=>Date.now()){(i??window.sessionStorage).setItem(`${CALLBACK_COMPLETION_PREFIX}${n}`,JSON.stringify({destination:e,callback:callbackIdentity(t),completedAt:s()}))}function XpodOidcCallbackApp({runtime:n,transactionStore:e,href:t=typeof window>"u"?"http://localhost/auth/callback":window.location.href,location:i=typeof window>"u"?void 0:window.location,restartSignIn:s,renderRedirected:a}){const[l]=reactExports.useState(()=>n?void 0:createCallbackRuntime()),u=n??l,[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),m=reactExports.useRef(void 0),v=reactExports.useRef(!1),[S]=reactExports.useState(()=>{const A=new URL(t);return readRestartTransaction(A,e)?.id??A.searchParams.get("transaction")}),E=reactExports.useMemo(()=>resolveXpodCallbackRestartDestination({href:t,transactionStore:e}),[t,e]);if(reactExports.useEffect(()=>{m.current||(m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d))},[u,t,i,e]),reactExports.useEffect(()=>{typeof document>"u"||h?.status==="redirected"&&a||(document.title=h?.status==="failure"?`Xpod - ${FAILURE_MESSAGES[h.code].title}`:h?.status==="redirected"?"Xpod - 登录完成":"Xpod - 正在登录")},[a,h]),reactExports.useEffect(()=>{!h||h.status!=="failure"||AUTO_RESET_FAILURE_CODES.has(h.code)&&(v.current||(v.current=!0,queueMicrotask(()=>{g(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S}).finally(()=>{(s??(C=>window.location.replace(C)))(E)})})))},[u,S,t,E,s,h,e]),!h)return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在完成登录",message:"请稍候,不要关闭这个窗口。"});if(h.status==="redirected")return a?.(h)??jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"登录完成",message:"正在打开 Xpod。"});if(AUTO_RESET_FAILURE_CODES.has(h.code))return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在重新登录",message:"Xpod 正在清理不匹配的登录状态。"});const w=FAILURE_MESSAGES[h.code];return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:w.title,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex min-h-0 flex-1 flex-col px-5 pb-5",children:[jsxRuntimeExports.jsx("div",{className:"flex min-h-0 flex-1 flex-col justify-center py-5",children:jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-destructive"}),jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold leading-6 text-foreground",children:w.title})]}),jsxRuntimeExports.jsx("p",{role:"alert",className:"mt-2 text-xs leading-5 text-muted-foreground",children:w.message}),jsxRuntimeExports.jsxs("details",{className:"group mt-3 text-[11px] leading-4 text-muted-foreground",children:[jsxRuntimeExports.jsxs("summary",{className:"-ml-1 inline-flex min-h-8 cursor-pointer list-none items-center gap-1 rounded-md px-1 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":"true",className:"h-3 w-3 shrink-0 group-open:rotate-90"}),"技术详情"]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 max-h-24 overflow-y-auto overscroll-contain",children:[jsxRuntimeExports.jsx("code",{className:"block break-all text-left",children:h.code}),!1]})]})]})}),jsxRuntimeExports.jsx(Button,{type:"button",className:"w-full shrink-0 rounded-xl",disabled:p,"aria-busy":p,onClick:()=>{if(!p){if(RETRYABLE_STORAGE_FAILURE_CODES.has(h.code)){callbackRuns.delete(callbackRunKey(new URL(t),e)),d(void 0),m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d);return}g(!0),(h.code==="redirect-failed"?Promise.resolve():resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S})).finally(()=>{if(h.actionUrl){(s??(T=>window.location.replace(T)))(h.actionUrl);return}(s??(C=>window.location.replace(C)))(E)})}},children:p?"正在重置…":w.action}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",disabled:p,onClick:()=>{p||(g(!0),setXpodLoginCancelled(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S,preserveSession:!0}).finally(()=>{(s??(C=>window.location.replace(C)))(E)}))},children:"返回应用"})]})})}function resolveXpodCallbackRestartDestination({href:n,transactionStore:e,basePath:t="/auth/callback/"}){const i=new URL(n),a=readRestartTransaction(i,e)?.returnTo;if(a)try{const u=normalizeXpodReturnTo(a);if(u)return u}catch{}const l=readInruptCurrentDestination(i);if(l)try{const u=new URL(l);if(u.origin===i.origin)return`${u.pathname}${u.search}${u.hash}`}catch{}return callbackProductEntryPath(t,i.pathname)}function readRestartTransaction(n,e){try{const t=e?e.readSinglePending():createXpodLoginTransactionStore({origin:n.origin}).readSinglePending(),i=n.searchParams.get("transaction");return i&&t?.id!==i?void 0:t}catch{return}}function callbackProductEntryPath(n,e){return normalizeBasePath(n)==="/settings/"||e==="/settings/auth-callback.html"||e.startsWith("/settings/")?"/settings/":XPOD_DEFAULT_RETURN_PATH}function normalizeBasePath(n){if(n)try{const e=new URL(n,"https://xpod.local");return e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`}catch{return}}function XpodCallbackStatus({title:n,message:e}){return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:n,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold text-foreground",children:n}),jsxRuntimeExports.jsx("p",{role:"status","aria-live":"polite",className:"mt-2 max-w-[13rem] text-xs leading-5 text-muted-foreground",children:e})]})})}async function resetXpodOidcCallback({href:n,runtime:e,transactionStore:t,storage:i,preserveSession:s=!1,associatedTransactionId:a}){const l=new URL(n);let u=a===void 0?l.searchParams.get("transaction"):a;try{const h=t??createXpodLoginTransactionStore({storage:i,origin:l.origin}),d=h.readSinglePending();a===void 0&&!u&&d&&(u=d.id),d&&d.id===u&&h.cancel(d.id)}catch{}try{const h=i??window.sessionStorage;u&&(h.removeItem(`${CALLBACK_COMPLETION_PREFIX}${u}`),h.removeItem(`${CALLBACK_IDENTITY_PREFIX}${u}`)),window.localStorage.removeItem(INRUPT_CURRENT_URL_KEY)}catch{}try{s||await e.session.logout()}catch{}callbackRuns.delete(`${l.origin}:${u??"<missing>"}`),callbackRuns.delete(`${l.origin}:<silent>`),callbackRuns.delete(`${l.origin}:<missing>`)}async function handleIncomingRedirect(n,e){let t="oidc-state-invalid";try{if(new URL(e).searchParams.has("error")&&(t="oidc-provider-error"),!n.session.handleIncomingRedirect)return failure("oidc-state-invalid");const i=await n.session.handleIncomingRedirect(e);if(t==="oidc-provider-error")return failure(t);const s=isRecord$1(i)?i:void 0;if(s?.status==="error"||s?.status==="expired")return failure("oidc-state-invalid");const a=s?.status==="authenticated"||s?.isLoggedIn===!0?readString(s.webId):void 0,l=n.session.getSnapshot();if(l.status==="error"||l.status==="expired")return failure("oidc-state-invalid");const u=a??(l.status==="authenticated"?l.webId:void 0);return u?{status:"success",webId:u}:failure("unauthenticated")}catch{return failure(t)}}function isRecord$1(n){return typeof n=="object"&&n!==null}async function recoverFailedOidcCallback({callbackUrl:n,destination:e,recoveryPointers:t,transactionStore:i,transactionId:s,storage:a,locationReplace:l}){const u=n.searchParams.get("error");if(isRecoverableSilentRestoreError(u)){clearRecoverableCallbackState({transactionStore:i,transactionId:s,storage:a});for(const{storage:h,key:d,value:p}of t)try{h.getItem(d)===p&&h.removeItem(d)}catch{}return l?.(e),{status:"redirected",destination:e}}}function isRecoverableSilentRestoreError(n){return n==="login_required"||n==="interaction_required"||n==="consent_required"||n==="account_selection_required"}function clearRecoverableCallbackState({transactionStore:n,transactionId:e,storage:t}){try{const i=n?.readSinglePending(),s=e;s&&i?.id===s&&n?.cancel(s),s&&i?.id===s&&((t??window.sessionStorage).removeItem(`${CALLBACK_COMPLETION_PREFIX}${s}`),(t??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${s}`))}catch{}clearXpodSelectedStorage({storage:t})}function captureRecoveryPointers(){const n=[];for(const e of["localStorage","sessionStorage"])try{const t=window[e];for(const i of[INRUPT_CURRENT_URL_KEY,"solidClientAuthn:currentSession",XPOD_SOLID_SESSION_ID_STORAGE_KEY,XPOD_LAST_OIDC_ISSUER_STORAGE_KEY]){const s=t.getItem(i);s!==null&&n.push({storage:t,key:i,value:s})}}catch{}return n}function productDestinationForTransaction(n,e){try{const t=normalizeXpodReturnTo(n.returnTo);return new URL(t??XPOD_DEFAULT_RETURN_PATH,e).href}catch{return new URL(XPOD_DEFAULT_RETURN_PATH,e).href}}function readString(n){return typeof n=="string"&&n?n:void 0}function isSafeSelectedStorage(n,e,t){try{const i=new URL(n.storageUrl),s=new URL(n.webId);return(i.origin===e||storageUrlBelongsToRoot(i.href,t))&&["http:","https:"].includes(i.protocol)&&["http:","https:"].includes(s.protocol)&&!i.username&&!i.password&&!i.hash&&!s.username&&!s.password}catch{return!1}}async function resolveCurrentXpodProvisionStatus(n,e){const t=await n(new URL("/provision/status",e),{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{storageRoot:e,available:!0};if(!t?.ok)return{storageRoot:e,available:!1};const i=await t.json().catch(()=>{});return!i||typeof i.managed!="boolean"&&typeof i.publicUrl!="string"?{storageRoot:e,available:!1}:{available:!0,storageRoot:typeof i?.publicUrl=="string"&&i.publicUrl?i.publicUrl:e,managed:i?.managed===!0,provisionUrl:safeProvisionUrl(i?.provisionUrl)}}function safeProvisionUrl(n){if(!(typeof n!="string"||!n))try{const e=new URL(n);return e.protocol==="https:"&&!e.username&&!e.password?e.href:void 0}catch{return}}async function discoverCurrentXpodStorage(n,e,t){let i=!1;const a=await filterWebIdsByStorageRoot(async(l,u)=>{const h=await n(l,u).catch(d=>{throw String(l)===e&&(i=!0),d});return String(l)===e&&!h.ok&&(i=!0),h},[e],t);if(i)throw new Error("Unable to read WebID profile storage bindings");if(a.length===1)return a[0]}function transactionFailureCode(n){switch(n?.code){case"consumed":return"replayed-transaction";case"expired":return"expired-transaction";case"malformed":return"malformed-transaction";default:return"missing-transaction"}}function failure(n,e){return{status:"failure",code:n,message:FAILURE_MESSAGES[n].message,...e?{actionUrl:e}:{}}}function sameUrl$3(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function createCallbackRuntime(){return createXpodSolidRuntimeValue()}var ABSOLUTE_URL_REGEX=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,PROTOCOL_RELATIVE_URL_REGEX=/^[\\/]{2}/;function normalizeProtocolRelativeUrl(n,e){return e+n.replace(/\\/g,"/")}var PopStateEventType="popstate";function isLocation(n){return typeof n=="object"&&n!=null&&"pathname"in n&&"search"in n&&"hash"in n&&"state"in n&&"key"in n}function createBrowserHistory(n={}){function e(i,s){let a=s.state?.masked,{pathname:l,search:u,hash:h}=a||i.location;return createLocation("",{pathname:l,search:u,hash:h},s.state&&s.state.usr||null,s.state&&s.state.key||"default",a?{pathname:i.location.pathname,search:i.location.search,hash:i.location.hash}:void 0)}function t(i,s){return typeof s=="string"?s:createPath(s)}return getUrlBasedHistory(e,t,null,n)}function invariant(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function warning(n,e){if(!n){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function createKey(){return Math.random().toString(36).substring(2,10)}function getHistoryState(n,e){return{usr:n.state,key:n.key,idx:e,masked:n.mask?{pathname:n.pathname,search:n.search,hash:n.hash}:void 0}}function createLocation(n,e,t=null,i,s){return{pathname:typeof n=="string"?n:n.pathname,search:"",hash:"",...typeof e=="string"?parsePath(e):e,state:t,key:e&&e.key||i||createKey(),mask:s}}function createPath({pathname:n="/",search:e="",hash:t=""}){return e&&e!=="?"&&(n+=e.charAt(0)==="?"?e:"?"+e),t&&t!=="#"&&(n+=t.charAt(0)==="#"?t:"#"+t),n}function parsePath(n){let e={};if(n){let t=n.indexOf("#");t>=0&&(e.hash=n.substring(t),n=n.substring(0,t));let i=n.indexOf("?");i>=0&&(e.search=n.substring(i),n=n.substring(0,i)),n&&(e.pathname=n)}return e}function getUrlBasedHistory(n,e,t,i={}){let{window:s=document.defaultView,v5Compat:a=!1}=i,l=s.history,u="POP",h=null,d=p();d==null&&(d=0,l.replaceState({...l.state,idx:d},""));function p(){return(l.state||{idx:null}).idx}function g(){u="POP";let w=p(),A=w==null?null:w-d;d=w,h&&h({action:u,location:E.location,delta:A})}function m(w,A){u="PUSH";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p()+1;let T=getHistoryState(C,d),F=E.createHref(C.mask||C);try{l.pushState(T,"",F)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;s.location.assign(F)}a&&h&&h({action:u,location:E.location,delta:1})}function v(w,A){u="REPLACE";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p();let T=getHistoryState(C,d),F=E.createHref(C.mask||C);l.replaceState(T,"",F),a&&h&&h({action:u,location:E.location,delta:0})}function S(w){return createBrowserURLImpl(s,w)}let E={get action(){return u},get location(){return n(s,l)},listen(w){if(h)throw new Error("A history only accepts one active listener");return s.addEventListener(PopStateEventType,g),h=w,()=>{s.removeEventListener(PopStateEventType,g),h=null}},createHref(w){return e(s,w)},createURL:S,encodeLocation(w){let A=S(w);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:m,replace:v,go(w){return l.go(w)}};return E}function createBrowserURLImpl(n,e,t=!1){let i="http://localhost";n&&(i=n.location.origin!=="null"?n.location.origin:n.location.href),invariant(i,"No window.location.(origin|href) available to create URL");let s=typeof e=="string"?e:createPath(e);return s=s.replace(/ $/,"%20"),!t&&PROTOCOL_RELATIVE_URL_REGEX.test(s)&&(s=i+s),new URL(s,i)}function matchRoutes(n,e,t="/"){return matchRoutesImpl(n,e,t,!1)}function matchRoutesImpl(n,e,t,i,s){let a=typeof e=="string"?parsePath(e):e,l=stripBasename(a.pathname||"/",t);if(l==null)return null;let u=flattenAndRankRoutes(n),h=null,d=decodePath(l);for(let p=0;h==null&&p<u.length;++p)h=matchRouteBranch(u[p],d,i);return h}function flattenAndRankRoutes(n){let e=flattenRoutes(n);return rankRouteBranches(e),e}function flattenRoutes(n,e=[],t=[],i="",s=!1){let a=(l,u,h=s,d)=>{let p={relativePath:d===void 0?l.path||"":d,caseSensitive:l.caseSensitive===!0,childrenIndex:u,route:l};if(p.relativePath.startsWith("/")){if(!p.relativePath.startsWith(i)&&h)return;invariant(p.relativePath.startsWith(i),`Absolute route path "${p.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),p.relativePath=p.relativePath.slice(i.length)}let g=joinPaths([i,p.relativePath]),m=t.concat(p);l.children&&l.children.length>0&&(invariant(l.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),flattenRoutes(l.children,e,m,g,h)),!(l.path==null&&!l.index)&&e.push({path:g,score:computeScore(g,l.index),routesMeta:m.map((v,S)=>{let[E,w]=compilePath(v.relativePath,v.caseSensitive,S===m.length-1);return{...v,matcher:E,compiledParams:w}})})};return n.forEach((l,u)=>{if(l.path===""||!l.path?.includes("?"))a(l,u);else for(let h of explodeOptionalSegments(l.path))a(l,u,!0,h)}),e}function explodeOptionalSegments(n){let e=n.split("/");if(e.length===0)return[];let[t,...i]=e,s=t.endsWith("?"),a=t.replace(/\?$/,"");if(i.length===0)return s?[a,""]:[a];let l=explodeOptionalSegments(i.join("/")),u=[];return u.push(...l.map(h=>h===""?a:[a,h].join("/"))),s&&u.push(...l),u.map(h=>n.startsWith("/")&&h===""?"/":h)}function rankRouteBranches(n){n.sort((e,t)=>e.score!==t.score?t.score-e.score:compareIndexes(e.routesMeta.map(i=>i.childrenIndex),t.routesMeta.map(i=>i.childrenIndex)))}var paramRe=/^:[\w-]+$/,dynamicSegmentValue=3,indexRouteValue=2,emptySegmentValue=1,staticSegmentValue=10,splatPenalty=-2,isSplat=n=>n==="*";function computeScore(n,e){let t=n.split("/"),i=t.length;return t.some(isSplat)&&(i+=splatPenalty),e&&(i+=indexRouteValue),t.filter(s=>!isSplat(s)).reduce((s,a)=>s+(paramRe.test(a)?dynamicSegmentValue:a===""?emptySegmentValue:staticSegmentValue),i)}function compareIndexes(n,e){return n.length===e.length&&n.slice(0,-1).every((i,s)=>i===e[s])?n[n.length-1]-e[e.length-1]:0}function matchRouteBranch(n,e,t=!1){let{routesMeta:i}=n,s={},a="/",l=[];for(let u=0;u<i.length;++u){let h=i[u],d=u===i.length-1,p=a==="/"?e:e.slice(a.length)||"/",g={path:h.relativePath,caseSensitive:h.caseSensitive,end:d},m=h.matcher&&h.compiledParams?matchPathImpl(g,p,h.matcher,h.compiledParams):matchPath(g,p),v=h.route;if(!m&&d&&t&&!i[i.length-1].route.index&&(m=matchPath({path:h.relativePath,caseSensitive:h.caseSensitive,end:!1},p)),!m)return null;Object.assign(s,m.params),l.push({params:s,pathname:joinPaths([a,m.pathname]),pathnameBase:normalizePathname(joinPaths([a,m.pathnameBase])),route:v}),m.pathnameBase!=="/"&&(a=joinPaths([a,m.pathnameBase]))}return l}function matchPath(n,e){typeof n=="string"&&(n={path:n,caseSensitive:!1,end:!0});let[t,i]=compilePath(n.path,n.caseSensitive,n.end);return matchPathImpl(n,e,t,i)}function matchPathImpl(n,e,t,i){let s=e.match(t);if(!s)return null;let a=s[0],l=a.replace(/(.)\/+$/,"$1"),u=s.slice(1);return{params:i.reduce((d,{paramName:p,isOptional:g},m)=>{if(p==="*"){let S=u[m]||"";l=a.slice(0,a.length-S.length).replace(/(.)\/+$/,"$1")}const v=u[m];return g&&!v?d[p]=void 0:d[p]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:a,pathnameBase:l,pattern:n}}function compilePath(n,e=!1,t=!0){warning(n==="*"||!n.endsWith("*")||n.endsWith("/*"),`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`);let i=[],s="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,u,h,d,p)=>{if(i.push({paramName:u,isOptional:h!=null}),h){let g=p.charAt(d+l.length);return g&&g!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return n.endsWith("*")?(i.push({paramName:"*"}),s+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?s+="\\/*$":n!==""&&n!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),i]}function decodePath(n){try{return n.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return warning(!1,`The URL path "${n}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).`),n}}function stripBasename(n,e){if(e==="/")return n;if(!n.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,i=n.charAt(t);return i&&i!=="/"?null:n.slice(t)||"/"}function resolvePath(n,e="/"){let{pathname:t,search:i="",hash:s=""}=typeof n=="string"?parsePath(n):n,a;return t?(t=removeDoubleSlashes(t),t.startsWith("/")?a=resolvePathname(t.substring(1),"/"):a=resolvePathname(t,e)):a=e,{pathname:a,search:normalizeSearch(i),hash:normalizeHash(s)}}function resolvePathname(n,e){let t=removeTrailingSlash(e).split("/");return n.split("/").forEach(s=>{s===".."?t.length>1&&t.pop():s!=="."&&t.push(s)}),t.length>1?t.join("/"):"/"}function getInvalidPathError(n,e,t,i){return`Cannot include a '${n}' character in a manually specified \`to.${e}\` field [${JSON.stringify(i)}]. Please separate it out to the \`to.${t}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function getPathContributingMatches(n){return n.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function getResolveToMatches(n){let e=getPathContributingMatches(n);return e.map((t,i)=>i===e.length-1?t.pathname:t.pathnameBase)}function resolveTo(n,e,t,i=!1){let s;typeof n=="string"?s=parsePath(n):(s={...n},invariant(!s.pathname||!s.pathname.includes("?"),getInvalidPathError("?","pathname","search",s)),invariant(!s.pathname||!s.pathname.includes("#"),getInvalidPathError("#","pathname","hash",s)),invariant(!s.search||!s.search.includes("#"),getInvalidPathError("#","search","hash",s)));let a=n===""||s.pathname==="",l=a?"/":s.pathname,u;if(l==null)u=t;else{let g=e.length-1;if(!i&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),g-=1;s.pathname=m.join("/")}u=g>=0?e[g]:"/"}let h=resolvePath(s,u),d=l&&l!=="/"&&l.endsWith("/"),p=(a||l===".")&&t.endsWith("/");return!h.pathname.endsWith("/")&&(d||p)&&(h.pathname+="/"),h}var removeDoubleSlashes=n=>n.replace(/[\\/]{2,}/g,"/"),joinPaths=n=>removeDoubleSlashes(n.join("/")),removeTrailingSlash=n=>n.replace(/\/+$/,""),normalizePathname=n=>removeTrailingSlash(n).replace(/^\/*/,"/"),normalizeSearch=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,normalizeHash=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n,ErrorResponseImpl=class{constructor(n,e,t,i=!1){this.status=n,this.statusText=e||"",this.internal=i,t instanceof Error?(this.data=t.toString(),this.error=t):this.data=t}};function isRouteErrorResponse(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}function getRoutePattern(n){let e=n.map(t=>t.route.path).filter(Boolean);return joinPaths(e)||"/"}var isBrowser$1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function parseToInfo(n,e){let t=n;if(typeof t!="string"||!ABSOLUTE_URL_REGEX.test(t))return{absoluteURL:void 0,isExternal:!1,to:t};let i=t,s=!1;if(isBrowser$1)try{let a=new URL(window.location.href),l=PROTOCOL_RELATIVE_URL_REGEX.test(t)?new URL(normalizeProtocolRelativeUrl(t,a.protocol)):new URL(t),u=stripBasename(l.pathname,e);l.origin===a.origin&&u!=null?t=u+l.search+l.hash:s=!0}catch{warning(!1,`<Link to="${t}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:i,isExternal:s,to:t}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var validMutationMethodsArr=["POST","PUT","PATCH","DELETE"];new Set(validMutationMethodsArr);var validRequestMethodsArr=["GET",...validMutationMethodsArr];new Set(validRequestMethodsArr);var invalidProtocols=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function hasInvalidProtocol(n){try{return invalidProtocols.includes(new URL(n).protocol)}catch{return!1}}var DataRouterContext=reactExports.createContext(null);DataRouterContext.displayName="DataRouter";var DataRouterStateContext=reactExports.createContext(null);DataRouterStateContext.displayName="DataRouterState";var RSCRouterContext=reactExports.createContext(!1);function useIsRSCRouterContext(){return reactExports.useContext(RSCRouterContext)}var ViewTransitionContext=reactExports.createContext({isTransitioning:!1});ViewTransitionContext.displayName="ViewTransition";var FetchersContext=reactExports.createContext(new Map);FetchersContext.displayName="Fetchers";var AwaitContext=reactExports.createContext(null);AwaitContext.displayName="Await";var NavigationContext=reactExports.createContext(null);NavigationContext.displayName="Navigation";var LocationContext=reactExports.createContext(null);LocationContext.displayName="Location";var RouteContext=reactExports.createContext({outlet:null,matches:[],isDataRoute:!1});RouteContext.displayName="Route";var RouteErrorContext=reactExports.createContext(null);RouteErrorContext.displayName="RouteError";var ERROR_DIGEST_BASE="REACT_ROUTER_ERROR",ERROR_DIGEST_REDIRECT="REDIRECT",ERROR_DIGEST_ROUTE_ERROR_RESPONSE="ROUTE_ERROR_RESPONSE";function decodeRedirectErrorDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`))try{let e=JSON.parse(n.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function decodeRouteErrorResponseDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`))try{let e=JSON.parse(n.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new ErrorResponseImpl(e.status,e.statusText,e.data)}catch{}}function useHref(n,{relative:e}={}){invariant(useInRouterContext(),"useHref() may be used only in the context of a <Router> component.");let{basename:t,navigator:i}=reactExports.useContext(NavigationContext),{hash:s,pathname:a,search:l}=useResolvedPath(n,{relative:e}),u=a;return t!=="/"&&(u=a==="/"?t:joinPaths([t,a])),i.createHref({pathname:u,search:l,hash:s})}function useInRouterContext(){return reactExports.useContext(LocationContext)!=null}function useLocation(){return invariant(useInRouterContext(),"useLocation() may be used only in the context of a <Router> component."),reactExports.useContext(LocationContext).location}var navigateEffectWarning="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function useIsomorphicLayoutEffect(n){reactExports.useContext(NavigationContext).static||reactExports.useLayoutEffect(n)}function useNavigate(){let{isDataRoute:n}=reactExports.useContext(RouteContext);return n?useNavigateStable():useNavigateUnstable()}function useNavigateUnstable(){invariant(useInRouterContext(),"useNavigate() may be used only in the context of a <Router> component.");let n=reactExports.useContext(DataRouterContext),{basename:e,navigator:t}=reactExports.useContext(NavigationContext),{matches:i}=reactExports.useContext(RouteContext),{pathname:s}=useLocation(),a=JSON.stringify(getResolveToMatches(i)),l=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{l.current=!0}),reactExports.useCallback((h,d={})=>{if(warning(l.current,navigateEffectWarning),!l.current)return;if(typeof h=="number"){t.go(h);return}let p=resolveTo(h,JSON.parse(a),s,d.relative==="path");n==null&&e!=="/"&&(p.pathname=p.pathname==="/"?e:joinPaths([e,p.pathname])),(d.replace?t.replace:t.push)(p,d.state,d)},[e,t,a,s,n])}var OutletContext=reactExports.createContext(null);function useOutlet(n){let e=reactExports.useContext(RouteContext).outlet;return reactExports.useMemo(()=>e&&reactExports.createElement(OutletContext.Provider,{value:n},e),[e,n])}function useResolvedPath(n,{relative:e}={}){let{matches:t}=reactExports.useContext(RouteContext),{pathname:i}=useLocation(),s=JSON.stringify(getResolveToMatches(t));return reactExports.useMemo(()=>resolveTo(n,JSON.parse(s),i,e==="path"),[n,s,i,e])}function useRoutes(n,e){return useRoutesImpl(n)}function useRoutesImpl(n,e,t){invariant(useInRouterContext(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:i}=reactExports.useContext(NavigationContext),{matches:s}=reactExports.useContext(RouteContext),a=s[s.length-1],l=a?a.params:{},u=a?a.pathname:"/",h=a?a.pathnameBase:"/",d=a&&a.route;{let w=d&&d.path||"";warningOnce(u,!d||w.endsWith("*")||w.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${u}" (under <Route path="${w}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
305
305
|
|
|
306
|
-
Please change the parent <Route path="${w}"> to <Route path="${w==="/"?"*":`${w}/*`}">.`)}let p=useLocation(),g;g=p;let m=g.pathname||"/",v=m;if(h!=="/"){let w=h.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(w.length).join("/")}let S=t&&t.state.matches.length?t.state.matches.map(w=>Object.assign(w,{route:t.manifest[w.route.id]||w.route})):matchRoutes(n,{pathname:v});return warning(d||S!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),warning(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(S&&S.map(w=>Object.assign({},w,{params:Object.assign({},l,w.params),pathname:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?h:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathnameBase])})),s,t)}function DefaultErrorComponent(){let n=useRouteError(),e=isRouteErrorResponse(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i},a={padding:"2px 4px",backgroundColor:i},l=null;return console.error("Error handled by React Router default ErrorBoundary:",n),l=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:a},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:a},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},e),t?reactExports.createElement("pre",{style:s},t):null,l)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,e){return e.location!==n.location||e.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:e.error,location:e.location,revalidation:n.revalidation||e.revalidation}}componentDidCatch(n,e){this.props.onError?this.props.onError(n,e):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const t=decodeRouteErrorResponseDigest(n.digest);t&&(n=t)}let e=n!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:n},e):e}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:n,error:e}){let{basename:t}=reactExports.useContext(NavigationContext);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let i=decodeRedirectErrorDigest(e.digest);if(i){let s=errorRedirectHandledMap.get(e);if(s)throw s;let a=parseToInfo(i.location,t),l=a.absoluteURL||a.to;if(hasInvalidProtocol(l))throw new Error("Invalid redirect location");if(isBrowser$1&&!errorRedirectHandledMap.get(e))if(a.isExternal||i.reloadDocument)window.location.href=l;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:i.replace}));throw errorRedirectHandledMap.set(e,u),u}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${l}`})}}return n}function RenderedRoute({routeContext:n,match:e,children:t}){let i=reactExports.useContext(DataRouterContext);return i&&i.static&&i.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=e.route.id),reactExports.createElement(RouteContext.Provider,{value:n},t)}function _renderMatches(n,e=[],t){let i=t?.state;if(n==null){if(!i)return null;if(i.errors)n=i.matches;else if(e.length===0&&!i.initialized&&i.matches.length>0)n=i.matches;else return null}let s=n,a=i?.errors;if(a!=null){let p=s.findIndex(g=>g.route.id&&a?.[g.route.id]!==void 0);invariant(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(",")}`),s=s.slice(0,Math.min(s.length,p+1))}let l=!1,u=-1;if(t&&i){l=i.renderFallback;for(let p=0;p<s.length;p++){let g=s[p];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(u=p),g.route.id){let{loaderData:m,errors:v}=i,S=g.route.loader&&!m.hasOwnProperty(g.route.id)&&(!v||v[g.route.id]===void 0);if(g.route.lazy||S){t.isStatic&&(l=!0),u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}}let h=t?.onError,d=i&&h?(p,g)=>{h(p,{location:i.location,params:i.matches?.[0]?.params??{},pattern:getRoutePattern(i.matches),errorInfo:g})}:void 0;return s.reduceRight((p,g,m)=>{let v,S=!1,E=null,w=null;i&&(v=a&&g.route.id?a[g.route.id]:void 0,E=g.route.errorElement||defaultErrorElement,l&&(u<0&&m===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,w=null):u===m&&(S=!0,w=g.route.hydrateFallbackElement||null)));let A=e.concat(s.slice(0,m+1)),C=()=>{let T;return v?T=E:S?T=w:g.route.Component?T=reactExports.createElement(g.route.Component,null):g.route.element?T=g.route.element:T=p,reactExports.createElement(RenderedRoute,{match:g,routeContext:{outlet:p,matches:A,isDataRoute:i!=null},children:T})};return i&&(g.route.ErrorBoundary||g.route.errorElement||m===0)?reactExports.createElement(RenderErrorBoundary,{location:i.location,revalidation:i.revalidation,component:E,error:v,children:C(),routeContext:{outlet:null,matches:A,isDataRoute:!0},onError:d}):C()},null)}function getDataRouterConsoleError(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError(n)),e}function useDataRouterState(n){let e=reactExports.useContext(DataRouterStateContext);return invariant(e,getDataRouterConsoleError(n)),e}function useRouteContext(n){let e=reactExports.useContext(RouteContext);return invariant(e,getDataRouterConsoleError(n)),e}function useCurrentRouteId(n){let e=useRouteContext(n),t=e.matches[e.matches.length-1];return invariant(t.route.id,`${n} can only be used on routes that contain a unique "id"`),t.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let n=reactExports.useContext(RouteErrorContext),e=useDataRouterState("useRouteError"),t=useCurrentRouteId("useRouteError");return n!==void 0?n:e.errors?.[t]}function useNavigateStable(){let{router:n}=useDataRouterContext("useNavigate"),e=useCurrentRouteId("useNavigate"),t=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{t.current=!0}),reactExports.useCallback(async(s,a={})=>{warning(t.current,navigateEffectWarning),t.current&&(typeof s=="number"?await n.navigate(s):await n.navigate(s,{fromRouteId:e,...a}))},[n,e])}var alreadyWarned={};function warningOnce(n,e,t){!e&&!alreadyWarned[n]&&(alreadyWarned[n]=!0,warning(!1,t))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:n,manifest:e,future:t,state:i,isStatic:s,onError:a}){return useRoutesImpl(n,void 0,{manifest:e,state:i,isStatic:s,onError:a})}function Navigate({to:n,replace:e,state:t,relative:i}){invariant(useInRouterContext(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=reactExports.useContext(NavigationContext);warning(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=reactExports.useContext(RouteContext),{pathname:l}=useLocation(),u=useNavigate(),h=resolveTo(n,getResolveToMatches(a),l,i==="path"),d=JSON.stringify(h);return reactExports.useEffect(()=>{u(JSON.parse(d),{replace:e,state:t,relative:i})},[u,d,i,e,t]),null}function Outlet(n){return useOutlet(n.context)}function Router({basename:n="/",children:e=null,location:t,navigationType:i="POP",navigator:s,static:a=!1,useTransitions:l}){invariant(!useInRouterContext(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=n.replace(/^\/*/,"/"),h=reactExports.useMemo(()=>({basename:u,navigator:s,static:a,useTransitions:l,future:{}}),[u,s,a,l]);typeof t=="string"&&(t=parsePath(t));let{pathname:d="/",search:p="",hash:g="",state:m=null,key:v="default",mask:S}=t,E=reactExports.useMemo(()=>{let w=stripBasename(d,u);return w==null?null:{location:{pathname:w,search:p,hash:g,state:m,key:v,mask:S},navigationType:i}},[u,d,p,g,m,v,i,S]);return warning(E!=null,`<Router basename="${u}"> is not able to match the URL "${d}${p}${g}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:reactExports.createElement(NavigationContext.Provider,{value:h},reactExports.createElement(LocationContext.Provider,{children:e,value:E}))}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function isButtonElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="button"}function isFormElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="form"}function isInputElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="input"}function isModifiedEvent(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function shouldProcessLinkClick(n,e){return n.button===0&&(!e||e==="_self")&&!isModifiedEvent(n)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(n){return n!=null&&!supportedFormEncTypes.has(n)?(warning(!1,`"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):n}function getFormSubmissionInfo(n,e){let t,i,s,a,l;if(isFormElement(n)){let u=n.getAttribute("action");i=u?stripBasename(u,e):null,t=n.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("enctype"))||defaultEncType,a=new FormData(n)}else if(isButtonElement(n)||isInputElement(n)&&(n.type==="submit"||n.type==="image")){let u=n.form;if(u==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let h=n.getAttribute("formaction")||u.getAttribute("action");if(i=h?stripBasename(h,e):null,t=n.getAttribute("formmethod")||u.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("formenctype"))||getFormEncType(u.getAttribute("enctype"))||defaultEncType,a=new FormData(u,n),!isFormDataSubmitterSupported()){let{name:d,type:p,value:g}=n;if(p==="image"){let m=d?`${d}.`:"";a.append(`${m}x`,"0"),a.append(`${m}y`,"0")}else d&&a.append(d,g)}}else{if(isHtmlElement(n))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=defaultMethod,i=null,s=defaultEncType,l=n}return a&&s==="text/plain"&&(l=a,a=void 0),{action:i,method:t.toLowerCase(),encType:s,formData:a,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function singleFetchUrl(n,e,t,i){let s=typeof n=="string"?new URL(n,typeof window>"u"?"server://singlefetch/":window.location.origin):n;return t?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${i}`:s.pathname=`${s.pathname}.${i}`:s.pathname==="/"?s.pathname=`_root.${i}`:e&&stripBasename(s.pathname,e)==="/"?s.pathname=`${removeTrailingSlash(e)}/_root.${i}`:s.pathname=`${removeTrailingSlash(s.pathname)}.${i}`,s}async function loadRouteModule(n,e){if(n.id in e)return e[n.id];try{let t=await import(n.module);return e[n.id]=t,t}catch(t){return console.error(`Error loading route module \`${n.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(n){return n==null?!1:n.href==null?n.rel==="preload"&&typeof n.imageSrcSet=="string"&&typeof n.imageSizes=="string":typeof n.rel=="string"&&typeof n.href=="string"}async function getKeyedPrefetchLinks(n,e,t){let i=await Promise.all(n.map(async s=>{let a=e.routes[s.route.id];if(a){let l=await loadRouteModule(a,t);return l.links?l.links():[]}return[]}));return dedupeLinkDescriptors(i.flat(1).filter(isHtmlLinkDescriptor).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function getNewMatchesForLinks(n,e,t,i,s,a){let l=(h,d)=>t[d]?h.route.id!==t[d].route.id:!0,u=(h,d)=>t[d].pathname!==h.pathname||t[d].route.path?.endsWith("*")&&t[d].params["*"]!==h.params["*"];return a==="assets"?e.filter((h,d)=>l(h,d)||u(h,d)):a==="data"?e.filter((h,d)=>{let p=i.routes[h.route.id];if(!p||!p.hasLoader)return!1;if(l(h,d)||u(h,d))return!0;if(h.route.shouldRevalidate){let g=h.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:t[0]?.params||{},nextUrl:new URL(n,window.origin),nextParams:h.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function getModuleLinkHrefs(n,e,{includeHydrateFallback:t}={}){return dedupeHrefs(n.map(i=>{let s=e.routes[i.route.id];if(!s)return[];let a=[s.module];return s.clientActionModule&&(a=a.concat(s.clientActionModule)),s.clientLoaderModule&&(a=a.concat(s.clientLoaderModule)),t&&s.hydrateFallbackModule&&(a=a.concat(s.hydrateFallbackModule)),s.imports&&(a=a.concat(s.imports)),a}).flat(1))}function dedupeHrefs(n){return[...new Set(n)]}function sortKeys(n){let e={},t=Object.keys(n).sort();for(let i of t)e[i]=n[i];return e}function dedupeLinkDescriptors(n,e){let t=new Set;return new Set(e),n.reduce((i,s)=>{let a=JSON.stringify(sortKeys(s));return t.has(a)||(t.add(a),i.push({key:a,link:s})),i},[])}function useDataRouterContext2(){let n=reactExports.useContext(DataRouterContext);return invariant2(n,"You must render this element inside a <DataRouterContext.Provider> element"),n}function useDataRouterStateContext(){let n=reactExports.useContext(DataRouterStateContext);return invariant2(n,"You must render this element inside a <DataRouterStateContext.Provider> element"),n}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let n=reactExports.useContext(FrameworkContext);return invariant2(n,"You must render this element inside a <HydratedRouter> element"),n}function usePrefetchBehavior(n,e){let t=reactExports.useContext(FrameworkContext),[i,s]=reactExports.useState(!1),[a,l]=reactExports.useState(!1),{onFocus:u,onBlur:h,onMouseEnter:d,onMouseLeave:p,onTouchStart:g}=e,m=reactExports.useRef(null);reactExports.useEffect(()=>{if(n==="render"&&l(!0),n==="viewport"){let E=A=>{A.forEach(C=>{l(C.isIntersecting)})},w=new IntersectionObserver(E,{threshold:.5});return m.current&&w.observe(m.current),()=>{w.disconnect()}}},[n]),reactExports.useEffect(()=>{if(i){let E=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(E)}}},[i]);let v=()=>{s(!0)},S=()=>{s(!1),l(!1)};return t?n!=="intent"?[a,m,{}]:[a,m,{onFocus:composeEventHandlers(u,v),onBlur:composeEventHandlers(h,S),onMouseEnter:composeEventHandlers(d,v),onMouseLeave:composeEventHandlers(p,S),onTouchStart:composeEventHandlers(g,v)}]:[!1,m,{}]}function composeEventHandlers(n,e){return t=>{n&&n(t),t.defaultPrevented||e(t)}}function PrefetchPageLinks({page:n,...e}){let t=useIsRSCRouterContext(),{nonce:i}=useFrameworkContext(),{router:s}=useDataRouterContext2(),a=reactExports.useMemo(()=>matchRoutes(s.routes,n,s.basename),[s.routes,n,s.basename]);return a?(e.nonce==null&&i&&(e={...e,nonce:i}),t?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:n,matches:a,...e}):reactExports.createElement(PrefetchPageLinksImpl,{page:n,matches:a,...e})):null}function useKeyedPrefetchLinks(n){let{manifest:e,routeModules:t}=useFrameworkContext(),[i,s]=reactExports.useState([]);return reactExports.useEffect(()=>{let a=!1;return getKeyedPrefetchLinks(n,e,t).then(l=>{a||s(l)}),()=>{a=!0}},[n,e,t]),i}function RSCPrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s}=useFrameworkContext(),{basename:a}=useDataRouterContext2(),l=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let u=singleFetchUrl(n,a,s.v8_trailingSlashAwareDataRequests,"rsc"),h=!1,d=[];for(let p of e)typeof p.route.shouldRevalidate=="function"?h=!0:d.push(p.route.id);return h&&d.length>0&&u.searchParams.set("_routes",d.join(",")),[u.pathname+u.search]},[a,s.v8_trailingSlashAwareDataRequests,n,i,e]);return reactExports.createElement(reactExports.Fragment,null,l.map(u=>reactExports.createElement("link",{key:u,rel:"prefetch",as:"fetch",href:u,...t})))}function PrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s,manifest:a,routeModules:l}=useFrameworkContext(),{basename:u}=useDataRouterContext2(),{loaderData:h,matches:d}=useDataRouterStateContext(),p=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"data"),[n,e,d,a,i]),g=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"assets"),[n,e,d,a,i]),m=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let E=new Set,w=!1;if(e.forEach(C=>{let T=a.routes[C.route.id];!T||!T.hasLoader||(!p.some(F=>F.route.id===C.route.id)&&C.route.id in h&&l[C.route.id]?.shouldRevalidate||T.hasClientLoader?w=!0:E.add(C.route.id))}),E.size===0)return[];let A=singleFetchUrl(n,u,s.v8_trailingSlashAwareDataRequests,"data");return w&&E.size>0&&A.searchParams.set("_routes",e.filter(C=>E.has(C.route.id)).map(C=>C.route.id).join(",")),[A.pathname+A.search]},[u,s.v8_trailingSlashAwareDataRequests,h,i,a,p,e,n,l]),v=reactExports.useMemo(()=>getModuleLinkHrefs(g,a),[g,a]),S=useKeyedPrefetchLinks(g);return reactExports.createElement(reactExports.Fragment,null,m.map(E=>reactExports.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...t})),v.map(E=>reactExports.createElement("link",{key:E,rel:"modulepreload",href:E,...t})),S.map(({key:E,link:w})=>reactExports.createElement("link",{key:E,nonce:t.nonce,...w,crossOrigin:w.crossOrigin??t.crossOrigin})))}function mergeRefs(...n){return e=>{n.forEach(t=>{typeof t=="function"?t(e):t!=null&&(t.current=e)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.2")}catch(n){}function BrowserRouter({basename:n,children:e,useTransitions:t,window:i}){let s=reactExports.useRef();s.current==null&&(s.current=createBrowserHistory({window:i,v5Compat:!0}));let a=s.current,[l,u]=reactExports.useState({action:a.action,location:a.location}),h=reactExports.useCallback(d=>{t===!1?u(d):reactExports.startTransition(()=>u(d))},[t]);return reactExports.useLayoutEffect(()=>a.listen(h),[a,h]),reactExports.createElement(Router,{basename:n,children:e,location:l.location,navigationType:l.action,navigator:a,useTransitions:t})}var Link=reactExports.forwardRef(function n({onClick:e,discover:t="render",prefetch:i="none",relative:s,reloadDocument:a,replace:l,mask:u,state:h,target:d,to:p,preventScrollReset:g,viewTransition:m,defaultShouldRevalidate:v,...S},E){let{basename:w,navigator:A,useTransitions:C}=reactExports.useContext(NavigationContext),T=typeof p=="string"&&ABSOLUTE_URL_REGEX.test(p),F=parseToInfo(p,w);p=F.to;let P=useHref(p,{relative:s}),M=useLocation(),$=null;if(u){let ke=resolveTo(u,[],M.mask?M.mask.pathname:"/",!0);w!=="/"&&(ke.pathname=ke.pathname==="/"?w:joinPaths([w,ke.pathname])),$=A.createHref(ke)}let[G,fe,B]=usePrefetchBehavior(i,S),ee=useLinkClickHandler(p,{replace:l,mask:u,state:h,target:d,preventScrollReset:g,relative:s,viewTransition:m,defaultShouldRevalidate:v,useTransitions:C});function Se(ke){e&&e(ke),ke.defaultPrevented||ee(ke)}let re=!(F.isExternal||a),Ae=reactExports.createElement("a",{...S,...B,href:(re?$:void 0)||F.absoluteURL||P,onClick:re?Se:e,ref:mergeRefs(E,fe),target:d,"data-discover":!T&&t==="render"?"true":void 0});return G&&!T?reactExports.createElement(reactExports.Fragment,null,Ae,reactExports.createElement(PrefetchPageLinks,{page:P})):Ae});Link.displayName="Link";var NavLink=reactExports.forwardRef(function n({"aria-current":e="page",caseSensitive:t=!1,className:i="",end:s=!1,style:a,to:l,viewTransition:u,children:h,...d},p){let g=useResolvedPath(l,{relative:d.relative}),m=useLocation(),v=reactExports.useContext(DataRouterStateContext),{navigator:S,basename:E}=reactExports.useContext(NavigationContext),w=v!=null&&useViewTransitionState(g)&&u===!0,A=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,C=m.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;t||(C=C.toLowerCase(),T=T?T.toLowerCase():null,A=A.toLowerCase()),T&&E&&(T=stripBasename(T,E)||T);const F=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let P=C===A||!s&&C.startsWith(A)&&C.charAt(F)==="/",M=T!=null&&(T===A||!s&&T.startsWith(A)&&T.charAt(A.length)==="/"),$={isActive:P,isPending:M,isTransitioning:w},G=P?e:void 0,fe;typeof i=="function"?fe=i($):fe=[i,P?"active":null,M?"pending":null,w?"transitioning":null].filter(Boolean).join(" ");let B=typeof a=="function"?a($):a;return reactExports.createElement(Link,{...d,"aria-current":G,className:fe,ref:p,style:B,to:l,viewTransition:u},typeof h=="function"?h($):h)});NavLink.displayName="NavLink";var Form=reactExports.forwardRef(({discover:n="render",fetcherKey:e,navigate:t,reloadDocument:i,replace:s,state:a,method:l=defaultMethod,action:u,onSubmit:h,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m,...v},S)=>{let{useTransitions:E}=reactExports.useContext(NavigationContext),w=useSubmit(),A=useFormAction(u,{relative:d}),C=l.toLowerCase()==="get"?"get":"post",T=typeof u=="string"&&ABSOLUTE_URL_REGEX.test(u),F=P=>{if(h&&h(P),P.defaultPrevented)return;P.preventDefault();let M=P.nativeEvent.submitter,$=M?.getAttribute("formmethod")||l,G=()=>w(M||P.currentTarget,{fetcherKey:e,method:$,navigate:t,replace:s,state:a,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m});E&&t!==!1?reactExports.startTransition(()=>G()):G()};return reactExports.createElement("form",{ref:S,method:C,action:A,onSubmit:i?h:F,...v,"data-discover":!T&&n==="render"?"true":void 0})});Form.displayName="Form";function getDataRouterConsoleError2(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError2(n)),e}function useLinkClickHandler(n,{target:e,replace:t,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h,useTransitions:d}={}){let p=useNavigate(),g=useLocation(),m=useResolvedPath(n,{relative:l});return reactExports.useCallback(v=>{if(shouldProcessLinkClick(v,e)){v.preventDefault();let S=t!==void 0?t:createPath(g)===createPath(m),E=()=>p(n,{replace:S,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h});d?reactExports.startTransition(()=>E()):E()}},[g,p,m,t,i,s,e,n,a,l,u,h,d])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:n}=useDataRouterContext3("useSubmit"),{basename:e}=reactExports.useContext(NavigationContext),t=useRouteId(),i=n.fetch,s=n.navigate;return reactExports.useCallback(async(a,l={})=>{let{action:u,method:h,encType:d,formData:p,body:g}=getFormSubmissionInfo(a,e);if(l.navigate===!1){let m=l.fetcherKey||getUniqueFetcherId();await i(m,t,l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,flushSync:l.flushSync})}else await s(l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,replace:l.replace,state:l.state,fromRouteId:t,flushSync:l.flushSync,viewTransition:l.viewTransition})},[i,s,e,t])}function useFormAction(n,{relative:e}={}){let{basename:t}=reactExports.useContext(NavigationContext),i=reactExports.useContext(RouteContext);invariant(i,"useFormAction must be used inside a RouteContext");let[s]=i.matches.slice(-1),a={...useResolvedPath(n||".",{relative:e})},l=useLocation();if(n==null){a.search=l.search;let u=new URLSearchParams(a.search),h=u.getAll("index");if(h.some(p=>p==="")){u.delete("index"),h.filter(g=>g).forEach(g=>u.append("index",g));let p=u.toString();a.search=p?`?${p}`:""}}return(!n||n===".")&&s.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(a.pathname=a.pathname==="/"?t:joinPaths([t,a.pathname])),createPath(a)}function useViewTransitionState(n,{relative:e}={}){let t=reactExports.useContext(ViewTransitionContext);invariant(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=useDataRouterContext3("useViewTransitionState"),s=useResolvedPath(n,{relative:e});if(!t.isTransitioning)return!1;let a=stripBasename(t.currentLocation.pathname,i)||t.currentLocation.pathname,l=stripBasename(t.nextLocation.pathname,i)||t.nextLocation.pathname;return matchPath(s.pathname,l)!=null||matchPath(s.pathname,a)!=null}function WebAccountFailureView({title:n="操作未完成",description:e,primaryLabel:t="重试",onPrimary:i,secondaryLabel:s="返回",onSecondary:a,pending:l=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:i,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:t}),a?jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:a,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring",children:s}):null]})]})}let automaticLoginBlocked=!1,logoutState={status:"idle"},operation,inFlight;const logoutListeners=new Set,isXpodAutomaticLoginBlocked=()=>automaticLoginBlocked,getXpodProductLogoutState=()=>logoutState;function subscribeXpodProductLogout(n){return logoutListeners.add(n),()=>{logoutListeners.delete(n)}}function publish(n){logoutState=n,logoutListeners.forEach(e=>e())}function logoutXpodProduct(n,e,t={}){return inFlight||(automaticLoginBlocked=!0,operation={account:n,runtime:e,solidCleared:!1,onComplete:t.onComplete},retryXpodProductLogout())}function retryXpodProductLogout(){if(inFlight)return inFlight;if(!operation)return Promise.resolve();const n=operation;return inFlight=(async()=>{let t=n.solidCleared?"account":"solid";publish({status:"running",step:t});try{if(n.solidCleared||(await n.runtime?.logout(),n.solidCleared=!0),t="account",publish({status:"running",step:t}),await n.account.logout(),n.account.isAnonymous&&!n.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(i){throw publish({status:"error",step:t}),i}operation=void 0,publish({status:"idle"}),n.onComplete?.()})().finally(()=>{inFlight=void 0}),inFlight}const LogoutRecoveryOwner=reactExports.createContext(!1);function XpodProductLogoutBoundary({children:n}){const e=reactExports.useContext(LogoutRecoveryOwner),t=reactExports.useSyncExternalStore(subscribeXpodProductLogout,getXpodProductLogoutState,getXpodProductLogoutState);if(e)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const i=t.status!=="idle";return jsxRuntimeExports.jsxs(LogoutRecoveryOwner.Provider,{value:!0,children:[i&&jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"退出 Xpod",children:t.status==="running"?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在退出…"}):jsxRuntimeExports.jsx(WebAccountFailureView,{title:"退出未完成",description:t.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{retryXpodProductLogout().catch(()=>{})}})}),jsxRuntimeExports.jsx("div",{className:i?"hidden":"contents","aria-hidden":i||void 0,inert:i||void 0,children:n})]})}const AuthContext=reactExports.createContext(null);function useAuth(){const n=reactExports.useContext(AuthContext);if(!n)throw new Error("useAuth must be used within AuthProvider");return n}function useXpodProfileCardIdentity({accountIdentity:n,runtime:e}){const t=e?.state.status,i=t==="authenticated"&&e?e.webId??e.state.webId:n?.webId,s=t==="authenticated"&&i?void 0:n,a=s?.displayName,l=s?.username,u=s?.id,h=s?.webId,d=e?.fetch,p=reactExports.useMemo(()=>accountProfileFallback({displayName:a,username:l,id:u},i),[a,u,l,h,i]),g=`${i??""}\0${p.displayName}\0${p.username??""}`,[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1);reactExports.useEffect(()=>{const A=d;if(t!=="authenticated"||!A||!i)return;let C=!1,T;async function F(P,M){E(!0);try{const $=await resolveSolidProfileIdentityFromWebIdDocument({info:{webId:M},fetch:P});if(C||!$)return;const G=normalizedHttpUrl($.profile?.avatar);let fe=G;if(G&&(fe=await resolveAuthenticatedAvatarUrl(P,G),T=fe?.startsWith("blob:")?fe:void 0),C){T&&URL.revokeObjectURL(T);return}v({key:g,value:{displayName:$.displayName??$.username??p.displayName,username:$.username||p.username,avatarUrl:fe??p.avatarUrl,avatarSourceUrl:G,note:$.profile?.note||p.note,region:$.profile?.region||p.region,webId:$.webId||p.webId,loading:!1,source:"webid-profile"}})}catch{C||v(void 0)}finally{C||E(!1)}}return F(A,i),()=>{C=!0,T&&URL.revokeObjectURL(T)}},[d,p,g,t,i]);const w=t==="authenticated"?S:!1;return t==="authenticated"&&m?.key===g?{...m.value,loading:w}:{...p,loading:w}}function accountProfileFallback(n,e){const t=n?.username||usernameFromWebId$1(e)||n?.id;return{displayName:n?.displayName||t||n?.id||"Xpod account",username:t,webId:e,loading:!1,source:"account"}}async function resolveAuthenticatedAvatarUrl(n,e){try{const t=await n(e);if(!t.ok)return e;const i=await t.blob();return URL.createObjectURL(i)}catch{return e}}function normalizedHttpUrl(n){if(n)try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function usernameFromWebId$1(n){if(n)try{const e=new URL(n);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const useXpodSolidRuntime=useXpodSolidRuntimeContext,XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),i=validatedWebId(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),a=validatedWebId(e.webId),l=validatedWebId(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!a||!l||!u||t!==i||a!==l||t!==a||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,a=normalizedEmail(i.email),l=validatedWebId(t.webId),u=validatedWebId(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!a||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...a?{email:a}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(n){return typeof n=="string"&&!hasInvalidWebIdWhitespace(n)&&normalizedUrl(n)?n:void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const a=normalizedUrl(s);return a&&new URL(a).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,a=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??a?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||a&&!rememberedXpodLoginMatchesActive(a,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??a?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??a?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,a,e.currentPod,t,s]),null}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTHORITY_STORAGE_KEY="xpod.cssAccountAuthority",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function bindAccountSessionAuthority(n){if(!isBrowser())return!1;const e=normalizeAccountAuthority(n),t=window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY),i=t!==null?t!==e:new URL(e).origin!==window.location.origin;return window.localStorage.setItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY,e),i&&clearAccountSessionToken(),i}function normalizeAccountAuthority(n){const e=new URL(n,window.location.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/.account/"||e.search||e.hash)throw new Error("Invalid Account authority");return e.href}function storeAccountSessionToken(n){!n||readCssAccountCookie()===n||writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"},e){if(e)try{if(window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY)!==normalizeAccountAuthority(e))return{...n}}catch{return{...n}}return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:scopeAccountUrl(t)}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const d=new URL(t,window.location.origin),p=new URL(n.trim(),d);if(p.origin===d.origin&&d.pathname.startsWith("/.account/")&&p.pathname.startsWith("/.account/")&&["http:","https:"].includes(p.protocol)&&!p.username&&!p.password)return scopeAccountUrl(p)}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const d=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(d)return scopeAccountUrl(d)}const a={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,a.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...a,fetch:async()=>l.clone()}):void 0;u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin);const h=u?resolveSolidLocalRouteUrl(s,[u]):void 0;return h?scopeAccountUrl(h):void 0}const LOCAL_ACCOUNT_INDEX$1="/.account/";function isProvisionStatusResponse(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX$1;if(!isLoopbackHostname$1(window.location.hostname)){const i=window.__XPOD__?.idpIndex;if(i!==void 0){try{const s=new URL(i,window.location.origin);if(typeof i=="string"&&i.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===LOCAL_ACCOUNT_INDEX$1&&!s.username&&!s.password&&!s.search&&!s.hash)return unregisterLocalProvisionResolver(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(e.status===404)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(!e.ok)throw new Error(`Local provisioning status request failed (${e.status})`);let t;try{t=await e.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!isProvisionStatusResponse(t)||typeof t.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(t.managed===!1)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(typeof t.oidcIssuer=="string")try{const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return installLocalProvisionResolver(n),typeof t.provisionCode=="string"&&setStoredProvisionCode(t.provisionCode),new URL(LOCAL_ACCOUNT_INDEX$1,i).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function installLocalProvisionResolver(n){const e=new URL("/provision/status",window.location.origin);registerLocalProvisionResolver(async()=>{const t=await n(e,{credentials:"include",headers:{accept:"application/json"}}),i=t.ok?await t.json().catch(()=>{}):void 0;if(i?.managed!==!0||i?.registered!==!0||typeof i?.provisionCode!="string")throw new Error(CLOUD_PROVISIONING_UNAVAILABLE);return i.provisionCode})}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[a,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,m]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),w=reactExports.useRef(void 0),A=reactExports.useRef(null),C=reactExports.useRef(void 0),T=reactExports.useRef(0),F=reactExports.useRef(0),P=reactExports.useRef(!1),M=reactExports.useCallback(()=>{const te=A.current?.account;return te?.logout?JSON.stringify([w.current,te.id,te.logout,te.clientCredentials]):void 0},[]),$=reactExports.useCallback(()=>{T.current+=1,P.current=!0},[]),G=reactExports.useCallback((te,Te)=>{const je=M(),He=C.current;A.current=te,C.current=Te,(je!==M()||He!==Te)&&$(),P.current=!M()},[M,$]),fe=reactExports.useCallback(()=>{const te=M(),Te=T.current,je=getAccountSessionToken();let He=!!te&&je===C.current&&!P.current&&F.current===0;return()=>{if(!He||!S.current||P.current||F.current>0||Te!==T.current||te!==M()||je!==getAccountSessionToken())throw He=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[M]),B=g.status==="authenticated",ee=a||g.status==="submitting",Se=reactExports.useRef(!1),re=reactExports.useCallback(te=>{(bindAccountSessionAuthority(te)||w.current&&w.current!==te)&&(E.current+=1,v.current+=1,Se.current=!1,G(null),s(null),p(!1),m({status:"initializing"})),w.current=te,t(te)},[G]),Ae=reactExports.useCallback(async()=>{l(!0),h(null),m(te=>te.status==="authenticated"?te:{status:"initializing"});try{const te=await resolveXpodAccountIndex();return S.current?(re(te),te):void 0}catch{if(!S.current)return;G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1);return}},[re,G]);reactExports.useEffect(()=>{let te=!0;return resolveXpodAccountIndex().then(Te=>{te&&S.current&&re(Te)}).catch(()=>{!te||!S.current||(G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1))}),()=>{te=!1}},[re,G]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,$(),E.current+=1}),[$]);const ke=reactExports.useCallback(te=>S.current&&te===E.current,[]),he=reactExports.useCallback(async()=>{const te=new AbortController,Te=setTimeout(()=>te.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{const je=w.current;if(!je)return!1;const He=await fetch(scopeAccountUrl(new URL("oidc/consent/",je)),{headers:storedAccountTokenHeaders(void 0,je),credentials:"include",signal:te.signal});return He.ok?!!(await He.json()).client:!1}catch{return!1}finally{clearTimeout(Te)}},[]),Oe=reactExports.useCallback(async({exposeTransientError:te,generation:Te,confirmUnauthenticated:je})=>{const He=w.current;if(!He)return"stale";const We=getAccountSessionToken(),me=()=>We===getAccountSessionToken()?!0:($(),!1);try{const ge=await fetch(scopeAccountUrl(He),{headers:storedAccountTokenHeaders(void 0,He),credentials:"include"});if(!ke(Te))return"stale";if(!me())return"transient-error";if(ge.ok){const Be=await ge.json();if(!ke(Te))return"stale";if(!me())return"transient-error";if(!Be?.controls||typeof Be.controls!="object"||Array.isArray(Be.controls))throw new Error("Invalid CSS Account controls response");const ie=Be.controls,q=++v.current;p(!1),G(ie,We),s(ie),h(null);const N=accountStateForControls(ie);return Se.current=N.status==="anonymous",m(N),ie.account?.logout&&isAccountSpaPath()&&he().then(k=>{ke(Te)&&q===v.current&&p(k)}),"ok"}else{if(ge.status===401||ge.status===403)return je?(v.current+=1,clearAccountSessionToken(),Se.current=!0,p(!1),G({}),s({}),m({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(ge.status))return h(null),m(ie=>ie.status==="authenticated"?ie:transientAccountState(te)),"transient-error";$();const Be=`Failed to load account controls (Status: ${ge.status})`;return h(Be),m({status:"error",mode:"login",message:Be}),"terminal-error"}}catch{return ke(Te)?(v.current+=1,p(!1),h(null),m(ge=>ge.status==="authenticated"?ge:transientAccountState(te)),"transient-error"):"stale"}},[G,he,ke,$]),ce=reactExports.useCallback(async()=>{const te=++E.current;for(let Te=0;Te<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;Te+=1){const je=Te===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,He=await Oe({exposeTransientError:je,generation:te});if(He==="unauthenticated")return!ke(te)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!ke(te))?"stale":Oe({exposeTransientError:!0,generation:te,confirmUnauthenticated:!0});if(He!=="transient-error")return He;if(!ke(te)||!je&&(m(We=>We.status==="authenticated"?We:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[Te]),!ke(te)))return"stale"}return"transient-error"},[Oe,ke]);reactExports.useEffect(()=>{if(!e)return;let te=!0;return(async()=>(await ce(),te&&S.current&&l(!1)))(),()=>{te=!1}},[ce,e]);const Ue=reactExports.useCallback(async()=>{const te=await Ae();if(te&&te===e){const Te=await ce();if(S.current&&l(!1),Te==="ok")return accountStateForControls(A.current)}return{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}},[ce,e,Ae]),O=reactExports.useCallback(async()=>{await Ue()},[Ue]),W=reactExports.useCallback(async()=>{F.current+=1;try{$(),E.current+=1,v.current+=1,A.current?.account?.logout||(Se.current=!1,(w.current??await Ae())&&await ce());const te=w.current,Te=A.current?.account?.logout,je=await resolveHostedAccountControlUrl(Te,fetch,te);let He=!je&&(!!Te||!Se.current);if(je)try{const We=await fetch(scopeAccountUrl(je),{method:"POST",headers:storedAccountTokenHeaders(void 0,te),credentials:"include"});He=!We.ok&&We.status!==401&&We.status!==403}catch{He=!0}if(He){m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}E.current+=1,v.current+=1,Se.current=!0,l(!1),clearAccountSessionToken(),p(!1),G({}),s({}),h(null),m({status:"anonymous",mode:"login"})}finally{F.current-=1}},[G,ce,Ae,$]),de=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:a,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:B,isAnonymous:()=>Se.current,bindAccountCapability:fe,authenticating:ee,hasOidcPending:d,refetchControls:Ue,retry:O,logout:W,accountState:g,identity:de},children:n})}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const a=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:a,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XpodServiceAvailability({children:n}){const[e,t]=reactExports.useState(!1),i=reactExports.useRef(()=>{}),s=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!e)return;const a=document.activeElement;return s.current?.focus(),()=>{a instanceof HTMLElement&&a.isConnected&&a.focus()}},[e]),reactExports.useEffect(()=>{let a=!1,l,u,h=0;async function d(){if(a||l)return;clearTimeout(u);const g=new AbortController;l=g;const m=setTimeout(()=>g.abort(),5e3);let v=!0;try{const S=await fetch("/service/status",{cache:"no-store",signal:g.signal});if(v=S.status<500,S.ok){const E=await S.json().catch(()=>null);Array.isArray(E)&&(v=!E.some(w=>w&&["css","api"].includes(w.name)&&typeof w.status=="string"&&w.status!=="running")),g.signal.aborted&&(v=!1)}else await S.body?.cancel()}catch{v=!1}finally{clearTimeout(m),l=void 0}a||(h=v?0:h+1,t(!v),u=setTimeout(()=>{document.visibilityState!=="hidden"&&d()},v?1e4:Math.min(2e3*2**Math.min(h-1,4),3e4)))}const p=()=>{document.visibilityState!=="hidden"&&d()};return i.current=()=>{d()},window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),d(),()=>{a=!0,clearTimeout(u),l?.abort(),i.current=()=>{},window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{style:{display:"contents"},inert:e||void 0,children:n}),e&&jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("section",{role:"alertdialog","aria-modal":"true","aria-labelledby":"xpod-connection-title","aria-describedby":"xpod-connection-description",className:"w-full max-w-sm rounded-2xl border bg-background p-6 shadow-lg",children:[jsxRuntimeExports.jsx("h2",{id:"xpod-connection-title",className:"text-lg font-semibold",children:"Xpod 连接中断"}),jsxRuntimeExports.jsx("p",{id:"xpod-connection-description",className:"mt-3 text-sm text-muted-foreground",children:"暂时无法连接 Xpod,正在自动重连。登录状态和当前页面已保留,恢复后即可继续。"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"刚才未完成的操作不会自动重试,请在连接恢复后确认结果。"}),jsxRuntimeExports.jsx("button",{ref:s,type:"button",onKeyDown:a=>{a.key==="Tab"&&a.preventDefault()},onClick:()=>i.current(),className:"mt-5 w-full rounded-lg bg-primary px-4 py-2 text-primary-foreground",children:"立即重试"})]})})]})}function XpodDesktopNavigationBridge(){const n=useNavigate();return reactExports.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const t=new URL(e,window.location.origin);t.origin===window.location.origin&&n(`${t.pathname}${t.search}${t.hash}`)}),[n]),null}const client_id="https://id.undefineds.co/app/xpod-desktop-client.json",desktopClient={client_id};function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[a,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),[v,S]=reactExports.useState(),[E,w]=reactExports.useState(0),[A,C]=reactExports.useState(),T=reactExports.useRef(a),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),M=reactExports.useCallback(async(Ae,ke)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):ke===void 0?t.session.fetch(Ae):t.session.fetch(Ae,ke),[t.session]),$=reactExports.useMemo(()=>a.status==="authenticated"?t.session.createAuthenticatedFetch(a.webId):void 0,[t.session,a]),G=reactExports.useCallback(async(Ae,ke)=>{if(!$||F.current)throw REJECTED_SESSION_FETCH_ERROR;return ke===void 0?$(Ae):$(Ae,ke)},[$]),fe=reactExports.useCallback(()=>{if(P.current)return P.current;const Ae=(async()=>{try{await t.session.logout();const ke=t.session.getSnapshot();(ke.status!=="authenticated"||isCurrentXpodSessionSnapshot(ke,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const ke={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=ke,l(ke),h(void 0),p(void 0),m(void 0),S(void 0),C(void 0)}})().finally(()=>{P.current===Ae&&(P.current=void 0)});return P.current=Ae,Ae},[t,i.issuer,i.selectedStorage]),B=reactExports.useMemo(()=>({...t.session,fetch:M,getSnapshot:()=>T.current}),[M,t.session]);reactExports.useEffect(()=>{const Ae=he=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(he,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,fe();return}he.status==="authenticated"&&(F.current=!1);const ce=T.current;T.current=he,l(he),h(Oe),he.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),he.status!=="expired"&&m(void 0),S(void 0),C(void 0),t.pod.clear()):ce!==he&&(p(void 0),m(void 0),S(void 0),C(void 0),t.pod.clear(ce.status==="authenticated"?{webId:ce.webId}:void 0))},ke=t.session.subscribe(Ae);return Ae(t.session.getSnapshot()),ke},[fe,t,i]),reactExports.useEffect(()=>{F.current&&fe()},[fe]),reactExports.useEffect(()=>{if(a.status!=="authenticated")return;let Ae=!1;const ke=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:a.webId}),he={webId:a.webId,...ke?{podUrl:ke.storageUrl}:{},fetch:G};return(async()=>{try{const Oe=await t.pod.open(he),ce=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(Ae)return;if(t.setLocalPodRoute?.(ce),!Ae){if(ke&&(Oe.webId!==ke.webId||!sameUrl$2(Oe.podUrl,ke.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),m(void 0),S({webId:a.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),m(ke??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){Ae||S({webId:a.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{Ae=!0}},[G,E,t,i.selectedStorage,a]);const ee=reactExports.useCallback(()=>{S(void 0),w(Ae=>Ae+1)},[]),Se=a.status==="authenticated"?a.webId:void 0;reactExports.useEffect(()=>{if(!Se)return;let Ae=!1;return discoverAiClientConfigurationCapability(G).then(ke=>{!Ae&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===Se&&C(ke)}),()=>{Ae=!0}},[G,Se,t]);const re=reactExports.useMemo(()=>{const Ae=u??t.getIssuer(),ke=a.status==="authenticated"&&v?.webId===a.webId?v:void 0,he=snapshotToState(a,d,Ae);return{session:B,pod:t.pod,fetch:G,state:he.status==="error"?{...he,error:safeAuthError(he.error)}:he,webId:he.webId,podUrl:he.podUrl,issuer:he.issuer,currentPod:d,selectedStorage:g,...ke?{podError:ke}:{},retryPodOpen:ee,aiClientConfiguration:A,resolveLocalUrl:Oe=>t.resolveLocalUrl(Oe),login:async Oe=>{const ce=normalizeXpodLoginTransaction(Oe),Ue=await resolveXpodLoginContext(ce.route.identityProvider.url,fetch),O=Ue.oidcIssuer;if(!O)throw new TypeError("Xpod login route has no valid issuer");const W=new URL("/auth/callback",window.location.origin),de=globalThis.xpodDesktop?desktopClient.client_id:void 0;try{await t.session.login({...de?{clientId:de}:{},oidcIssuer:O,redirectUrl:W.toString(),handleRedirect:te=>{t.setIssuer(O),h(O);const Te=new URL(te);ce.prompt?Te.searchParams.set("prompt",ce.prompt):de&&Te.searchParams.get("prompt")==="consent"&&Te.searchParams.delete("prompt"),window.location.assign(Ue.provisionCode?withXpodProvisionScope(Te.href,Ue.provisionCode):Te.href)}}),t.setIssuer(O),h(O)}catch(te){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",te,te instanceof Error?te.cause:void 0),te}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),m(void 0),C(void 0)}}},[A,G,d,B,u,v,ee,t,i,g,a]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:B,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:re,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),a=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(a)},[a]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:a,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,a]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function DesktopLoginReturnAction(){const[n,e]=reactExports.useState(!1),[t,i]=reactExports.useState(!1),s=reactExports.useRef(!1);if(!window.xpodDesktop?.cancelLogin)return null;const a=async()=>{const l=window.xpodDesktop;if(!(s.current||!l?.cancelLogin)){s.current=!0,e(!0),i(!1);try{await l.cancelLogin()}catch{i(!0)}finally{s.current=!1,e(!1)}}};return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[t&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"返回应用未完成,请重试。"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:"w-full",disabled:n,"aria-busy":n,onClick:()=>{a()},children:n?"正在返回…":"返回应用"})]})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodAccountPageCopy={forgotPassword:"忘记密码?"},xpodRegistrationCopy={usernameRequired:"请填写 Pod 名称",usernameLength:"Pod 名称需为 3-63 个字符",usernameCharset:"Pod 名称只能包含小写字母、数字和连字符",usernameHyphen:"Pod 名称不能以连字符开头或结尾",emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。",podNameTaken:"Pod 名称已被占用,请换一个。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const a=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(a||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:a}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(M,$)=>{const G=await fetch(typeof M=="string"||M instanceof URL?scopeAccountUrl(M):M,$);if(!G.ok)throw new PasswordLoginStatusError(G.status);return G}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await a();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},w=C=>{u(C),h&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:w,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:h?{form:h}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),a=e??s.accountState,l=t??s.retry;return a.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):a.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):a.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):a.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:a.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[a,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),w=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),M=P.displayName,$=initialsFor(P.displayName),G=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),fe=accountHandle(P.username,i?void 0:F?.id,G),B=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,Se=e?.currentPod,re=reactExports.useMemo(()=>B?podNameFromUrl(B):void 0,[B]),Ae=e?.state.status==="authenticated"&&!!(G&&B&&ee&&Se)&&ee?.webId===G&&sameUrl$1(ee?.storageUrl??"",B??"")&&Se?.webId===G&&sameUrl$1(Se?.podUrl??"",B??""),ke=s,he=a&&ke,Oe=reactExports.useCallback(W=>{l(W),W||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!he)return;const W=()=>{const de=S.current;de&&m(accountCardPosition(de.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return W(),window.addEventListener("resize",W),window.addEventListener("scroll",W,!0),window.visualViewport?.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),window.visualViewport?.removeEventListener("resize",W)}},[he]),reactExports.useEffect(()=>{if(!ke){clearAccountCardRequest();return}if(!he)return;const W=te=>{const Te=te.target;Te instanceof Node&&(v.current?.contains(Te)||S.current?.contains(Te)||Oe(!1))},de=te=>{te.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",W),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointerdown",W),document.removeEventListener("keydown",de)}},[ke,he,Oe]),reactExports.useEffect(()=>{!he||!g||v.current?.focus({preventScroll:!0})},[he,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const ce=async()=>{h("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{h(void 0)}},Ue=async()=>{h("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const W=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);W.searchParams.set("xpod-login","switch"),window.location.assign(W)}}),Oe(!1)}catch{}finally{h(void 0)}},O=async()=>{const W=P.webId??fe;try{await navigator.clipboard.writeText(W),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return ke?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${M}`:"Open account menu","aria-expanded":he,"aria-controls":he?w:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ae?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!he),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?M:"Not signed in"})]}),he&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:w,role:"region",tabIndex:-1,"aria-label":s?M:"Xpod account","data-avatar-card":"true","data-selected-pod-url":B,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:$})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:M}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:fe}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{O()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ae?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ae?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(re)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(B)]})]}),Ae?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{Ue()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{ce()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const a=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(a,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DlLYWOhw.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DlLYWOhw.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-DlLYWOhw.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-B3qBfANA.js"),__vite__mapDeps([8,9,10,2,11,3,12,13,6]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-Dkv63Uwk.js"),__vite__mapDeps([14,2,10,9,11]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-DQkEVsFs.js"),__vite__mapDeps([15,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-Dhf01GqF.js"),__vite__mapDeps([16,1,17])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0;return reactExports.useEffect(()=>{!i&&!t.current&&(t.current=!0,n())},[i,n]),jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),a=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const h=p=>{try{return a.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=a.readSinglePending();m&&a.cancel(m.id)}catch{}return a.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=h(S);u=!0;try{await n.runtime.login(E)}catch(w){try{a.cancel(E.id)}catch{}throw w}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=a.readSinglePending();p&&a.cancel(p.id)},readPending:()=>a.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),a=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,h]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{a.cancelLogin()}catch{}},[u,a]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[w,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),M=reactExports.useRef(!1),$=reactExports.useCallback(O=>{console.error("[WebIdAuthBoundary] authentication action failed",O),v(actionFailureMessage)},[]),G=reactExports.useCallback(O=>{const W=++C.current;v(void 0),E(!0),O().catch(de=>{W===C.current&&$(de)}).finally(()=>{W===C.current&&E(!1)})},[$]),fe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),h(!1),v(void 0),A({})},[]),B=reactExports.useCallback(()=>{if(!w)return;const O=w.prompt;setXpodLoginCancelled(!1),h(!1),A(void 0),G(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await a.startLogin(void 0,void 0,O)})},[a,w,G,t.session,l]),ee=()=>{if(T){re();return}d.status==="authenticated"?t.retryPodOpen?.():fe()},Se=()=>{if(!T){try{a.cancelLogin()}catch{}setXpodLoginCancelled(!0),h(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},re=()=>G(async()=>{F(!0);const O=()=>{setXpodLoginCancelled(!1),h(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:O}):(await t.logout(),O())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch($))},[u,$,t.session,t.state.status]),reactExports.useEffect(()=>{u||w||s||S||T||!e||M.current||d.status!=="anonymous"||(M.current=!0,fe())},[u,s,e,S,w,fe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(w)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:B});const Ae="remembered"in d?d.remembered:void 0,ke=d.status==="restoring",he=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let ce,Ue;return!u&&t.state.status==="error"&&t.state.error.name==="SolidSessionPendingError"?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:"上次登录尚未结束,请刷新页面后重新登录。",primaryLabel:"刷新页面",onPrimary:()=>window.location.reload(),secondaryLabel:"返回登录",onSecondary:Se}):m?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:Se}):ke?(Ue=Ae?void 0:Oe,ce=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ae?.displayName,avatarUrl:Ae?.avatarUrl,label:rememberedCopy.restoringLabel})):he?ce=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:Se}):d.status==="authenticated"?ce=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:re}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ae&&!u?ce=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ae.displayName,avatarUrl:Ae.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ae.displayName):rememberedCopy.continueLabel(Ae.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:fe,onReauthenticate:ee,onSwitchAccount:re})]}):!u&&(d.status==="error"||d.status==="expired")?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:Se}):ce=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:fe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ue,children:ce})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-BRS0sje3.js").then(n=>n.M),__vite__mapDeps([18,19,20,21,11,4,5,22,12]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-DOtvlxH0.js"),__vite__mapDeps([23,9,24,19,20,21,11]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-BJutWaAF.js").then(n=>n.M),__vite__mapDeps([25,24,19,20,21,22,4])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-BS2voQgL.js"),__vite__mapDeps([26,25,24,19,20,21,22,4])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-MyNUSEwT.js"),__vite__mapDeps([27,25,24,19,20,21,22,4])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-Cvt0cJtN.js"),__vite__mapDeps([28,25,24,19,20,21,22,4])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-TIsUfX5d.js"),__vite__mapDeps([29,7,1,30,9,11]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-BJWEt2-7.js"),__vite__mapDeps([31,1,30,19,13,17,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))}])]},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}function createCallbackNavigation({location:n,history:e}){return{origin:n.origin,replace(t){const i=new URL(t,n.origin);if(i.origin===n.origin&&isProductPath(i.pathname)){e.replaceState({},"",`${i.pathname}${i.search}${i.hash}`);return}n.replace(i.href)}}}function resolveCallbackProductDestination(n,e){try{const t=new URL(n,e);if(t.origin!==e)return;const i=productAppForPathname(t.pathname);return i?{app:i,pathname:t.pathname,target:`${t.pathname}${t.search}${t.hash}`}:void 0}catch{return}}function isProductPath(n){return productAppForPathname(n)!==void 0}function productAppForPathname(n){return productSurfaceRoots.find(({basename:e})=>n===e||n.startsWith(`${e}/`))?.app}initializeXpodTheme();const runtime=getXpodSolidRuntimeValue(),callbackLocation=createCallbackNavigation({location:window.location,history:window.history});function renderRedirected(n){const e=resolveCallbackProductDestination(n.destination,window.location.origin);return e?(`${window.location.pathname}${window.location.search}${window.location.hash}`!==e.target&&window.history.replaceState({},"",e.target),jsxRuntimeExports.jsx(XpodShellApp,{runtime,initialPathname:e.pathname},e.target)):jsxRuntimeExports.jsx("main",{role:"status","aria-live":"polite",children:"Sign-in complete. Opening Xpod…"})}clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodOidcCallbackApp,{runtime,location:callbackLocation,renderRedirected})}));export{dispatchDiscreteCustomEvent as $,hasInvalidWebIdWhitespace as A,Button as B,Card as C,Database as D,xpodRegistrationCopy as E,resolveProvisionCodeForPodCreate as F,scopeAccountUrl as G,buildPodCreatePayload as H,getAccountSessionToken as I,accountTokenHeaders as J,resolveProvisionScope as K,storageUrlBelongsToRoot as L,prepareProvisionedPod as M,NavLink as N,Outlet as O,Primitive as P,useAuth as Q,RefreshCw as R,resolveProvisionCodeForCurrentScope as S,Sparkles as T,Gauge as U,reactDomExports as V,useCallbackRef as W,X,toast as Y,Copy as Z,React4 as _,CardHeader as a,clsx as a0,Link as a1,getDefaultExportFromCjs as a2,createLucideIcon$1 as a3,createSlottable as a4,getLinkedResourceUrlAll as a5,acp as a6,internal_cloneResource as a7,getSolidDataset as a8,freeze as a9,AvatarFallback as aA,LoaderCircle$1 as aB,Input as aC,LoginFailureView as aD,LoginConnectingView as aE,Label as aF,dismissToast as aG,controlFocusClass as aH,Toaster as aI,AuthContext as aJ,createXpodLoginController as aK,requireBuffer as aL,requireLink as aM,getAugmentedNamespace as aN,requireBrowser$2 as aO,requireSparql as aP,requireEvents as aQ,requireBrowser$3 as aR,requireString_decoder as aS,bufferExports as aT,commonjsGlobal as aU,getSourceUrl as aa,getResourceInfo as ab,getSourceIri as ac,getThingAll as ad,getIriAll as ae,rdf$3 as af,acl as ag,setThing as ah,setIri as ai,removeIri as aj,removeAll as ak,createThing as al,addIri as am,removeThing as an,subjectToRdfJsQuads as ao,DataFactory$1 as ap,getIri as aq,saveSolidDatasetAt as ar,createSolidDataset as as,foaf as at,getThing as au,getUrlAll as av,buildThing as aw,__vitePreload as ax,Avatar as ay,AvatarImage as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,credentialDescriptor as h,interactiveFocusClass as i,jsxRuntimeExports as j,credentialResource as k,useLayoutEffect2 as l,useComposedRefs as m,createContextScope as n,createSlot as o,aiConfigModelRef as p,aiProviderResource as q,reactExports as r,aiModelResource as s,configureSparqlEngine as t,useXpodSolidRuntime as u,useLocation as v,handleListNavigationKeyDown as w,getListNavItemClass as x,resolveHostedAccountControlUrl as y,storedAccountTokenHeaders as z};
|
|
306
|
+
Please change the parent <Route path="${w}"> to <Route path="${w==="/"?"*":`${w}/*`}">.`)}let p=useLocation(),g;g=p;let m=g.pathname||"/",v=m;if(h!=="/"){let w=h.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(w.length).join("/")}let S=t&&t.state.matches.length?t.state.matches.map(w=>Object.assign(w,{route:t.manifest[w.route.id]||w.route})):matchRoutes(n,{pathname:v});return warning(d||S!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),warning(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(S&&S.map(w=>Object.assign({},w,{params:Object.assign({},l,w.params),pathname:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?h:joinPaths([h,i.encodeLocation?i.encodeLocation(w.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathnameBase])})),s,t)}function DefaultErrorComponent(){let n=useRouteError(),e=isRouteErrorResponse(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i},a={padding:"2px 4px",backgroundColor:i},l=null;return console.error("Error handled by React Router default ErrorBoundary:",n),l=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:a},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:a},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},e),t?reactExports.createElement("pre",{style:s},t):null,l)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,e){return e.location!==n.location||e.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:e.error,location:e.location,revalidation:n.revalidation||e.revalidation}}componentDidCatch(n,e){this.props.onError?this.props.onError(n,e):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const t=decodeRouteErrorResponseDigest(n.digest);t&&(n=t)}let e=n!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:n},e):e}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:n,error:e}){let{basename:t}=reactExports.useContext(NavigationContext);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let i=decodeRedirectErrorDigest(e.digest);if(i){let s=errorRedirectHandledMap.get(e);if(s)throw s;let a=parseToInfo(i.location,t),l=a.absoluteURL||a.to;if(hasInvalidProtocol(l))throw new Error("Invalid redirect location");if(isBrowser$1&&!errorRedirectHandledMap.get(e))if(a.isExternal||i.reloadDocument)window.location.href=l;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:i.replace}));throw errorRedirectHandledMap.set(e,u),u}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${l}`})}}return n}function RenderedRoute({routeContext:n,match:e,children:t}){let i=reactExports.useContext(DataRouterContext);return i&&i.static&&i.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=e.route.id),reactExports.createElement(RouteContext.Provider,{value:n},t)}function _renderMatches(n,e=[],t){let i=t?.state;if(n==null){if(!i)return null;if(i.errors)n=i.matches;else if(e.length===0&&!i.initialized&&i.matches.length>0)n=i.matches;else return null}let s=n,a=i?.errors;if(a!=null){let p=s.findIndex(g=>g.route.id&&a?.[g.route.id]!==void 0);invariant(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(",")}`),s=s.slice(0,Math.min(s.length,p+1))}let l=!1,u=-1;if(t&&i){l=i.renderFallback;for(let p=0;p<s.length;p++){let g=s[p];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(u=p),g.route.id){let{loaderData:m,errors:v}=i,S=g.route.loader&&!m.hasOwnProperty(g.route.id)&&(!v||v[g.route.id]===void 0);if(g.route.lazy||S){t.isStatic&&(l=!0),u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}}let h=t?.onError,d=i&&h?(p,g)=>{h(p,{location:i.location,params:i.matches?.[0]?.params??{},pattern:getRoutePattern(i.matches),errorInfo:g})}:void 0;return s.reduceRight((p,g,m)=>{let v,S=!1,E=null,w=null;i&&(v=a&&g.route.id?a[g.route.id]:void 0,E=g.route.errorElement||defaultErrorElement,l&&(u<0&&m===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,w=null):u===m&&(S=!0,w=g.route.hydrateFallbackElement||null)));let A=e.concat(s.slice(0,m+1)),C=()=>{let T;return v?T=E:S?T=w:g.route.Component?T=reactExports.createElement(g.route.Component,null):g.route.element?T=g.route.element:T=p,reactExports.createElement(RenderedRoute,{match:g,routeContext:{outlet:p,matches:A,isDataRoute:i!=null},children:T})};return i&&(g.route.ErrorBoundary||g.route.errorElement||m===0)?reactExports.createElement(RenderErrorBoundary,{location:i.location,revalidation:i.revalidation,component:E,error:v,children:C(),routeContext:{outlet:null,matches:A,isDataRoute:!0},onError:d}):C()},null)}function getDataRouterConsoleError(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError(n)),e}function useDataRouterState(n){let e=reactExports.useContext(DataRouterStateContext);return invariant(e,getDataRouterConsoleError(n)),e}function useRouteContext(n){let e=reactExports.useContext(RouteContext);return invariant(e,getDataRouterConsoleError(n)),e}function useCurrentRouteId(n){let e=useRouteContext(n),t=e.matches[e.matches.length-1];return invariant(t.route.id,`${n} can only be used on routes that contain a unique "id"`),t.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let n=reactExports.useContext(RouteErrorContext),e=useDataRouterState("useRouteError"),t=useCurrentRouteId("useRouteError");return n!==void 0?n:e.errors?.[t]}function useNavigateStable(){let{router:n}=useDataRouterContext("useNavigate"),e=useCurrentRouteId("useNavigate"),t=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{t.current=!0}),reactExports.useCallback(async(s,a={})=>{warning(t.current,navigateEffectWarning),t.current&&(typeof s=="number"?await n.navigate(s):await n.navigate(s,{fromRouteId:e,...a}))},[n,e])}var alreadyWarned={};function warningOnce(n,e,t){!e&&!alreadyWarned[n]&&(alreadyWarned[n]=!0,warning(!1,t))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:n,manifest:e,future:t,state:i,isStatic:s,onError:a}){return useRoutesImpl(n,void 0,{manifest:e,state:i,isStatic:s,onError:a})}function Navigate({to:n,replace:e,state:t,relative:i}){invariant(useInRouterContext(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=reactExports.useContext(NavigationContext);warning(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=reactExports.useContext(RouteContext),{pathname:l}=useLocation(),u=useNavigate(),h=resolveTo(n,getResolveToMatches(a),l,i==="path"),d=JSON.stringify(h);return reactExports.useEffect(()=>{u(JSON.parse(d),{replace:e,state:t,relative:i})},[u,d,i,e,t]),null}function Outlet(n){return useOutlet(n.context)}function Router({basename:n="/",children:e=null,location:t,navigationType:i="POP",navigator:s,static:a=!1,useTransitions:l}){invariant(!useInRouterContext(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=n.replace(/^\/*/,"/"),h=reactExports.useMemo(()=>({basename:u,navigator:s,static:a,useTransitions:l,future:{}}),[u,s,a,l]);typeof t=="string"&&(t=parsePath(t));let{pathname:d="/",search:p="",hash:g="",state:m=null,key:v="default",mask:S}=t,E=reactExports.useMemo(()=>{let w=stripBasename(d,u);return w==null?null:{location:{pathname:w,search:p,hash:g,state:m,key:v,mask:S},navigationType:i}},[u,d,p,g,m,v,i,S]);return warning(E!=null,`<Router basename="${u}"> is not able to match the URL "${d}${p}${g}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:reactExports.createElement(NavigationContext.Provider,{value:h},reactExports.createElement(LocationContext.Provider,{children:e,value:E}))}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function isButtonElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="button"}function isFormElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="form"}function isInputElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="input"}function isModifiedEvent(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function shouldProcessLinkClick(n,e){return n.button===0&&(!e||e==="_self")&&!isModifiedEvent(n)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(n){return n!=null&&!supportedFormEncTypes.has(n)?(warning(!1,`"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):n}function getFormSubmissionInfo(n,e){let t,i,s,a,l;if(isFormElement(n)){let u=n.getAttribute("action");i=u?stripBasename(u,e):null,t=n.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("enctype"))||defaultEncType,a=new FormData(n)}else if(isButtonElement(n)||isInputElement(n)&&(n.type==="submit"||n.type==="image")){let u=n.form;if(u==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let h=n.getAttribute("formaction")||u.getAttribute("action");if(i=h?stripBasename(h,e):null,t=n.getAttribute("formmethod")||u.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("formenctype"))||getFormEncType(u.getAttribute("enctype"))||defaultEncType,a=new FormData(u,n),!isFormDataSubmitterSupported()){let{name:d,type:p,value:g}=n;if(p==="image"){let m=d?`${d}.`:"";a.append(`${m}x`,"0"),a.append(`${m}y`,"0")}else d&&a.append(d,g)}}else{if(isHtmlElement(n))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=defaultMethod,i=null,s=defaultEncType,l=n}return a&&s==="text/plain"&&(l=a,a=void 0),{action:i,method:t.toLowerCase(),encType:s,formData:a,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function singleFetchUrl(n,e,t,i){let s=typeof n=="string"?new URL(n,typeof window>"u"?"server://singlefetch/":window.location.origin):n;return t?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${i}`:s.pathname=`${s.pathname}.${i}`:s.pathname==="/"?s.pathname=`_root.${i}`:e&&stripBasename(s.pathname,e)==="/"?s.pathname=`${removeTrailingSlash(e)}/_root.${i}`:s.pathname=`${removeTrailingSlash(s.pathname)}.${i}`,s}async function loadRouteModule(n,e){if(n.id in e)return e[n.id];try{let t=await import(n.module);return e[n.id]=t,t}catch(t){return console.error(`Error loading route module \`${n.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(n){return n==null?!1:n.href==null?n.rel==="preload"&&typeof n.imageSrcSet=="string"&&typeof n.imageSizes=="string":typeof n.rel=="string"&&typeof n.href=="string"}async function getKeyedPrefetchLinks(n,e,t){let i=await Promise.all(n.map(async s=>{let a=e.routes[s.route.id];if(a){let l=await loadRouteModule(a,t);return l.links?l.links():[]}return[]}));return dedupeLinkDescriptors(i.flat(1).filter(isHtmlLinkDescriptor).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function getNewMatchesForLinks(n,e,t,i,s,a){let l=(h,d)=>t[d]?h.route.id!==t[d].route.id:!0,u=(h,d)=>t[d].pathname!==h.pathname||t[d].route.path?.endsWith("*")&&t[d].params["*"]!==h.params["*"];return a==="assets"?e.filter((h,d)=>l(h,d)||u(h,d)):a==="data"?e.filter((h,d)=>{let p=i.routes[h.route.id];if(!p||!p.hasLoader)return!1;if(l(h,d)||u(h,d))return!0;if(h.route.shouldRevalidate){let g=h.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:t[0]?.params||{},nextUrl:new URL(n,window.origin),nextParams:h.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function getModuleLinkHrefs(n,e,{includeHydrateFallback:t}={}){return dedupeHrefs(n.map(i=>{let s=e.routes[i.route.id];if(!s)return[];let a=[s.module];return s.clientActionModule&&(a=a.concat(s.clientActionModule)),s.clientLoaderModule&&(a=a.concat(s.clientLoaderModule)),t&&s.hydrateFallbackModule&&(a=a.concat(s.hydrateFallbackModule)),s.imports&&(a=a.concat(s.imports)),a}).flat(1))}function dedupeHrefs(n){return[...new Set(n)]}function sortKeys(n){let e={},t=Object.keys(n).sort();for(let i of t)e[i]=n[i];return e}function dedupeLinkDescriptors(n,e){let t=new Set;return new Set(e),n.reduce((i,s)=>{let a=JSON.stringify(sortKeys(s));return t.has(a)||(t.add(a),i.push({key:a,link:s})),i},[])}function useDataRouterContext2(){let n=reactExports.useContext(DataRouterContext);return invariant2(n,"You must render this element inside a <DataRouterContext.Provider> element"),n}function useDataRouterStateContext(){let n=reactExports.useContext(DataRouterStateContext);return invariant2(n,"You must render this element inside a <DataRouterStateContext.Provider> element"),n}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let n=reactExports.useContext(FrameworkContext);return invariant2(n,"You must render this element inside a <HydratedRouter> element"),n}function usePrefetchBehavior(n,e){let t=reactExports.useContext(FrameworkContext),[i,s]=reactExports.useState(!1),[a,l]=reactExports.useState(!1),{onFocus:u,onBlur:h,onMouseEnter:d,onMouseLeave:p,onTouchStart:g}=e,m=reactExports.useRef(null);reactExports.useEffect(()=>{if(n==="render"&&l(!0),n==="viewport"){let E=A=>{A.forEach(C=>{l(C.isIntersecting)})},w=new IntersectionObserver(E,{threshold:.5});return m.current&&w.observe(m.current),()=>{w.disconnect()}}},[n]),reactExports.useEffect(()=>{if(i){let E=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(E)}}},[i]);let v=()=>{s(!0)},S=()=>{s(!1),l(!1)};return t?n!=="intent"?[a,m,{}]:[a,m,{onFocus:composeEventHandlers(u,v),onBlur:composeEventHandlers(h,S),onMouseEnter:composeEventHandlers(d,v),onMouseLeave:composeEventHandlers(p,S),onTouchStart:composeEventHandlers(g,v)}]:[!1,m,{}]}function composeEventHandlers(n,e){return t=>{n&&n(t),t.defaultPrevented||e(t)}}function PrefetchPageLinks({page:n,...e}){let t=useIsRSCRouterContext(),{nonce:i}=useFrameworkContext(),{router:s}=useDataRouterContext2(),a=reactExports.useMemo(()=>matchRoutes(s.routes,n,s.basename),[s.routes,n,s.basename]);return a?(e.nonce==null&&i&&(e={...e,nonce:i}),t?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:n,matches:a,...e}):reactExports.createElement(PrefetchPageLinksImpl,{page:n,matches:a,...e})):null}function useKeyedPrefetchLinks(n){let{manifest:e,routeModules:t}=useFrameworkContext(),[i,s]=reactExports.useState([]);return reactExports.useEffect(()=>{let a=!1;return getKeyedPrefetchLinks(n,e,t).then(l=>{a||s(l)}),()=>{a=!0}},[n,e,t]),i}function RSCPrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s}=useFrameworkContext(),{basename:a}=useDataRouterContext2(),l=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let u=singleFetchUrl(n,a,s.v8_trailingSlashAwareDataRequests,"rsc"),h=!1,d=[];for(let p of e)typeof p.route.shouldRevalidate=="function"?h=!0:d.push(p.route.id);return h&&d.length>0&&u.searchParams.set("_routes",d.join(",")),[u.pathname+u.search]},[a,s.v8_trailingSlashAwareDataRequests,n,i,e]);return reactExports.createElement(reactExports.Fragment,null,l.map(u=>reactExports.createElement("link",{key:u,rel:"prefetch",as:"fetch",href:u,...t})))}function PrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s,manifest:a,routeModules:l}=useFrameworkContext(),{basename:u}=useDataRouterContext2(),{loaderData:h,matches:d}=useDataRouterStateContext(),p=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"data"),[n,e,d,a,i]),g=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"assets"),[n,e,d,a,i]),m=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let E=new Set,w=!1;if(e.forEach(C=>{let T=a.routes[C.route.id];!T||!T.hasLoader||(!p.some(F=>F.route.id===C.route.id)&&C.route.id in h&&l[C.route.id]?.shouldRevalidate||T.hasClientLoader?w=!0:E.add(C.route.id))}),E.size===0)return[];let A=singleFetchUrl(n,u,s.v8_trailingSlashAwareDataRequests,"data");return w&&E.size>0&&A.searchParams.set("_routes",e.filter(C=>E.has(C.route.id)).map(C=>C.route.id).join(",")),[A.pathname+A.search]},[u,s.v8_trailingSlashAwareDataRequests,h,i,a,p,e,n,l]),v=reactExports.useMemo(()=>getModuleLinkHrefs(g,a),[g,a]),S=useKeyedPrefetchLinks(g);return reactExports.createElement(reactExports.Fragment,null,m.map(E=>reactExports.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...t})),v.map(E=>reactExports.createElement("link",{key:E,rel:"modulepreload",href:E,...t})),S.map(({key:E,link:w})=>reactExports.createElement("link",{key:E,nonce:t.nonce,...w,crossOrigin:w.crossOrigin??t.crossOrigin})))}function mergeRefs(...n){return e=>{n.forEach(t=>{typeof t=="function"?t(e):t!=null&&(t.current=e)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.2")}catch(n){}function BrowserRouter({basename:n,children:e,useTransitions:t,window:i}){let s=reactExports.useRef();s.current==null&&(s.current=createBrowserHistory({window:i,v5Compat:!0}));let a=s.current,[l,u]=reactExports.useState({action:a.action,location:a.location}),h=reactExports.useCallback(d=>{t===!1?u(d):reactExports.startTransition(()=>u(d))},[t]);return reactExports.useLayoutEffect(()=>a.listen(h),[a,h]),reactExports.createElement(Router,{basename:n,children:e,location:l.location,navigationType:l.action,navigator:a,useTransitions:t})}var Link=reactExports.forwardRef(function n({onClick:e,discover:t="render",prefetch:i="none",relative:s,reloadDocument:a,replace:l,mask:u,state:h,target:d,to:p,preventScrollReset:g,viewTransition:m,defaultShouldRevalidate:v,...S},E){let{basename:w,navigator:A,useTransitions:C}=reactExports.useContext(NavigationContext),T=typeof p=="string"&&ABSOLUTE_URL_REGEX.test(p),F=parseToInfo(p,w);p=F.to;let P=useHref(p,{relative:s}),M=useLocation(),$=null;if(u){let ke=resolveTo(u,[],M.mask?M.mask.pathname:"/",!0);w!=="/"&&(ke.pathname=ke.pathname==="/"?w:joinPaths([w,ke.pathname])),$=A.createHref(ke)}let[G,fe,B]=usePrefetchBehavior(i,S),ee=useLinkClickHandler(p,{replace:l,mask:u,state:h,target:d,preventScrollReset:g,relative:s,viewTransition:m,defaultShouldRevalidate:v,useTransitions:C});function Se(ke){e&&e(ke),ke.defaultPrevented||ee(ke)}let re=!(F.isExternal||a),Ae=reactExports.createElement("a",{...S,...B,href:(re?$:void 0)||F.absoluteURL||P,onClick:re?Se:e,ref:mergeRefs(E,fe),target:d,"data-discover":!T&&t==="render"?"true":void 0});return G&&!T?reactExports.createElement(reactExports.Fragment,null,Ae,reactExports.createElement(PrefetchPageLinks,{page:P})):Ae});Link.displayName="Link";var NavLink=reactExports.forwardRef(function n({"aria-current":e="page",caseSensitive:t=!1,className:i="",end:s=!1,style:a,to:l,viewTransition:u,children:h,...d},p){let g=useResolvedPath(l,{relative:d.relative}),m=useLocation(),v=reactExports.useContext(DataRouterStateContext),{navigator:S,basename:E}=reactExports.useContext(NavigationContext),w=v!=null&&useViewTransitionState(g)&&u===!0,A=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,C=m.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;t||(C=C.toLowerCase(),T=T?T.toLowerCase():null,A=A.toLowerCase()),T&&E&&(T=stripBasename(T,E)||T);const F=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let P=C===A||!s&&C.startsWith(A)&&C.charAt(F)==="/",M=T!=null&&(T===A||!s&&T.startsWith(A)&&T.charAt(A.length)==="/"),$={isActive:P,isPending:M,isTransitioning:w},G=P?e:void 0,fe;typeof i=="function"?fe=i($):fe=[i,P?"active":null,M?"pending":null,w?"transitioning":null].filter(Boolean).join(" ");let B=typeof a=="function"?a($):a;return reactExports.createElement(Link,{...d,"aria-current":G,className:fe,ref:p,style:B,to:l,viewTransition:u},typeof h=="function"?h($):h)});NavLink.displayName="NavLink";var Form=reactExports.forwardRef(({discover:n="render",fetcherKey:e,navigate:t,reloadDocument:i,replace:s,state:a,method:l=defaultMethod,action:u,onSubmit:h,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m,...v},S)=>{let{useTransitions:E}=reactExports.useContext(NavigationContext),w=useSubmit(),A=useFormAction(u,{relative:d}),C=l.toLowerCase()==="get"?"get":"post",T=typeof u=="string"&&ABSOLUTE_URL_REGEX.test(u),F=P=>{if(h&&h(P),P.defaultPrevented)return;P.preventDefault();let M=P.nativeEvent.submitter,$=M?.getAttribute("formmethod")||l,G=()=>w(M||P.currentTarget,{fetcherKey:e,method:$,navigate:t,replace:s,state:a,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m});E&&t!==!1?reactExports.startTransition(()=>G()):G()};return reactExports.createElement("form",{ref:S,method:C,action:A,onSubmit:i?h:F,...v,"data-discover":!T&&n==="render"?"true":void 0})});Form.displayName="Form";function getDataRouterConsoleError2(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError2(n)),e}function useLinkClickHandler(n,{target:e,replace:t,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h,useTransitions:d}={}){let p=useNavigate(),g=useLocation(),m=useResolvedPath(n,{relative:l});return reactExports.useCallback(v=>{if(shouldProcessLinkClick(v,e)){v.preventDefault();let S=t!==void 0?t:createPath(g)===createPath(m),E=()=>p(n,{replace:S,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:h});d?reactExports.startTransition(()=>E()):E()}},[g,p,m,t,i,s,e,n,a,l,u,h,d])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:n}=useDataRouterContext3("useSubmit"),{basename:e}=reactExports.useContext(NavigationContext),t=useRouteId(),i=n.fetch,s=n.navigate;return reactExports.useCallback(async(a,l={})=>{let{action:u,method:h,encType:d,formData:p,body:g}=getFormSubmissionInfo(a,e);if(l.navigate===!1){let m=l.fetcherKey||getUniqueFetcherId();await i(m,t,l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,flushSync:l.flushSync})}else await s(l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||h,formEncType:l.encType||d,replace:l.replace,state:l.state,fromRouteId:t,flushSync:l.flushSync,viewTransition:l.viewTransition})},[i,s,e,t])}function useFormAction(n,{relative:e}={}){let{basename:t}=reactExports.useContext(NavigationContext),i=reactExports.useContext(RouteContext);invariant(i,"useFormAction must be used inside a RouteContext");let[s]=i.matches.slice(-1),a={...useResolvedPath(n||".",{relative:e})},l=useLocation();if(n==null){a.search=l.search;let u=new URLSearchParams(a.search),h=u.getAll("index");if(h.some(p=>p==="")){u.delete("index"),h.filter(g=>g).forEach(g=>u.append("index",g));let p=u.toString();a.search=p?`?${p}`:""}}return(!n||n===".")&&s.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(a.pathname=a.pathname==="/"?t:joinPaths([t,a.pathname])),createPath(a)}function useViewTransitionState(n,{relative:e}={}){let t=reactExports.useContext(ViewTransitionContext);invariant(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=useDataRouterContext3("useViewTransitionState"),s=useResolvedPath(n,{relative:e});if(!t.isTransitioning)return!1;let a=stripBasename(t.currentLocation.pathname,i)||t.currentLocation.pathname,l=stripBasename(t.nextLocation.pathname,i)||t.nextLocation.pathname;return matchPath(s.pathname,l)!=null||matchPath(s.pathname,a)!=null}function WebAccountFailureView({title:n="操作未完成",description:e,primaryLabel:t="重试",onPrimary:i,secondaryLabel:s="返回",onSecondary:a,pending:l=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:i,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:t}),a?jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:a,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring",children:s}):null]})]})}let automaticLoginBlocked=!1,logoutState={status:"idle"},operation,inFlight;const logoutListeners=new Set,isXpodAutomaticLoginBlocked=()=>automaticLoginBlocked,getXpodProductLogoutState=()=>logoutState;function subscribeXpodProductLogout(n){return logoutListeners.add(n),()=>{logoutListeners.delete(n)}}function publish(n){logoutState=n,logoutListeners.forEach(e=>e())}function logoutXpodProduct(n,e,t={}){return inFlight||(automaticLoginBlocked=!0,operation={account:n,runtime:e,solidCleared:!1,onComplete:t.onComplete},retryXpodProductLogout())}function retryXpodProductLogout(){if(inFlight)return inFlight;if(!operation)return Promise.resolve();const n=operation;return inFlight=(async()=>{let t=n.solidCleared?"account":"solid";publish({status:"running",step:t});try{if(n.solidCleared||(await n.runtime?.logout(),n.solidCleared=!0),t="account",publish({status:"running",step:t}),await n.account.logout(),n.account.isAnonymous&&!n.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(i){throw publish({status:"error",step:t}),i}operation=void 0,publish({status:"idle"}),n.onComplete?.()})().finally(()=>{inFlight=void 0}),inFlight}const LogoutRecoveryOwner=reactExports.createContext(!1);function XpodProductLogoutBoundary({children:n}){const e=reactExports.useContext(LogoutRecoveryOwner),t=reactExports.useSyncExternalStore(subscribeXpodProductLogout,getXpodProductLogoutState,getXpodProductLogoutState);if(e)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const i=t.status!=="idle";return jsxRuntimeExports.jsxs(LogoutRecoveryOwner.Provider,{value:!0,children:[i&&jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"退出 Xpod",children:t.status==="running"?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在退出…"}):jsxRuntimeExports.jsx(WebAccountFailureView,{title:"退出未完成",description:t.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{retryXpodProductLogout().catch(()=>{})}})}),jsxRuntimeExports.jsx("div",{className:i?"hidden":"contents","aria-hidden":i||void 0,inert:i||void 0,children:n})]})}const AuthContext=reactExports.createContext(null);function useAuth(){const n=reactExports.useContext(AuthContext);if(!n)throw new Error("useAuth must be used within AuthProvider");return n}function useXpodProfileCardIdentity({accountIdentity:n,runtime:e}){const t=e?.state.status,i=t==="authenticated"&&e?e.webId??e.state.webId:n?.webId,s=t==="authenticated"&&i?void 0:n,a=s?.displayName,l=s?.username,u=s?.id,h=s?.webId,d=e?.fetch,p=reactExports.useMemo(()=>accountProfileFallback({displayName:a,username:l,id:u},i),[a,u,l,h,i]),g=`${i??""}\0${p.displayName}\0${p.username??""}`,[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1);reactExports.useEffect(()=>{const A=d;if(t!=="authenticated"||!A||!i)return;let C=!1,T;async function F(P,M){E(!0);try{const $=await resolveSolidProfileIdentityFromWebIdDocument({info:{webId:M},fetch:P});if(C||!$)return;const G=normalizedHttpUrl($.profile?.avatar);let fe=G;if(G&&(fe=await resolveAuthenticatedAvatarUrl(P,G),T=fe?.startsWith("blob:")?fe:void 0),C){T&&URL.revokeObjectURL(T);return}v({key:g,value:{displayName:$.displayName??$.username??p.displayName,username:$.username||p.username,avatarUrl:fe??p.avatarUrl,avatarSourceUrl:G,note:$.profile?.note||p.note,region:$.profile?.region||p.region,webId:$.webId||p.webId,loading:!1,source:"webid-profile"}})}catch{C||v(void 0)}finally{C||E(!1)}}return F(A,i),()=>{C=!0,T&&URL.revokeObjectURL(T)}},[d,p,g,t,i]);const w=t==="authenticated"?S:!1;return t==="authenticated"&&m?.key===g?{...m.value,loading:w}:{...p,loading:w}}function accountProfileFallback(n,e){const t=n?.username||usernameFromWebId$1(e)||n?.id;return{displayName:n?.displayName||t||n?.id||"Xpod account",username:t,webId:e,loading:!1,source:"account"}}async function resolveAuthenticatedAvatarUrl(n,e){try{const t=await n(e);if(!t.ok)return e;const i=await t.blob();return URL.createObjectURL(i)}catch{return e}}function normalizedHttpUrl(n){if(n)try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function usernameFromWebId$1(n){if(n)try{const e=new URL(n);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const useXpodSolidRuntime=useXpodSolidRuntimeContext,XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),i=validatedWebId(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),a=validatedWebId(e.webId),l=validatedWebId(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!a||!l||!u||t!==i||a!==l||t!==a||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,a=normalizedEmail(i.email),l=validatedWebId(t.webId),u=validatedWebId(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!a||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...a?{email:a}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(n){return typeof n=="string"&&!hasInvalidWebIdWhitespace(n)&&normalizedUrl(n)?n:void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const a=normalizedUrl(s);return a&&new URL(a).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,a=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??a?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||a&&!rememberedXpodLoginMatchesActive(a,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??a?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??a?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,a,e.currentPod,t,s]),null}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTHORITY_STORAGE_KEY="xpod.cssAccountAuthority",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function bindAccountSessionAuthority(n){if(!isBrowser())return!1;const e=normalizeAccountAuthority(n),t=window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY),i=t!==null?t!==e:new URL(e).origin!==window.location.origin;return window.localStorage.setItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY,e),i&&clearAccountSessionToken(),i}function normalizeAccountAuthority(n){const e=new URL(n,window.location.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/.account/"||e.search||e.hash)throw new Error("Invalid Account authority");return e.href}function storeAccountSessionToken(n){!n||readCssAccountCookie()===n||writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"},e){if(e)try{if(window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY)!==normalizeAccountAuthority(e))return{...n}}catch{return{...n}}return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:scopeAccountUrl(t)}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const d=new URL(t,window.location.origin),p=new URL(n.trim(),d);if(p.origin===d.origin&&d.pathname.startsWith("/.account/")&&p.pathname.startsWith("/.account/")&&["http:","https:"].includes(p.protocol)&&!p.username&&!p.password)return scopeAccountUrl(p)}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const d=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(d)return scopeAccountUrl(d)}const a={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,a.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...a,fetch:async()=>l.clone()}):void 0;u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin);const h=u?resolveSolidLocalRouteUrl(s,[u]):void 0;return h?scopeAccountUrl(h):void 0}const LOCAL_ACCOUNT_INDEX$1="/.account/";function isProvisionStatusResponse(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX$1;if(!isLoopbackHostname$1(window.location.hostname)){const i=window.__XPOD__?.idpIndex;if(i!==void 0){try{const s=new URL(i,window.location.origin);if(typeof i=="string"&&i.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===LOCAL_ACCOUNT_INDEX$1&&!s.username&&!s.password&&!s.search&&!s.hash)return unregisterLocalProvisionResolver(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(e.status===404)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(!e.ok)throw new Error(`Local provisioning status request failed (${e.status})`);let t;try{t=await e.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!isProvisionStatusResponse(t)||typeof t.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(t.managed===!1)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(typeof t.oidcIssuer=="string")try{const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return installLocalProvisionResolver(n),typeof t.provisionCode=="string"&&setStoredProvisionCode(t.provisionCode),new URL(LOCAL_ACCOUNT_INDEX$1,i).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function installLocalProvisionResolver(n){const e=new URL("/provision/status",window.location.origin);registerLocalProvisionResolver(async()=>{const t=await n(e,{credentials:"include",headers:{accept:"application/json"}}),i=t.ok?await t.json().catch(()=>{}):void 0;if(i?.managed!==!0||i?.registered!==!0||typeof i?.provisionCode!="string")throw new Error(CLOUD_PROVISIONING_UNAVAILABLE);return i.provisionCode})}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[a,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,m]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),w=reactExports.useRef(void 0),A=reactExports.useRef(null),C=reactExports.useRef(void 0),T=reactExports.useRef(0),F=reactExports.useRef(0),P=reactExports.useRef(!1),M=reactExports.useCallback(()=>{const te=A.current?.account;return te?.logout?JSON.stringify([w.current,te.id,te.logout,te.clientCredentials]):void 0},[]),$=reactExports.useCallback(()=>{T.current+=1,P.current=!0},[]),G=reactExports.useCallback((te,Te)=>{const je=M(),He=C.current;A.current=te,C.current=Te,(je!==M()||He!==Te)&&$(),P.current=!M()},[M,$]),fe=reactExports.useCallback(()=>{const te=M(),Te=T.current,je=getAccountSessionToken();let He=!!te&&je===C.current&&!P.current&&F.current===0;return()=>{if(!He||!S.current||P.current||F.current>0||Te!==T.current||te!==M()||je!==getAccountSessionToken())throw He=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[M]),B=g.status==="authenticated",ee=a||g.status==="submitting",Se=reactExports.useRef(!1),re=reactExports.useCallback(te=>{(bindAccountSessionAuthority(te)||w.current&&w.current!==te)&&(E.current+=1,v.current+=1,Se.current=!1,G(null),s(null),p(!1),m({status:"initializing"})),w.current=te,t(te)},[G]),Ae=reactExports.useCallback(async()=>{l(!0),h(null),m(te=>te.status==="authenticated"?te:{status:"initializing"});try{const te=await resolveXpodAccountIndex();return S.current?(re(te),te):void 0}catch{if(!S.current)return;G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1);return}},[re,G]);reactExports.useEffect(()=>{let te=!0;return resolveXpodAccountIndex().then(Te=>{te&&S.current&&re(Te)}).catch(()=>{!te||!S.current||(G(null),s(null),p(!1),h(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1))}),()=>{te=!1}},[re,G]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,$(),E.current+=1}),[$]);const ke=reactExports.useCallback(te=>S.current&&te===E.current,[]),he=reactExports.useCallback(async()=>{const te=new AbortController,Te=setTimeout(()=>te.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{const je=w.current;if(!je)return!1;const He=await fetch(scopeAccountUrl(new URL("oidc/consent/",je)),{headers:storedAccountTokenHeaders(void 0,je),credentials:"include",signal:te.signal});return He.ok?!!(await He.json()).client:!1}catch{return!1}finally{clearTimeout(Te)}},[]),Oe=reactExports.useCallback(async({exposeTransientError:te,generation:Te,confirmUnauthenticated:je})=>{const He=w.current;if(!He)return"stale";const We=getAccountSessionToken(),me=()=>We===getAccountSessionToken()?!0:($(),!1);try{const ge=await fetch(scopeAccountUrl(He),{headers:storedAccountTokenHeaders(void 0,He),credentials:"include"});if(!ke(Te))return"stale";if(!me())return"transient-error";if(ge.ok){const Be=await ge.json();if(!ke(Te))return"stale";if(!me())return"transient-error";if(!Be?.controls||typeof Be.controls!="object"||Array.isArray(Be.controls))throw new Error("Invalid CSS Account controls response");const ie=Be.controls,q=++v.current;p(!1),G(ie,We),s(ie),h(null);const N=accountStateForControls(ie);return Se.current=N.status==="anonymous",m(N),ie.account?.logout&&isAccountSpaPath()&&he().then(k=>{ke(Te)&&q===v.current&&p(k)}),"ok"}else{if(ge.status===401||ge.status===403)return je?(v.current+=1,clearAccountSessionToken(),Se.current=!0,p(!1),G({}),s({}),m({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(ge.status))return h(null),m(ie=>ie.status==="authenticated"?ie:transientAccountState(te)),"transient-error";$();const Be=`Failed to load account controls (Status: ${ge.status})`;return h(Be),m({status:"error",mode:"login",message:Be}),"terminal-error"}}catch{return ke(Te)?(v.current+=1,p(!1),h(null),m(ge=>ge.status==="authenticated"?ge:transientAccountState(te)),"transient-error"):"stale"}},[G,he,ke,$]),ce=reactExports.useCallback(async()=>{const te=++E.current;for(let Te=0;Te<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;Te+=1){const je=Te===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,He=await Oe({exposeTransientError:je,generation:te});if(He==="unauthenticated")return!ke(te)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!ke(te))?"stale":Oe({exposeTransientError:!0,generation:te,confirmUnauthenticated:!0});if(He!=="transient-error")return He;if(!ke(te)||!je&&(m(We=>We.status==="authenticated"?We:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[Te]),!ke(te)))return"stale"}return"transient-error"},[Oe,ke]);reactExports.useEffect(()=>{if(!e)return;let te=!0;return(async()=>(await ce(),te&&S.current&&l(!1)))(),()=>{te=!1}},[ce,e]);const Ue=reactExports.useCallback(async()=>{const te=await Ae();if(te&&te===e){const Te=await ce();if(S.current&&l(!1),Te==="ok")return accountStateForControls(A.current)}return{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}},[ce,e,Ae]),O=reactExports.useCallback(async()=>{await Ue()},[Ue]),W=reactExports.useCallback(async()=>{F.current+=1;try{$(),E.current+=1,v.current+=1,A.current?.account?.logout||(Se.current=!1,(w.current??await Ae())&&await ce());const te=w.current,Te=A.current?.account?.logout,je=await resolveHostedAccountControlUrl(Te,fetch,te);let He=!je&&(!!Te||!Se.current);if(je)try{const We=await fetch(scopeAccountUrl(je),{method:"POST",headers:storedAccountTokenHeaders(void 0,te),credentials:"include"});He=!We.ok&&We.status!==401&&We.status!==403}catch{He=!0}if(He){m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}E.current+=1,v.current+=1,Se.current=!0,l(!1),clearAccountSessionToken(),p(!1),G({}),s({}),h(null),m({status:"anonymous",mode:"login"})}finally{F.current-=1}},[G,ce,Ae,$]),de=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:a,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:B,isAnonymous:()=>Se.current,bindAccountCapability:fe,authenticating:ee,hasOidcPending:d,refetchControls:Ue,retry:O,logout:W,accountState:g,identity:de},children:n})}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const a=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:a,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XpodServiceAvailability({children:n}){const[e,t]=reactExports.useState(!1),i=reactExports.useRef(()=>{}),s=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!e)return;const a=document.activeElement;return s.current?.focus(),()=>{a instanceof HTMLElement&&a.isConnected&&a.focus()}},[e]),reactExports.useEffect(()=>{let a=!1,l,u,h=0;async function d(){if(a||l)return;clearTimeout(u);const g=new AbortController;l=g;const m=setTimeout(()=>g.abort(),5e3);let v=!0;try{const S=await fetch("/service/status",{cache:"no-store",signal:g.signal});if(v=S.status<500,S.ok){const E=await S.json().catch(()=>null);Array.isArray(E)&&(v=!E.some(w=>w&&["css","api"].includes(w.name)&&typeof w.status=="string"&&w.status!=="running")),g.signal.aborted&&(v=!1)}else await S.body?.cancel()}catch{v=!1}finally{clearTimeout(m),l=void 0}a||(h=v?0:h+1,t(!v),u=setTimeout(()=>{document.visibilityState!=="hidden"&&d()},v?1e4:Math.min(2e3*2**Math.min(h-1,4),3e4)))}const p=()=>{document.visibilityState!=="hidden"&&d()};return i.current=()=>{d()},window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),d(),()=>{a=!0,clearTimeout(u),l?.abort(),i.current=()=>{},window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{style:{display:"contents"},inert:e||void 0,children:n}),e&&jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("section",{role:"alertdialog","aria-modal":"true","aria-labelledby":"xpod-connection-title","aria-describedby":"xpod-connection-description",className:"w-full max-w-sm rounded-2xl border bg-background p-6 shadow-lg",children:[jsxRuntimeExports.jsx("h2",{id:"xpod-connection-title",className:"text-lg font-semibold",children:"Xpod 连接中断"}),jsxRuntimeExports.jsx("p",{id:"xpod-connection-description",className:"mt-3 text-sm text-muted-foreground",children:"暂时无法连接 Xpod,正在自动重连。登录状态和当前页面已保留,恢复后即可继续。"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"刚才未完成的操作不会自动重试,请在连接恢复后确认结果。"}),jsxRuntimeExports.jsx("button",{ref:s,type:"button",onKeyDown:a=>{a.key==="Tab"&&a.preventDefault()},onClick:()=>i.current(),className:"mt-5 w-full rounded-lg bg-primary px-4 py-2 text-primary-foreground",children:"立即重试"})]})})]})}function XpodDesktopNavigationBridge(){const n=useNavigate();return reactExports.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const t=new URL(e,window.location.origin);t.origin===window.location.origin&&n(`${t.pathname}${t.search}${t.hash}`)}),[n]),null}const client_id="https://id.undefineds.co/app/xpod-desktop-client.json",desktopClient={client_id};function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[a,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),[v,S]=reactExports.useState(),[E,w]=reactExports.useState(0),[A,C]=reactExports.useState(),T=reactExports.useRef(a),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),M=reactExports.useCallback(async(Ae,ke)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):ke===void 0?t.session.fetch(Ae):t.session.fetch(Ae,ke),[t.session]),$=reactExports.useMemo(()=>a.status==="authenticated"?t.session.createAuthenticatedFetch(a.webId):void 0,[t.session,a]),G=reactExports.useCallback(async(Ae,ke)=>{if(!$||F.current)throw REJECTED_SESSION_FETCH_ERROR;return ke===void 0?$(Ae):$(Ae,ke)},[$]),fe=reactExports.useCallback(()=>{if(P.current)return P.current;const Ae=(async()=>{try{await t.session.logout();const ke=t.session.getSnapshot();(ke.status!=="authenticated"||isCurrentXpodSessionSnapshot(ke,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const ke={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=ke,l(ke),h(void 0),p(void 0),m(void 0),S(void 0),C(void 0)}})().finally(()=>{P.current===Ae&&(P.current=void 0)});return P.current=Ae,Ae},[t,i.issuer,i.selectedStorage]),B=reactExports.useMemo(()=>({...t.session,fetch:M,getSnapshot:()=>T.current}),[M,t.session]);reactExports.useEffect(()=>{const Ae=he=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(he,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,fe();return}he.status==="authenticated"&&(F.current=!1);const ce=T.current;T.current=he,l(he),h(Oe),he.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),he.status!=="expired"&&m(void 0),S(void 0),C(void 0),t.pod.clear()):ce!==he&&(p(void 0),m(void 0),S(void 0),C(void 0),t.pod.clear(ce.status==="authenticated"?{webId:ce.webId}:void 0))},ke=t.session.subscribe(Ae);return Ae(t.session.getSnapshot()),ke},[fe,t,i]),reactExports.useEffect(()=>{F.current&&fe()},[fe]),reactExports.useEffect(()=>{if(a.status!=="authenticated")return;let Ae=!1;const ke=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:a.webId}),he={webId:a.webId,...ke?{podUrl:ke.storageUrl}:{},fetch:G};return(async()=>{try{const Oe=await t.pod.open(he),ce=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(Ae)return;if(t.setLocalPodRoute?.(ce),!Ae){if(ke&&(Oe.webId!==ke.webId||!sameUrl$2(Oe.podUrl,ke.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),m(void 0),S({webId:a.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),m(ke??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){Ae||S({webId:a.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{Ae=!0}},[G,E,t,i.selectedStorage,a]);const ee=reactExports.useCallback(()=>{S(void 0),w(Ae=>Ae+1)},[]),Se=a.status==="authenticated"?a.webId:void 0;reactExports.useEffect(()=>{if(!Se)return;let Ae=!1;return discoverAiClientConfigurationCapability(G).then(ke=>{!Ae&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===Se&&C(ke)}),()=>{Ae=!0}},[G,Se,t]);const re=reactExports.useMemo(()=>{const Ae=u??t.getIssuer(),ke=a.status==="authenticated"&&v?.webId===a.webId?v:void 0,he=snapshotToState(a,d,Ae);return{session:B,pod:t.pod,fetch:G,state:he.status==="error"?{...he,error:safeAuthError(he.error)}:he,webId:he.webId,podUrl:he.podUrl,issuer:he.issuer,currentPod:d,selectedStorage:g,...ke?{podError:ke}:{},retryPodOpen:ee,aiClientConfiguration:A,resolveLocalUrl:Oe=>t.resolveLocalUrl(Oe),login:async Oe=>{const ce=normalizeXpodLoginTransaction(Oe),Ue=await resolveXpodLoginContext(ce.route.identityProvider.url,fetch),O=Ue.oidcIssuer;if(!O)throw new TypeError("Xpod login route has no valid issuer");const W=new URL("/auth/callback",window.location.origin),de=globalThis.xpodDesktop?desktopClient.client_id:void 0;try{await t.session.login({...de?{clientId:de}:{},oidcIssuer:O,redirectUrl:W.toString(),handleRedirect:te=>{t.setIssuer(O),h(O);const Te=new URL(te);ce.prompt?Te.searchParams.set("prompt",ce.prompt):de&&Te.searchParams.get("prompt")==="consent"&&Te.searchParams.delete("prompt"),window.location.assign(Ue.provisionCode?withXpodProvisionScope(Te.href,Ue.provisionCode):Te.href)}}),t.setIssuer(O),h(O)}catch(te){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",te,te instanceof Error?te.cause:void 0),te}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),m(void 0),C(void 0)}}},[A,G,d,B,u,v,ee,t,i,g,a]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:B,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:re,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),a=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(a)},[a]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:a,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,a]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function DesktopLoginReturnAction(){const[n,e]=reactExports.useState(!1),[t,i]=reactExports.useState(!1),s=reactExports.useRef(!1);if(!window.xpodDesktop?.cancelLogin)return null;const a=async()=>{const l=window.xpodDesktop;if(!(s.current||!l?.cancelLogin)){s.current=!0,e(!0),i(!1);try{await l.cancelLogin()}catch{i(!0)}finally{s.current=!1,e(!1)}}};return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[t&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"返回应用未完成,请重试。"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:"w-full",disabled:n,"aria-busy":n,onClick:()=>{a()},children:n?"正在返回…":"返回应用"})]})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodAccountPageCopy={forgotPassword:"忘记密码?"},xpodRegistrationCopy={usernameRequired:"请填写 Pod 名称",usernameLength:"Pod 名称需为 3-63 个字符",usernameCharset:"Pod 名称只能包含小写字母、数字和连字符",usernameHyphen:"Pod 名称不能以连字符开头或结尾",emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。",podNameTaken:"Pod 名称已被占用,请换一个。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const a=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(a||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:a}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[h,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(M,$)=>{const G=await fetch(typeof M=="string"||M instanceof URL?scopeAccountUrl(M):M,$);if(!G.ok)throw new PasswordLoginStatusError(G.status);return G}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await a();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},w=C=>{u(C),h&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:w,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:h?{form:h}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),a=e??s.accountState,l=t??s.retry;return a.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):a.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):a.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):a.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:a.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[a,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),w=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),M=P.displayName,$=initialsFor(P.displayName),G=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),fe=accountHandle(P.username,i?void 0:F?.id,G),B=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,Se=e?.currentPod,re=reactExports.useMemo(()=>B?podNameFromUrl(B):void 0,[B]),Ae=e?.state.status==="authenticated"&&!!(G&&B&&ee&&Se)&&ee?.webId===G&&sameUrl$1(ee?.storageUrl??"",B??"")&&Se?.webId===G&&sameUrl$1(Se?.podUrl??"",B??""),ke=s,he=a&&ke,Oe=reactExports.useCallback(W=>{l(W),W||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!he)return;const W=()=>{const de=S.current;de&&m(accountCardPosition(de.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return W(),window.addEventListener("resize",W),window.addEventListener("scroll",W,!0),window.visualViewport?.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),window.visualViewport?.removeEventListener("resize",W)}},[he]),reactExports.useEffect(()=>{if(!ke){clearAccountCardRequest();return}if(!he)return;const W=te=>{const Te=te.target;Te instanceof Node&&(v.current?.contains(Te)||S.current?.contains(Te)||Oe(!1))},de=te=>{te.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",W),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointerdown",W),document.removeEventListener("keydown",de)}},[ke,he,Oe]),reactExports.useEffect(()=>{!he||!g||v.current?.focus({preventScroll:!0})},[he,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const ce=async()=>{h("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{h(void 0)}},Ue=async()=>{h("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const W=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);W.searchParams.set("xpod-login","switch"),window.location.assign(W)}}),Oe(!1)}catch{}finally{h(void 0)}},O=async()=>{const W=P.webId??fe;try{await navigator.clipboard.writeText(W),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return ke?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${M}`:"Open account menu","aria-expanded":he,"aria-controls":he?w:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ae?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!he),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?M:"Not signed in"})]}),he&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:w,role:"region",tabIndex:-1,"aria-label":s?M:"Xpod account","data-avatar-card":"true","data-selected-pod-url":B,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:$})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:M}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:fe}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{O()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ae?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ae?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(re)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(B)]})]}),Ae?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{Ue()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{ce()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const a=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(a,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-D983R1FV.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-D983R1FV.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-D983R1FV.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-CG9RelJA.js"),__vite__mapDeps([8,9,10,2,11,3,12,13,6]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-CBdRahCF.js"),__vite__mapDeps([14,2,10,9,11]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-8qtVxnzC.js"),__vite__mapDeps([15,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-CYyLOlQU.js"),__vite__mapDeps([16,1,17])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0;return reactExports.useEffect(()=>{!i&&!t.current&&(t.current=!0,n())},[i,n]),jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),a=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const h=p=>{try{return a.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=a.readSinglePending();m&&a.cancel(m.id)}catch{}return a.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=h(S);u=!0;try{await n.runtime.login(E)}catch(w){try{a.cancel(E.id)}catch{}throw w}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=a.readSinglePending();p&&a.cancel(p.id)},readPending:()=>a.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),a=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,h]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{a.cancelLogin()}catch{}},[u,a]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[w,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),M=reactExports.useRef(!1),$=reactExports.useCallback(O=>{console.error("[WebIdAuthBoundary] authentication action failed",O),v(actionFailureMessage)},[]),G=reactExports.useCallback(O=>{const W=++C.current;v(void 0),E(!0),O().catch(de=>{W===C.current&&$(de)}).finally(()=>{W===C.current&&E(!1)})},[$]),fe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),h(!1),v(void 0),A({})},[]),B=reactExports.useCallback(()=>{if(!w)return;const O=w.prompt;setXpodLoginCancelled(!1),h(!1),A(void 0),G(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await a.startLogin(void 0,void 0,O)})},[a,w,G,t.session,l]),ee=()=>{if(T){re();return}d.status==="authenticated"?t.retryPodOpen?.():fe()},Se=()=>{if(!T){try{a.cancelLogin()}catch{}setXpodLoginCancelled(!0),h(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},re=()=>G(async()=>{F(!0);const O=()=>{setXpodLoginCancelled(!1),h(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:O}):(await t.logout(),O())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch($))},[u,$,t.session,t.state.status]),reactExports.useEffect(()=>{u||w||s||S||T||!e||M.current||d.status!=="anonymous"||(M.current=!0,fe())},[u,s,e,S,w,fe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(w)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:B});const Ae="remembered"in d?d.remembered:void 0,ke=d.status==="restoring",he=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let ce,Ue;return!u&&t.state.status==="error"&&t.state.error.name==="SolidSessionPendingError"?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:"上次登录尚未结束,请刷新页面后重新登录。",primaryLabel:"刷新页面",onPrimary:()=>window.location.reload(),secondaryLabel:"返回登录",onSecondary:Se}):m?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:Se}):ke?(Ue=Ae?void 0:Oe,ce=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ae?.displayName,avatarUrl:Ae?.avatarUrl,label:rememberedCopy.restoringLabel})):he?ce=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:Se}):d.status==="authenticated"?ce=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:re}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ae&&!u?ce=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ae.displayName,avatarUrl:Ae.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ae.displayName):rememberedCopy.continueLabel(Ae.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:fe,onReauthenticate:ee,onSwitchAccount:re})]}):!u&&(d.status==="error"||d.status==="expired")?ce=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:Se}):ce=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:fe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ue,children:ce})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-DwyITxt7.js").then(n=>n.M),__vite__mapDeps([18,19,20,21,11,4,5,22,12]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-fe-xMIXa.js"),__vite__mapDeps([23,9,24,19,20,21,11]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-BOvUH4yr.js").then(n=>n.M),__vite__mapDeps([25,24,19,20,21,22,4])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-BGnkfMuU.js"),__vite__mapDeps([26,25,24,19,20,21,22,4])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-2_a6ezzj.js"),__vite__mapDeps([27,25,24,19,20,21,22,4])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-42Jups0j.js"),__vite__mapDeps([28,25,24,19,20,21,22,4])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-BZJ6vWkg.js"),__vite__mapDeps([29,7,1,30,9,11]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-xm08UhXP.js"),__vite__mapDeps([31,1,30,19,13,17,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))}])]},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}function createCallbackNavigation({location:n,history:e}){return{origin:n.origin,replace(t){const i=new URL(t,n.origin);if(i.origin===n.origin&&isProductPath(i.pathname)){e.replaceState({},"",`${i.pathname}${i.search}${i.hash}`);return}n.replace(i.href)}}}function resolveCallbackProductDestination(n,e){try{const t=new URL(n,e);if(t.origin!==e)return;const i=productAppForPathname(t.pathname);return i?{app:i,pathname:t.pathname,target:`${t.pathname}${t.search}${t.hash}`}:void 0}catch{return}}function isProductPath(n){return productAppForPathname(n)!==void 0}function productAppForPathname(n){return productSurfaceRoots.find(({basename:e})=>n===e||n.startsWith(`${e}/`))?.app}initializeXpodTheme();const runtime=getXpodSolidRuntimeValue(),callbackLocation=createCallbackNavigation({location:window.location,history:window.history});function renderRedirected(n){const e=resolveCallbackProductDestination(n.destination,window.location.origin);return e?(`${window.location.pathname}${window.location.search}${window.location.hash}`!==e.target&&window.history.replaceState({},"",e.target),jsxRuntimeExports.jsx(XpodShellApp,{runtime,initialPathname:e.pathname},e.target)):jsxRuntimeExports.jsx("main",{role:"status","aria-live":"polite",children:"Sign-in complete. Opening Xpod…"})}clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodOidcCallbackApp,{runtime,location:callbackLocation,renderRedirected})}));export{dispatchDiscreteCustomEvent as $,hasInvalidWebIdWhitespace as A,Button as B,Card as C,Database as D,xpodRegistrationCopy as E,resolveProvisionCodeForPodCreate as F,scopeAccountUrl as G,buildPodCreatePayload as H,getAccountSessionToken as I,accountTokenHeaders as J,resolveProvisionScope as K,storageUrlBelongsToRoot as L,prepareProvisionedPod as M,NavLink as N,Outlet as O,Primitive as P,useAuth as Q,RefreshCw as R,resolveProvisionCodeForCurrentScope as S,Sparkles as T,Gauge as U,reactDomExports as V,useCallbackRef as W,X,toast as Y,Copy as Z,React4 as _,CardHeader as a,clsx as a0,Link as a1,getDefaultExportFromCjs as a2,createLucideIcon$1 as a3,createSlottable as a4,getLinkedResourceUrlAll as a5,acp as a6,internal_cloneResource as a7,getSolidDataset as a8,freeze as a9,AvatarFallback as aA,LoaderCircle$1 as aB,Input as aC,LoginFailureView as aD,LoginConnectingView as aE,Label as aF,dismissToast as aG,controlFocusClass as aH,Toaster as aI,AuthContext as aJ,createXpodLoginController as aK,requireBuffer as aL,requireLink as aM,getAugmentedNamespace as aN,requireBrowser$2 as aO,requireSparql as aP,requireEvents as aQ,requireBrowser$3 as aR,requireString_decoder as aS,bufferExports as aT,commonjsGlobal as aU,getSourceUrl as aa,getResourceInfo as ab,getSourceIri as ac,getThingAll as ad,getIriAll as ae,rdf$3 as af,acl as ag,setThing as ah,setIri as ai,removeIri as aj,removeAll as ak,createThing as al,addIri as am,removeThing as an,subjectToRdfJsQuads as ao,DataFactory$1 as ap,getIri as aq,saveSolidDatasetAt as ar,createSolidDataset as as,foaf as at,getThing as au,getUrlAll as av,buildThing as aw,__vitePreload as ax,Avatar as ay,AvatarImage as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,credentialDescriptor as h,interactiveFocusClass as i,jsxRuntimeExports as j,credentialResource as k,useLayoutEffect2 as l,useComposedRefs as m,createContextScope as n,createSlot as o,aiConfigModelRef as p,aiProviderResource as q,reactExports as r,aiModelResource as s,configureSparqlEngine as t,useXpodSolidRuntime as u,useLocation as v,handleListNavigationKeyDown as w,getListNavItemClass as x,resolveHostedAccountControlUrl as y,storedAccountTokenHeaders as z};
|