@undefineds.co/xpod 0.4.10 → 0.4.12
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 +5 -1
- package/config/notifications.json +68 -0
- package/config/xpod.base.json +9 -11
- package/dist/ai/service/AiCredentialSecret.d.ts +30 -0
- package/dist/ai/service/AiCredentialSecret.js +120 -0
- package/dist/ai/service/CredentialReaderImpl.d.ts +18 -0
- package/dist/ai/service/CredentialReaderImpl.js +81 -5
- package/dist/ai/service/CredentialReaderImpl.jsonld +42 -2
- package/dist/ai/service/EmbeddingModelPolicy.d.ts +79 -0
- package/dist/ai/service/EmbeddingModelPolicy.js +134 -0
- package/dist/ai/service/EmbeddingProviderError.js +6 -0
- package/dist/ai/service/EmbeddingServiceImpl.d.ts +13 -1
- package/dist/ai/service/EmbeddingServiceImpl.js +18 -5
- package/dist/ai/service/EmbeddingServiceImpl.jsonld +35 -0
- package/dist/ai/service/index.d.ts +2 -0
- package/dist/ai/service/index.js +2 -0
- package/dist/api/ai-gateway/connect/index.d.ts +20 -2
- package/dist/api/ai-gateway/connect/index.js +162 -16
- package/dist/api/ai-gateway/credentials/AiCredentialSecretDecoder.d.ts +12 -0
- package/dist/api/ai-gateway/credentials/AiCredentialSecretDecoder.js +30 -0
- package/dist/api/ai-gateway/errors.d.ts +1 -1
- package/dist/api/ai-gateway/models/GatewayEmbeddingModelCatalog.d.ts +11 -0
- package/dist/api/ai-gateway/models/GatewayEmbeddingModelCatalog.js +31 -0
- package/dist/api/ai-gateway/models/PodModelSelectionRepository.js +7 -3
- package/dist/api/ai-gateway/models/ProviderCustomModelsService.d.ts +18 -0
- package/dist/api/ai-gateway/models/ProviderCustomModelsService.js +23 -0
- package/dist/api/ai-gateway/models/ProviderModelDiscoveryAdapters.d.ts +3 -1
- package/dist/api/ai-gateway/models/ProviderModelDiscoveryAdapters.js +2 -45
- package/dist/api/ai-gateway/models/ProviderModelSelectionService.d.ts +10 -0
- package/dist/api/ai-gateway/models/ProviderModelSelectionService.js +57 -20
- package/dist/api/ai-gateway/models/ProviderModelType.d.ts +28 -0
- package/dist/api/ai-gateway/models/ProviderModelType.js +34 -0
- package/dist/api/ai-gateway/models/ProviderModelsAdapter.d.ts +10 -0
- package/dist/api/ai-gateway/models/ProviderModelsAdapter.js +3 -4
- package/dist/api/ai-gateway/models/index.d.ts +1 -0
- package/dist/api/ai-gateway/models/index.js +3 -1
- package/dist/api/ai-gateway/providers/CustomRuntimeAdapter.d.ts +7 -0
- package/dist/api/ai-gateway/providers/CustomRuntimeAdapter.js +9 -2
- package/dist/api/ai-gateway/providers/ModelsDevCatalog.d.ts +7 -1
- package/dist/api/ai-gateway/providers/ModelsDevCatalog.js +4 -10
- package/dist/api/ai-gateway/providers/ProviderRegistry.d.ts +107 -0
- package/dist/api/ai-gateway/providers/ProviderRegistry.js +244 -21
- package/dist/api/ai-gateway/providers/ProviderRuntimeRegistry.d.ts +5 -0
- package/dist/api/ai-gateway/providers/ProviderRuntimeRegistry.js +5 -1
- package/dist/api/ai-gateway/quota/SubscriptionQuotaAdapters.d.ts +12 -4
- package/dist/api/ai-gateway/quota/SubscriptionQuotaAdapters.js +11 -11
- package/dist/api/ai-gateway/routing/ModelRouter.d.ts +14 -0
- package/dist/api/ai-gateway/routing/ModelRouter.js +43 -4
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.d.ts +9 -1
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.js +3 -27
- package/dist/api/auth/ClientCredentialsAuthenticator.d.ts +0 -1
- package/dist/api/auth/ClientCredentialsAuthenticator.js +0 -3
- package/dist/api/auth/index.d.ts +1 -0
- package/dist/api/auth/index.js +1 -1
- package/dist/api/chatkit/pod-store.d.ts +31 -0
- package/dist/api/chatkit/pod-store.js +132 -8
- package/dist/api/container/common.js +24 -4
- package/dist/api/container/routes.js +17 -2
- package/dist/api/container/types.d.ts +3 -1
- package/dist/api/handlers/AdminHandler.d.ts +13 -0
- package/dist/api/handlers/AdminHandler.js +47 -18
- package/dist/api/handlers/AiConfigHandler.d.ts +6 -0
- package/dist/api/handlers/AiConfigHandler.js +28 -0
- package/dist/api/handlers/AiGatewayManagementHandler.js +36 -0
- package/dist/api/runs/RdfRunContextRetriever.d.ts +14 -0
- package/dist/api/runs/RdfRunContextRetriever.js +41 -5
- package/dist/api/runtime.js +2 -1
- package/dist/cli/commands/secret.d.ts +1 -0
- package/dist/cli/commands/secret.js +25 -7
- package/dist/components/components.jsonld +3 -1
- package/dist/components/context.jsonld +53 -1
- package/dist/http/SubgraphSparqlHttpHandler.d.ts +59 -2
- package/dist/http/SubgraphSparqlHttpHandler.js +145 -13
- package/dist/http/SubgraphSparqlHttpHandler.jsonld +37 -0
- package/dist/identity/drizzle/AccountRoleRepository.d.ts +30 -2
- package/dist/identity/drizzle/AccountRoleRepository.js +163 -15
- package/dist/identity/drizzle/EdgeNodeRepository.d.ts +0 -12
- package/dist/identity/drizzle/EdgeNodeRepository.js +5 -13
- package/dist/identity/drizzle/PodLookupRepository.d.ts +58 -4
- package/dist/identity/drizzle/PodLookupRepository.js +248 -105
- package/dist/identity/drizzle/db.d.ts +19 -0
- package/dist/identity/drizzle/db.js +39 -4
- package/dist/index.d.ts +2 -1
- package/dist/index.js +7 -3
- package/dist/logging/log-file.d.ts +17 -0
- package/dist/logging/log-file.js +69 -0
- package/dist/main.js +2 -1
- package/dist/notifications/NotificationChannelSweeper.d.ts +50 -0
- package/dist/notifications/NotificationChannelSweeper.js +131 -0
- package/dist/notifications/NotificationChannelSweeper.jsonld +136 -0
- package/dist/notifications/ReclaimingWebSocket2023Storer.d.ts +25 -0
- package/dist/notifications/ReclaimingWebSocket2023Storer.js +56 -0
- package/dist/notifications/ReclaimingWebSocket2023Storer.jsonld +77 -0
- package/dist/notifications/index.d.ts +2 -0
- package/dist/notifications/index.js +2 -0
- package/dist/runtime/Proxy.d.ts +37 -0
- package/dist/runtime/Proxy.js +88 -16
- package/dist/runtime/bootstrap.js +2 -1
- package/dist/runtime/upgrade/BunNativeUpgradeRelay.d.ts +116 -0
- package/dist/runtime/upgrade/BunNativeUpgradeRelay.js +423 -0
- package/dist/runtime/upgrade/UpgradeHandshake.d.ts +63 -0
- package/dist/runtime/upgrade/UpgradeHandshake.js +199 -0
- package/dist/runtime/upgrade/WebSocketFrames.d.ts +67 -0
- package/dist/runtime/upgrade/WebSocketFrames.js +224 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.js +8 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.d.ts +11 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiAuthorizationActions.js +27 -10
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.d.ts +7 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiClientConfigurationSection.js +13 -11
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectDialog.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsList.js +10 -6
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMain.js +29 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsMainHeader.js +18 -3
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +16 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +92 -20
- package/node_modules/@undefineds.co/ai-connections/dist/AiCopyButton.d.ts +35 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiCopyButton.js +45 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +71 -11
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialRow.js +9 -7
- package/node_modules/@undefineds.co/ai-connections/dist/AiEndpointList.d.ts +23 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiEndpointList.js +24 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +13 -4
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +35 -38
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.d.ts +21 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayModelsSection.js +51 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiInfoTooltip.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiInfoTooltip.js +16 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.d.ts +175 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiModelCatalog.js +133 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +13 -64
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.d.ts +21 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +12 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiRowAction.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiRowAction.js +12 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiSortableCredentialList.js +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/ai-connections-client.d.ts +7 -0
- package/node_modules/@undefineds.co/ai-connections/dist/ai-connections-client.js +6 -0
- package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.d.ts +36 -5
- package/node_modules/@undefineds.co/ai-connections/dist/authorization-methods.js +52 -9
- package/node_modules/@undefineds.co/ai-connections/dist/client/normalize.js +30 -3
- package/node_modules/@undefineds.co/ai-connections/dist/client/types.d.ts +21 -1
- package/node_modules/@undefineds.co/ai-connections/dist/client-config/base-adapter.d.ts +1 -3
- package/node_modules/@undefineds.co/ai-connections/dist/client-config/base-adapter.js +3 -7
- package/node_modules/@undefineds.co/ai-connections/dist/client-config/index.cjs +9 -7
- package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.d.ts +46 -0
- package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.js +231 -0
- package/node_modules/@undefineds.co/ai-connections/dist/collections.d.ts +119 -0
- package/node_modules/@undefineds.co/ai-connections/dist/collections.js +173 -0
- package/node_modules/@undefineds.co/ai-connections/dist/controller.d.ts +71 -5
- package/node_modules/@undefineds.co/ai-connections/dist/controller.js +285 -16
- package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.d.ts +5 -0
- package/node_modules/@undefineds.co/ai-connections/dist/credential-labels.js +8 -3
- package/node_modules/@undefineds.co/ai-connections/dist/credential-storage.d.ts +59 -0
- package/node_modules/@undefineds.co/ai-connections/dist/credential-storage.js +131 -0
- package/node_modules/@undefineds.co/ai-connections/dist/endpoint-urls.d.ts +15 -0
- package/node_modules/@undefineds.co/ai-connections/dist/endpoint-urls.js +20 -0
- package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.d.ts +14 -0
- package/node_modules/@undefineds.co/ai-connections/dist/gateway-endpoints.js +20 -0
- package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +8 -0
- package/node_modules/@undefineds.co/ai-connections/dist/index.js +8 -0
- package/node_modules/@undefineds.co/ai-connections/dist/manifest.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.d.ts +14 -0
- package/node_modules/@undefineds.co/ai-connections/dist/offering-endpoints.js +17 -0
- package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.cjs +68 -1
- package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.d.ts +75 -1
- package/node_modules/@undefineds.co/ai-connections/dist/provider-catalog.js +119 -0
- package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.d.ts +5 -0
- package/node_modules/@undefineds.co/ai-connections/dist/provider-visuals.js +5 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +2 -27
- package/node_modules/@undefineds.co/ai-connections/package.json +1 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/manifest.d.ts +1 -1
- package/node_modules/@undefineds.co/extension-sdk/dist/manifest.js +2 -0
- package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +150 -0
- package/node_modules/@undefineds.co/extension-sdk/package.json +2 -1
- package/node_modules/@undefineds.co/models/README.md +1 -1
- package/node_modules/@undefineds.co/models/dist/ai-config/index.d.ts +3 -3
- package/node_modules/@undefineds.co/models/dist/ai-gateway.schema.d.ts +5 -0
- package/node_modules/@undefineds.co/models/dist/ai-gateway.schema.js +9 -0
- package/node_modules/@undefineds.co/models/dist/ai-runtime.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/approval.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/audit.presentation.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/capture.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/chat-project.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/chat.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/control-request.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/conversation-share.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/credential.schema.d.ts +12 -0
- package/node_modules/@undefineds.co/models/dist/credential.schema.js +15 -1
- package/node_modules/@undefineds.co/models/dist/discovery/index.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/discovery/providers.json +248 -7
- package/node_modules/@undefineds.co/models/dist/discovery/types.d.ts +31 -0
- package/node_modules/@undefineds.co/models/dist/extension/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/favorite/index.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/fixtures/contracts-chat-contact.d.ts +5 -5
- package/node_modules/@undefineds.co/models/dist/import/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/index.d.ts +73 -73
- package/node_modules/@undefineds.co/models/dist/index.js +1 -1
- package/node_modules/@undefineds.co/models/dist/input-request.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/knowledge/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/message.repository.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/namespaces.js +5 -0
- package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.d.ts +4815 -26
- package/node_modules/@undefineds.co/models/dist/pod-storage-descriptor.js +482 -132
- package/node_modules/@undefineds.co/models/dist/schema.d.ts +4 -0
- package/node_modules/@undefineds.co/models/dist/session/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/settings/index.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/sidecar/persistence-mapping.d.ts +5 -5
- package/node_modules/@undefineds.co/models/dist/thread.repository.d.ts +2 -2
- package/node_modules/@undefineds.co/models/dist/types/message-block.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/vocab/_namespaces.d.ts +1 -1
- package/node_modules/@undefineds.co/models/dist/vocab/index.d.ts +10 -10
- package/node_modules/@undefineds.co/models/dist/vocab/sidecar.vocab.d.ts +1 -0
- package/node_modules/@undefineds.co/models/dist/vocab/sidecar.vocab.js +1 -0
- package/node_modules/@undefineds.co/models/package.json +4 -2
- package/node_modules/@undefineds.co/pod-collections/README.md +71 -0
- package/node_modules/@undefineds.co/pod-collections/dist/diff.d.ts +85 -0
- package/node_modules/@undefineds.co/pod-collections/dist/diff.js +166 -0
- package/node_modules/@undefineds.co/pod-collections/dist/feed.d.ts +17 -0
- package/node_modules/@undefineds.co/pod-collections/dist/feed.js +27 -0
- package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +1042 -0
- package/node_modules/@undefineds.co/pod-collections/dist/index.d.ts +37 -0
- package/node_modules/@undefineds.co/pod-collections/dist/index.js +89 -0
- package/node_modules/@undefineds.co/pod-collections/dist/layout.d.ts +75 -0
- package/node_modules/@undefineds.co/pod-collections/dist/layout.js +173 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +78 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +287 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.d.ts +83 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +273 -0
- package/node_modules/@undefineds.co/pod-collections/dist/react.d.ts +21 -0
- package/node_modules/@undefineds.co/pod-collections/dist/react.js +22 -0
- package/node_modules/@undefineds.co/pod-collections/dist/read.d.ts +65 -0
- package/node_modules/@undefineds.co/pod-collections/dist/read.js +31 -0
- package/node_modules/@undefineds.co/pod-collections/dist/sync.d.ts +66 -0
- package/node_modules/@undefineds.co/pod-collections/dist/sync.js +260 -0
- package/node_modules/@undefineds.co/pod-collections/dist/types.d.ts +155 -0
- package/node_modules/@undefineds.co/pod-collections/dist/types.js +9 -0
- package/node_modules/@undefineds.co/pod-collections/package.json +42 -0
- package/node_modules/@undefineds.co/shared-ui/dist/index.d.ts +0 -1
- package/node_modules/@undefineds.co/shared-ui/dist/index.js +0 -1
- package/package.json +15 -7
- package/static/app/assets/main.css +1 -1
- package/static/app/assets/main.js +12 -13
- package/static/auth-callback/assets/AiConfigContext-DnQs1ZpW.js +1 -0
- package/static/auth-callback/assets/AiConfigPage-DOtvlxH0.js +1 -0
- package/static/auth-callback/assets/DocumentProcessingPanel-BS2voQgL.js +1 -0
- package/static/auth-callback/assets/IndexLifecyclePanel-Cvt0cJtN.js +1 -0
- package/static/auth-callback/assets/{IndexSubjectPanel-C4YG0whI.js → IndexSubjectPanel-Dhf01GqF.js} +1 -1
- package/static/auth-callback/assets/ModelAssignmentsPanel-BJutWaAF.js +1 -0
- package/static/auth-callback/assets/ModelsPage-BRS0sje3.js +11 -0
- package/static/auth-callback/assets/{NetworkPage-Cbdn_P1e.js → NetworkPage-B3qBfANA.js} +2 -2
- package/static/auth-callback/assets/{PaneListHeader-jy70Q00L.js → PaneListHeader-QQeJGTp4.js} +1 -1
- package/static/auth-callback/assets/SearchIndexingPanel-MyNUSEwT.js +1 -0
- package/static/auth-callback/assets/{StatusSubjectPanel-hfjoB5aS.js → StatusSubjectPanel-DQkEVsFs.js} +1 -1
- package/static/{settings/assets/StatusWorkspace-CKD_Rzdr.js → auth-callback/assets/StatusWorkspace-Dkv63Uwk.js} +1 -1
- package/static/auth-callback/assets/SystemSettingsPage-TIsUfX5d.js +1 -0
- package/static/auth-callback/assets/SystemSettingsSubjectPanel-BJWEt2-7.js +33 -0
- package/static/auth-callback/assets/XpodAiConnectionsPodStore-BJiXm-PF.js +3 -0
- package/static/auth-callback/assets/{activity-BcsZZxxw.js → activity-5hNeNKnL.js} +1 -1
- package/static/auth-callback/assets/admin-C6qCRFiY.js +1 -0
- package/static/auth-callback/assets/ai-connections-CryuHGKW.js +1 -0
- package/static/auth-callback/assets/{auth-callback-atKg_oig.js → auth-callback-CAFZ3R0B.js} +80 -84
- package/static/auth-callback/assets/auth-callback-rk080mvG.css +1 -0
- package/static/auth-callback/assets/{badge-BWbRHThQ.js → badge-CAIPI0CB.js} +1 -1
- package/static/auth-callback/assets/collection-runtime-D9s7h9YA.js +1 -0
- package/static/auth-callback/assets/dialog-BjA109aX.js +1 -0
- package/static/auth-callback/assets/{download-BmvG1Vya.js → download-B3Up5W2G.js} +1 -1
- package/static/auth-callback/assets/{external-link-DZ34d3g3.js → external-link-BTXgSPzB.js} +1 -1
- package/static/auth-callback/assets/index-BppXlxcp.js +41 -0
- package/static/auth-callback/assets/index-CirW4CJf.js +1 -0
- package/static/auth-callback/assets/index-DlLYWOhw.js +4 -0
- package/static/auth-callback/assets/{index-browser-B9Z7GU-T.js → index-browser-DtU38ni3.js} +1 -1
- package/static/auth-callback/assets/{key-round-tjP76Se-.js → key-round-CQCOrZ7x.js} +1 -1
- package/static/auth-callback/assets/layout-DB3pMyTl.js +1 -0
- package/static/auth-callback/assets/pod-collections-host-KnnGFZHL.js +8 -0
- package/static/auth-callback/assets/{rotate-ccw-C_L5ZLx1.js → rotate-ccw-C1zM2KtS.js} +1 -1
- package/static/auth-callback/assets/settings-projection-CUkyprDQ.js +1 -0
- package/static/auth-callback/assets/{skeleton-C7tGDQIs.js → skeleton-Cqp7_M9-.js} +1 -1
- package/static/auth-callback/assets/{waypoints-VMNQlWdU.js → waypoints-Bj6gAUSQ.js} +1 -1
- package/static/auth-callback/assets/{workspace-layout-SAp6BtYK.js → workspace-layout-DK8mDzrY.js} +1 -1
- package/static/auth-callback/auth-callback.html +2 -2
- package/static/dashboard/assets/AiConfigContext-BsE7MqX8.js +1 -0
- package/static/dashboard/assets/AiConfigPage-DvM-lRXa.js +1 -0
- package/static/dashboard/assets/DocumentProcessingPanel-BPfdlfuf.js +1 -0
- package/static/dashboard/assets/IndexLifecyclePanel--m0AGxvh.js +1 -0
- package/static/dashboard/assets/{IndexSubjectPanel-DQFPP6-p.js → IndexSubjectPanel-Bb7m1k3d.js} +1 -1
- package/static/dashboard/assets/ModelAssignmentsPanel-BLi_zbMa.js +1 -0
- package/static/dashboard/assets/ModelsPage-CxdpgnfR.js +11 -0
- package/static/dashboard/assets/{NetworkPage-CHQ3YxIB.js → NetworkPage-BAIPw-D_.js} +2 -2
- package/static/dashboard/assets/{PaneListHeader-DsXemAdR.js → PaneListHeader-BBCMei0r.js} +1 -1
- package/static/dashboard/assets/SearchIndexingPanel-Ck4Y-xjR.js +1 -0
- package/static/dashboard/assets/{StatusSubjectPanel-D3PGEYT4.js → StatusSubjectPanel-D1KWfAXE.js} +1 -1
- package/static/dashboard/assets/{StatusWorkspace-BcpePYUW.js → StatusWorkspace-JbA5gzXx.js} +1 -1
- package/static/dashboard/assets/SystemSettingsPage-BbwQWsSR.js +1 -0
- package/static/dashboard/assets/SystemSettingsSubjectPanel-N117nMt5.js +33 -0
- package/static/dashboard/assets/XpodAiConnectionsPodStore-CdDOb4SV.js +18 -0
- package/static/dashboard/assets/{activity-j5zrznu-.js → activity-DX1I96o_.js} +1 -1
- package/static/dashboard/assets/admin-C6qCRFiY.js +1 -0
- package/static/dashboard/assets/ai-connections-DwCRqOQa.js +1 -0
- package/static/dashboard/assets/{badge-CzeBdG7h.js → badge-k2vhtDqH.js} +1 -1
- package/static/dashboard/assets/collection-runtime-BFQ8teQJ.js +1 -0
- package/static/dashboard/assets/{dashboard-D-xANHk1.js → dashboard-DWZ-fmCT.js} +105 -109
- package/static/dashboard/assets/dashboard-rk080mvG.css +1 -0
- package/static/dashboard/assets/dialog-1CCw-iHT.js +1 -0
- package/static/dashboard/assets/{download-IcNdEZWi.js → download-C6-SNY1q.js} +1 -1
- package/static/dashboard/assets/{external-link-DxBxK8Vu.js → external-link-BgPcZ_j2.js} +1 -1
- package/static/dashboard/assets/index-6LcIUIYO.js +1 -0
- package/static/dashboard/assets/index-D7A8U6Pt.js +41 -0
- package/static/dashboard/assets/index-UD6QOE7H.js +4 -0
- package/static/dashboard/assets/{key-round-D1K7warM.js → key-round-BOd7Jo0Q.js} +1 -1
- package/static/dashboard/assets/layout-DB3pMyTl.js +1 -0
- package/static/dashboard/assets/pod-collections-host-KnnGFZHL.js +8 -0
- package/static/dashboard/assets/{rotate-ccw-CcN1N6p9.js → rotate-ccw-CCgJqsvx.js} +1 -1
- package/static/dashboard/assets/settings-projection-CUkyprDQ.js +1 -0
- package/static/dashboard/assets/{skeleton-CKnmJMUH.js → skeleton-Bc7abAn5.js} +1 -1
- package/static/dashboard/assets/{waypoints-DuZPO_wu.js → waypoints-s-opmJxx.js} +1 -1
- package/static/dashboard/assets/{workspace-layout-BUj3wZ_m.js → workspace-layout-DqIQeTBV.js} +1 -1
- package/static/dashboard/dashboard.html +2 -2
- package/static/settings/assets/AiConfigContext-BB9KZySa.js +1 -0
- package/static/settings/assets/AiConfigPage-DGSXUkLs.js +1 -0
- package/static/settings/assets/DocumentProcessingPanel-Da2Re6Rg.js +1 -0
- package/static/settings/assets/IndexLifecyclePanel-BSZuIzgr.js +1 -0
- package/static/settings/assets/{IndexSubjectPanel-73sM16Ma.js → IndexSubjectPanel-CFd0ay-r.js} +1 -1
- package/static/settings/assets/ModelAssignmentsPanel-CSAryvWJ.js +1 -0
- package/static/settings/assets/ModelsPage-BQwCwLHU.js +11 -0
- package/static/settings/assets/{NetworkPage-i6j-M2RY.js → NetworkPage-BKymvsQc.js} +2 -2
- package/static/settings/assets/{PaneListHeader-DpqC0jd5.js → PaneListHeader-Bjh3hRdQ.js} +1 -1
- package/static/settings/assets/SearchIndexingPanel-MjKL5QLU.js +1 -0
- package/static/settings/assets/{StatusSubjectPanel-Dv4q3PGh.js → StatusSubjectPanel-Bvl6K4mx.js} +1 -1
- package/static/settings/assets/StatusWorkspace-B0NzrP--.js +1 -0
- package/static/settings/assets/SystemSettingsPage-D2z6Z4FE.js +1 -0
- package/static/settings/assets/SystemSettingsSubjectPanel-4sxma4X4.js +33 -0
- package/static/settings/assets/XpodAiConnectionsPodStore-BkNQ8fZx.js +3 -0
- package/static/settings/assets/{activity-DaFkk8f3.js → activity-CgJJGpjx.js} +1 -1
- package/static/settings/assets/admin-C6qCRFiY.js +1 -0
- package/static/settings/assets/ai-connections-CryuHGKW.js +1 -0
- package/static/settings/assets/{badge-d5SHdc-x.js → badge-C4NypVyT.js} +1 -1
- package/static/settings/assets/collection-runtime-CTLCDxAi.js +1 -0
- package/static/settings/assets/dialog-Csq0vWUi.js +1 -0
- package/static/settings/assets/{download-CpkwomDr.js → download-DaLJJ-Wp.js} +1 -1
- package/static/settings/assets/{external-link-_4YT42Mf.js → external-link--w_iW5Au.js} +1 -1
- package/static/settings/assets/index-B0mQa59b.js +4 -0
- package/static/settings/assets/index-BukHiu4y.js +1 -0
- package/static/settings/assets/index-COmVnZi2.js +41 -0
- package/static/settings/assets/{index-browser-B06xjBdZ.js → index-browser-BGpvHwD0.js} +1 -1
- package/static/settings/assets/{key-round-Dlqmp1Kq.js → key-round-Bk4YRjBu.js} +1 -1
- package/static/settings/assets/layout-DB3pMyTl.js +1 -0
- package/static/settings/assets/pod-collections-host-KnnGFZHL.js +8 -0
- package/static/settings/assets/{rotate-ccw-TAY65xWT.js → rotate-ccw-TCabbqsr.js} +1 -1
- package/static/settings/assets/{settings-ExBXGgbj.js → settings-CJWpdbNC.js} +105 -109
- package/static/settings/assets/settings-projection-CUkyprDQ.js +1 -0
- package/static/settings/assets/settings-rk080mvG.css +1 -0
- package/static/settings/assets/{skeleton-DKIWjNr9.js → skeleton-JDHYVe7t.js} +1 -1
- package/static/settings/assets/{waypoints-9erLIxyR.js → waypoints-DDvEl-MU.js} +1 -1
- package/static/settings/assets/{workspace-layout-CYXfYIa3.js → workspace-layout-DV5QU30U.js} +1 -1
- package/static/settings/settings.html +2 -2
- package/node_modules/@undefineds.co/shared-ui/dist/oidc-consent.d.ts +0 -54
- package/node_modules/@undefineds.co/shared-ui/dist/oidc-consent.js +0 -21
- package/static/auth-callback/assets/AiConfigContext-C81deMM9.js +0 -1
- package/static/auth-callback/assets/AiConfigPage-evWI8T56.js +0 -1
- package/static/auth-callback/assets/DocumentProcessingPanel-B9GrDEMe.js +0 -1
- package/static/auth-callback/assets/IndexLifecyclePanel-qCo8ABQZ.js +0 -1
- package/static/auth-callback/assets/ModelAssignmentsPanel-DG7Lxh3t.js +0 -1
- package/static/auth-callback/assets/ModelsPage-CgEuqE6p.js +0 -10
- package/static/auth-callback/assets/SearchIndexingPanel-ByU3u7kp.js +0 -1
- package/static/auth-callback/assets/StatusWorkspace-BZd617sV.js +0 -1
- package/static/auth-callback/assets/SystemSettingsPage-BirzWAQM.js +0 -1
- package/static/auth-callback/assets/SystemSettingsSubjectPanel-CmsVWNCx.js +0 -31
- package/static/auth-callback/assets/admin-BU4m6Ko2.js +0 -1
- package/static/auth-callback/assets/ai-connections-CHNTKemd.js +0 -1
- package/static/auth-callback/assets/auth-callback-C_7MUXJb.css +0 -1
- package/static/auth-callback/assets/index-BpV1hsqs.js +0 -4
- package/static/auth-callback/assets/index-D9oE6FXK.js +0 -41
- package/static/dashboard/assets/AiConfigContext-De-OtAWo.js +0 -1
- package/static/dashboard/assets/AiConfigPage-macP4Mop.js +0 -1
- package/static/dashboard/assets/DocumentProcessingPanel-C5ObvCCl.js +0 -1
- package/static/dashboard/assets/IndexLifecyclePanel-xVNa2l40.js +0 -1
- package/static/dashboard/assets/ModelAssignmentsPanel-DMOATFpQ.js +0 -1
- package/static/dashboard/assets/ModelsPage-91UbnETA.js +0 -25
- package/static/dashboard/assets/SearchIndexingPanel-Dh70PNFZ.js +0 -1
- package/static/dashboard/assets/SystemSettingsPage-BiN5GcKx.js +0 -1
- package/static/dashboard/assets/SystemSettingsSubjectPanel-B9QrSiFp.js +0 -31
- package/static/dashboard/assets/admin-BU4m6Ko2.js +0 -1
- package/static/dashboard/assets/ai-connections-CHNTKemd.js +0 -1
- package/static/dashboard/assets/dashboard-C_7MUXJb.css +0 -1
- package/static/dashboard/assets/index-FWZ-s52O.js +0 -41
- package/static/dashboard/assets/index-ZiQZ96oC.js +0 -4
- package/static/settings/assets/AiConfigContext-C0cQMPfG.js +0 -1
- package/static/settings/assets/AiConfigPage-CPhB4iFb.js +0 -1
- package/static/settings/assets/DocumentProcessingPanel-sYI7OpuH.js +0 -1
- package/static/settings/assets/IndexLifecyclePanel-yj8iyiT8.js +0 -1
- package/static/settings/assets/ModelAssignmentsPanel-BFIgUX5v.js +0 -1
- package/static/settings/assets/ModelsPage-BdppXl7E.js +0 -10
- package/static/settings/assets/SearchIndexingPanel-BlPnrkT3.js +0 -1
- package/static/settings/assets/SystemSettingsPage-CiOm2NzV.js +0 -1
- package/static/settings/assets/SystemSettingsSubjectPanel-Cd-GECon.js +0 -31
- package/static/settings/assets/admin-BU4m6Ko2.js +0 -1
- package/static/settings/assets/ai-connections-CHNTKemd.js +0 -1
- package/static/settings/assets/index-BFi9yn7_.js +0 -41
- package/static/settings/assets/index-BGgEhIUy.js +0 -4
- package/static/settings/assets/settings-C_7MUXJb.css +0 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{P as F,r as Nt,a as Wt,b as Bt,c as Oe,s as Ge,d as Ht,e as Ct}from"./layout-DB3pMyTl.js";class Ke{}class Rt extends Ke{constructor(e){super(),this.path=e,this.type="ref"}}class Q extends Ke{constructor(e){super(),this.value=e,this.type="val"}}class j extends Ke{constructor(e,t){super(),this.name=e,this.args=t,this.type="func"}}function Ye(s,e){if(typeof s==typeof e){if(typeof s=="number"&&typeof e=="number"){const t=Number.isNaN(s),n=Number.isNaN(e);if(t||n)return t&&n?0:t?1:-1}return s<e?-1:s>e?1:0}return typeof s=="string"?-1:1}Gt();function Gt(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}function Yt(){return Math.random()*(2**31-1)>>>0}const Jt=Yt(),Je=new WeakMap;function Qt(s){Zt(s)}let Qe=1;function Zt(s){let e=Je.get(s);return e===void 0&&(e=Qe^Jt,Qe++,Je.set(s,e)),e}function le(){const s=typeof globalThis<"u"?globalThis.crypto:void 0;if(s&&typeof s.randomUUID=="function")return s.randomUUID();if(s&&typeof s.getRandomValues=="function"){const e=s.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[];for(let n=0;n<16;n++)t.push(e[n].toString(16).padStart(2,"0"));return t.slice(0,4).join("")+"-"+t.slice(4,6).join("")+"-"+t.slice(6,8).join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10,16).join("")}throw new Error("No secure random number generator available: neither crypto.randomUUID nor crypto.getRandomValues is defined in this environment.")}class H extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class Ze extends H{constructor(e,t,n){const i=`${e==="insert"?"Insert":"Update"} validation failed: ${t.map(r=>`
|
|
2
|
+
- ${r.message} - path: ${r.path}`).join("")}`;super(n||i),this.name="SchemaValidationError",this.type=e,this.issues=t}}class ee extends H{constructor(e){super(e),this.name="CollectionConfigurationError"}}class Xt extends ee{constructor(){super("Collection requires a config")}}class es extends ee{constructor(){super("Collection requires a sync config")}}class ts extends ee{constructor(){super("Schema must implement the standard-schema interface")}}class Xe extends ee{constructor(){super("Schema validation must be synchronous")}}class ie extends H{constructor(e){super(e),this.name="CollectionStateError"}}class ss extends ie{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class ns extends ie{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}}class is extends ie{constructor(){super("Collection is in error state")}}class rs extends ie{constructor(){super("Active subscribers count is negative - this should never happen")}}class q extends H{constructor(e){super(e),this.name="CollectionOperationError"}}class os extends q{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class as extends q{constructor(e,t){const n=e===null?"null":typeof e;super(`getKey returned an invalid key type. Expected string or number, but got ${n}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}}class cs extends q{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class ls extends q{constructor(e,t,n){const i=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${i}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):n?.hasCustomGetKey&&n.hasJoins?super(`${i}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(i)}}class us extends q{constructor(){super("The first argument to update is missing")}}class ds extends q{constructor(){super("No keys were passed to update")}}class hs extends q{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class fs extends q{constructor(e,t){super(`Updating the key of an item is not allowed. Original key: "${e}", Attempted new key: "${t}". Please delete the old item and create a new one if a key change is necessary.`)}}class ps extends q{constructor(){super("No keys were passed to delete")}}class ys extends q{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class Fe extends H{constructor(e){super(e),this.name="MissingHandlerError"}}class ms extends Fe{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class gs extends Fe{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class Ss extends Fe{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class G extends H{constructor(e){super(e),this.name="TransactionError"}}class bs extends G{constructor(){super("mutationFn is required when creating a transaction")}}class ws extends G{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class vs extends G{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class ks extends G{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class Te extends G{constructor(){super("No pending sync transaction to write to")}}class xe extends G{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class Cs extends G{constructor(){super("No pending sync transaction to commit")}}class Rs extends G{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class Ve extends H{constructor(e){super(e),this.name="QueryCompilationError"}}class Os extends Ve{constructor(e){super(`Unknown expression type: ${e}`)}}class Ts extends Ve{constructor(){super("Reference path cannot be empty")}}class xs extends Ve{constructor(e){super(`Unknown function: ${e}`)}}class et extends H{constructor(e,t){const n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name="SyncCleanupError"}}class tt extends Error{constructor(){super("Sync transaction was aborted before application"),this.name="AbortError"}}class Es extends Error{constructor(){super("Collection preload was abandoned during cleanup"),this.name="AbortError"}}class $ extends Error{constructor(){super("Load subset operation was aborted before its result became visible"),this.name="AbortError"}}function K(s,e){return pe(s,e,new Map)}function st(s){const e=Object.keys(s);for(const t of Object.getOwnPropertySymbols(s))Object.prototype.propertyIsEnumerable.call(s,t)&&e.push(t);return e}function pe(s,e,t){if(s===e)return!0;if(s==null||e==null||typeof s!=typeof e)return!1;if(s instanceof Date)return e instanceof Date?s.getTime()===e.getTime():!1;if(e instanceof Date)return!1;if(s instanceof RegExp)return e instanceof RegExp?s.source===e.source&&s.flags===e.flags:!1;if(e instanceof RegExp)return!1;if(s instanceof Map){if(!(e instanceof Map)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const i=Array.from(s.entries()).every(([r,o])=>e.has(r)&&pe(o,e.get(r),t));return t.delete(s),i}if(e instanceof Map)return!1;if(s instanceof Set){if(!(e instanceof Set)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=Array.from(s),i=Array.from(e);if(n.every(o=>typeof o!="object"))return t.delete(s),n.every(o=>e.has(o));const r=n.length===i.length;return t.delete(s),r}if(e instanceof Set)return!1;if(ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)&&!(s instanceof DataView)&&!(e instanceof DataView)){const n=s,i=e;if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++)if(n[r]!==i[r])return!1;return!0}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)&&!ArrayBuffer.isView(s))return!1;if(z(s)&&z(e)){const n=s[Symbol.toStringTag],i=e[Symbol.toStringTag];return n!==i?!1:typeof s.equals=="function"?s.equals(e):s.toString()===e.toString()}if(z(e))return!1;if(Array.isArray(s)){if(!Array.isArray(e)||s.length!==e.length)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=s.every((i,r)=>pe(i,e[r],t));return t.delete(s),n}if(Array.isArray(e))return!1;if(typeof s=="object"){if(t.has(s))return t.get(s)===e;t.set(s,e);const n=st(s),i=st(e);if(n.length!==i.length)return t.delete(s),!1;const r=n.every(o=>Object.prototype.propertyIsEnumerable.call(e,o)&&pe(s[o],e[o],t));return t.delete(s),r}return!1}const Ds=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]);function z(s){if(s==null||typeof s!="object")return!1;const e=s[Symbol.toStringTag];return typeof e=="string"&&Ds.has(e)}const ve={direction:"asc",nulls:"first",stringSort:"locale"};function Ps(){const s=new WeakMap;let e,t,n,i=0;const r=(o,a)=>{let c=o.get(a);return c===void 0&&(c=++i,o.set(a,c)),c};return o=>{n??=As();let a;if(typeof o=="symbol"){const c=Symbol.keyFor(o);c===void 0?(e??=Is(),a=r(e,o)):(t??=new Map,a=r(t,c))}else a=r(s,o);return["runtimeReference",n,a]}}function Is(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}let nt;function it(s){return nt??=Ps(),nt(s)}function As(){const s=new Uint32Array(4),e=Reflect.get(globalThis,"crypto");return typeof e?.getRandomValues=="function"?(e.getRandomValues(s),Array.from(s,t=>t.toString(36)).join("-")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}const Ee=new WeakMap;let _s=1;function rt(s){if(Ee.has(s))return Ee.get(s);const e=_s++;return Ee.set(s,e),e}function I(s){return typeof s=="number"&&Number.isNaN(s)||s instanceof Date&&Number.isNaN(s.getTime())}const Ue=(s,e,t)=>{const{nulls:n}=t;if(s==null&&e==null)return 0;if(s==null)return n==="first"?-1:1;if(e==null)return n==="first"?1:-1;const i=I(s),r=I(e);if(i&&r)return 0;if(i)return 1;if(r)return-1;if(typeof s=="string"&&typeof e=="string"&&t.stringSort==="locale")return s.localeCompare(e,t.locale,t.localeOptions);if(Array.isArray(s)&&Array.isArray(e)){for(let d=0;d<Math.min(s.length,e.length);d++){const h=Ue(s[d],e[d],t);if(h!==0)return h}return s.length-e.length}if(s instanceof Date&&e instanceof Date)return s.getTime()-e.getTime();if(z(s)&&z(e))return xt(s,e);const o=typeof s=="symbol",a=typeof e=="symbol";if(o&&a)return s===e?0:it(s)[2]-it(e)[2];if(o)return 1;if(a)return-1;const c=typeof s=="object",u=typeof e=="object";if(c||u){if(c&&u){const d=rt(s),h=rt(e);return d-h}if(c)return 1;if(u)return-1}return s<e?-1:s>e?1:0},Ms=(s,e,t)=>Ue(e,s,{...t,nulls:t.nulls==="first"?"last":"first"});function Ot(s){return(e,t)=>s.direction==="asc"?Ue(e,t,s):Ms(e,t,s)}function Se(s){return s instanceof Uint8Array||typeof Buffer<"u"&&s instanceof Buffer}function Ls(s,e){if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}const Tt="\0tanstack-db:";function _e(s,e){return`${Tt}${s}:${e}`}function Ks(s){let e="";for(let t=0;t<s.byteLength;t++)e+=String.fromCharCode(s[t]);return _e("binary",e)}function Fs(s){return typeof s=="string"?s.startsWith(Tt)?_e("string",s):s:typeof s!="object"||s===null?s:s instanceof Date?s.getTime():z(s)?_e("temporal",`${s[Symbol.toStringTag]}:${s.toString()}`):Se(s)?Ks(s):s}const ot=new Map;function xt(s,e){const t=s[Symbol.toStringTag],n=e[Symbol.toStringTag];if(t!==n)throw new TypeError(`Cannot order Temporal values of different types: ${t} vs ${n}`);let i=ot.get(t);if(i===void 0){const r=s.constructor.compare;i=typeof r=="function"?r:null,ot.set(t,i)}if(i===null)throw new TypeError(`${t} has no defined ordering`);return i(s,e)}function he(s,e){return z(s)&&z(e)?xt(s,e):s<e?-1:s>e?1:0}function Vs(s,e){return s===e?!0:Se(s)&&Se(e)?Ls(s,e):!1}function _(s){return s==null}function fe(s){return Se(s)?s:Fs(s)}function at(s,e){return I(s)||I(e)?I(s)&&I(e):Vs(s,e)}function De(s){if(s instanceof Date)return Number.isNaN(s.getTime())?null:s;if(typeof s=="string"||typeof s=="number"){const e=new Date(s);return Number.isNaN(e.getTime())?null:e}return null}function Us(s,e){return s==="%Y-%m-%d"?e.toISOString().slice(0,10):e.toISOString()}function $s(s){return s===!0}function zs(s,e=!1){return $e(s,e)}function Et(s){return $e(s,!0)}function $e(s,e){switch(s.type){case"val":{const t=s.value;return()=>t}case"ref":return e?js(s):qs(s);case"func":return Ns(s,e);default:throw new Os(s.type)}}function qs(s){const[e,...t]=s.path;if(!e)throw new Ts;if(e==="$selected"){if(t.length===0)return i=>i.$selected;if(t.length===1){const i=t[0];return r=>r.$selected?.[i]}else return i=>{const r=i.$selected;if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}const n=e;if(t.length===0)return i=>i[n];if(t.length===1){const i=t[0];return r=>r[n]?.[i]}else return i=>{const r=i[n];if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}function js(s){const e=s.path;return t=>{let n=t;for(const i of e){if(n==null)return n;n=n[i]}return n}}function Ns(s,e){const t=s.args.map(n=>$e(n,e));switch(s.name){case"eq":{const n=t[0],i=t[1];return r=>{const o=fe(n(r)),a=fe(i(r));return _(o)||_(a)?null:at(o,a)}}case"gt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(o)&&!I(a):he(o,a)>0}}case"gte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(o):he(o,a)>=0}}case"lt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(a)&&!I(o):he(o,a)<0}}case"lte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(a):he(o,a)<=0}}case"and":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!1)return!1;_(o)&&(i=!0)}return i?null:!0};case"or":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!0)return!0;_(o)&&(i=!0)}return i?null:!1};case"not":{const n=t[0];return i=>{const r=n(i);return _(r)?null:!r}}case"in":{const n=t[0],i=t[1];return r=>{const o=fe(n(r)),a=i(r);return _(o)?null:Array.isArray(a)?a.some(c=>at(fe(c),o)):!1}}case"like":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:ct(o,a,!1)}}case"ilike":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:ct(o,a,!0)}}case"upper":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toUpperCase():r}}case"lower":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toLowerCase():r}}case"length":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"||Array.isArray(r)?r.length:0}}case"concat":return n=>t.map(i=>{const r=i(n);try{return String(r??"")}catch{try{return JSON.stringify(r)||""}catch{return"[object]"}}}).join("");case"coalesce":return n=>{for(const i of t){const r=i(n);if(r!=null)return r}return null};case"caseWhen":{const n=t.length%2===1,i=Math.floor(t.length/2);if(t.length<2)throw new Error("caseWhen() requires at least two arguments");return r=>{for(let o=0;o<i;o++){const a=t[o*2];if(Ws(a(r))){const c=t[o*2+1];return c(r)}}return n?t[t.length-1](r):null}}case"add":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)+(a??0)}}case"subtract":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)-(a??0)}}case"multiply":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)*(a??0)}}case"divide":{const n=t[0],i=t[1];return r=>{const o=n(r),c=i(r)??0;return c!==0?(o??0)/c:null}}case"date":{const n=t[0];return i=>{const r=n(i),o=De(r);return o?o.toISOString().slice(0,10):null}}case"datetime":{const n=t[0];return i=>{const r=n(i),o=De(r);return o?o.toISOString():null}}case"strftime":{const n=t[0],i=t[1];return r=>{const o=n(r);if(typeof o!="string")return null;const a=i(r),c=De(a);return c?Us(o,c):null}}case"isUndefined":{const n=t[0];return i=>n(i)===void 0}case"isNull":{const n=t[0];return i=>n(i)===null}default:throw new xs(s.name)}}function Ws(s){return s==null||s===!1?!1:s===!0?!0:typeof s=="number"?s!==0&&!Number.isNaN(s):typeof s=="bigint"?s!==0n:!!s}function ct(s,e,t){if(typeof s!="string"||typeof e!="string")return!1;const n=t?s.toLowerCase():s;let r=(t?e.toLowerCase():e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r=r.replace(/%/g,".*"),r=r.replace(/_/g,"."),new RegExp(`^${r}$`,"s").test(n)}class Bs{constructor(e){this.originalIndex=e}lookup(e,t){const n=e==="gt"?"lt":e==="gte"?"lte":e==="lt"?"gt":e==="lte"?"gte":e;return this.originalIndex.lookup(n,t)}rangeQuery(e={}){return this.originalIndex.rangeQueryReversed(e)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}supports(e){return this.originalIndex.supports(e)}get supportsRangeOptimization(){return this.originalIndex.supportsRangeOptimization}canOptimizeRangeFor(e){return this.originalIndex.canOptimizeRangeFor?.(e)??!0}get keyCount(){return this.originalIndex.keyCount}}function lt(s,e,t,n,i){const r=s;return{...s,$synced:r.$synced??n(),$origin:r.$origin??i(),$key:r.$key??e,$collectionId:r.$collectionId??t}}const Hs=["$synced","$origin","$key","$collectionId"];function Gs(s){return Hs.includes(s)}function Dt(s){return s.some(e=>Gs(e))}function ke(s,e,t){if(Dt(e))return;const n=t??{...ve,...s.compareOptions};for(const i of s.indexes.values())if(i.matchesField(e)&&i.matchesCompareOptions(n))return i.matchesDirection(n.direction)?i:new Bs(i)}function Ys(s){if(s.length===0)return new Set;if(s.length===1)return new Set(s[0]);let e=new Set(s[0]);for(let t=1;t<s.length;t++){const n=new Set;for(const i of e)s[t].has(i)&&n.add(i);e=n}return e}function Js(s){const e=new Set;for(const t of s)for(const n of t)e.add(n);return e}function ze(s){return s!=null}function Qs(s){return{...ve,...s.compareOptions}.stringSort==="locale"}function Zs(s,e){switch(typeof s){case"number":case"bigint":case"boolean":return!1;case"string":return Qs(e);case"symbol":return!0;case"object":return s===null?!1:!(s instanceof Date);default:return!1}}function Pt(s,e,t){return!Zs(s,t)&&e.supportsRangeOptimization&&(e.canOptimizeRangeFor?.(s)??!0)}function Xs(s,e){return qe(s,e)}function qe(s,e){if(s.type==="func")switch(s.name){case"eq":case"gt":case"gte":case"lt":case"lte":return tn(s,e);case"and":return sn(s,e);case"or":return nn(s,e);case"in":return rn(s,e)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function en(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};const t=new Map;for(const[n,i]of s.args.entries())if(i.type==="func"&&["gt","gte","lt","lte"].includes(i.name)){const r=i;if(r.args.length===2){const o=r.args[0],a=r.args[1];let c=null,u=null,d=r.name;if(o.type==="ref"&&a.type==="val")c=o,u=a;else if(o.type==="val"&&a.type==="ref")switch(c=a,u=o,d){case"gt":d="lt";break;case"gte":d="lte";break;case"lt":d="gt";break;case"lte":d="gte";break}if(c&&u){const l=c.path.join("."),p=u.value;t.has(l)||t.set(l,[]),t.get(l).push({operation:d,value:p,argIndex:n})}}}for(const[n,i]of t)if(i.length>=2){const r=n.split("."),o=ke(e,r);if(o&&i.some(a=>!Pt(a.value,o,e)))continue;if(o&&o.supports("gt")&&o.supports("lt")){const a=Ot({...ve,...e.compareOptions,direction:"asc"});let c,u,d=!1,h=!1,l=!0,p=!0,f=!1;for(const{operation:b,value:x}of i){if(!ze(x)){f=!0;continue}switch(b){case"gt":case"gte":{const v=d?a(x,c):1;v>0?(c=x,d=!0,l=b==="gte"):v===0&&b==="gt"&&(l=!1);break}case"lt":case"lte":{const v=h?a(x,u):-1;v<0?(u=x,h=!0,p=b==="lte"):v===0&&b==="lt"&&(p=!1);break}}}const g={};return d&&(g.from=c,g.fromInclusive=l),h&&(g.to=u,g.toInclusive=p),{canOptimize:!0,matchingKeys:o.rangeQuery(g),isExact:d&&!f,coveredArgIndices:new Set(i.map(b=>b.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}function tn(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];let i=null,r=null,o=s.name;if(t.type==="ref"&&n.type==="val")i=t,r=n;else if(t.type==="val"&&n.type==="ref")switch(i=n,r=t,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte";break}if(i&&r){const a=i.path,c=ke(e,a);if(c){const u=r.value,d=o;if(!c.supports(d))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};if((o==="gt"||o==="gte"||o==="lt"||o==="lte")&&!Pt(u,c,e))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const h=c.lookup(d,u),l=o==="lt"||o==="lte"?!1:ze(u);return{canOptimize:!0,matchingKeys:h,isExact:l}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function sn(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=en(s,e),n=t.canOptimize?t.coveredArgIndices:new Set,i=[];t.canOptimize&&i.push(t);let r=t.canOptimize?t.isExact:!0;for(const[o,a]of s.args.entries()){if(n.has(o))continue;const c=qe(a,e);c.canOptimize?(i.push(c),c.isExact||(r=!1)):r=!1}if(i.length>0){const o=i.map(c=>c.matchingKeys);return{canOptimize:!0,matchingKeys:Ys(o),isExact:r}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function nn(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=[];for(const r of s.args){const o=qe(r,e);if(!o.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};t.push(o)}const n=t.map(r=>r.matchingKeys);return{canOptimize:!0,matchingKeys:Js(n),isExact:t.every(r=>r.isExact)}}function rn(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];if(t.type==="ref"&&n.type==="val"&&Array.isArray(n.value)){const i=t.path,r=n.value,o=ke(e,i),a=r.every(c=>ze(c));if(o){if(o.supports("in"))return{canOptimize:!0,matchingKeys:o.lookup("in",r),isExact:a};if(o.supports("eq")){const c=new Set;for(const u of r){const d=o.lookup("eq",u);for(const h of d)c.add(h)}return{canOptimize:!0,matchingKeys:c,isExact:a}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function It(s){return s.config.autoIndex==="eager"}function At(s,e,t,n,i){if(Dt(e)||!It(t))return;const r=n??{...ve,...t.compareOptions};if(!Array.from(t.indexes.values()).find(a=>a.matchesField(e)&&a.matchesCompareOptions(r)))try{t.createIndex(a=>{let c=a;for(const u of e)c=c[u];return c},{name:`auto:${e.join(".")}`,options:i?{compareFn:i,compareOptions:r}:{}})}catch(a){console.warn(`${t.id?`[${t.id}] `:""}Failed to create auto-index for field path "${e.join(".")}":`,a)}}function on(s,e){if(!It(e))return;const t=an(s);for(const{fieldName:n,fieldPath:i}of t)At(n,i,e)}function an(s){const e=[];function t(n){if(n.type!=="func")return;const i=n;if(i.name==="and"){for(const u of i.args)t(u);return}if(!["eq","gt","gte","lt","lte","in"].includes(i.name)||i.args.length<1||i.args[0].type!=="ref")return;const a=i.args[0].path;if(a.length===0)return;const c=a.join("_");e.push({fieldName:c,fieldPath:a})}return t(s),e}function cn(s,e){return ln(s,e.compareOptions)}function ln(s,e){return s.compareOptions.stringSort===void 0?{...e,direction:s.compareOptions.direction,nulls:s.compareOptions.nulls}:s.compareOptions}function un(s,e={}){const t=n=>{const i=[];for(const[r,o]of s.entries())(n?.(o)??!0)&&i.push({type:"insert",key:r,value:o});return i};if(e.limit!==void 0&&!e.orderBy)throw new Error("limit cannot be used without orderBy");if(e.orderBy){const n=e.where?te(e.where):void 0,i=hn(s,e.orderBy,e.limit,n,e.optimizedOnly);if(i===void 0)return;const r=[];for(const o of i){const a=s.get(o);a!==void 0&&r.push({type:"insert",key:o,value:a})}return r}if(!e.where)return t();try{const n=e.where,i=Xs(n,s);if(i.canOptimize){const r=i.isExact?void 0:te(n),o=[];for(const a of i.matchingKeys){const c=s.get(a);c!==void 0&&(r?.(c)??!0)&&o.push({type:"insert",key:a,value:c})}return o}else{if(e.optimizedOnly)return;const r=te(n);return t(r)}}catch(n){console.warn(`${s.id?`[${s.id}] `:""}Error processing where clause, falling back to full scan:`,n);const i=te(e.where);return e.optimizedOnly?void 0:t(i)}}function te(s){const e=Et(s);return t=>{try{const n=e(t);return $s(n)}catch{return!1}}}function dn(s,e){const t=te(e.whereExpression);return n=>{const i=[];for(const r of n)if(r.type==="insert")t(r.value)&&i.push(r);else if(r.type==="update"){const o=t(r.value),a=r.previousValue?t(r.previousValue):!1;o&&a?i.push(r):o&&!a?i.push({...r,type:"insert"}):!o&&a&&i.push({...r,type:"delete",value:r.previousValue})}else t(r.value)&&i.push(r);return i.length>0||n.length===0?(s(i),!0):!1}}function hn(s,e,t,n,i){if(e.length===1){const c=e[0],u=c.expression;if(u.type==="ref"){const h=u.path,l=cn(c,s);At(h[0],h,s,l);const p=ke(s,h,l);if(p&&p.supports("gt")){const f=g=>{const w=s.get(g);return w===void 0?!1:n?.(w)??!0};return p.takeFromStart(t??p.keyCount,f)}}}if(i)return;const r=[];for(const[c,u]of s.entries())(n?.(u)??!0)&&r.push({key:c,value:u});const o=(c,u)=>{for(const d of e){const h=Ot(d.compareOptions),l=ut(c.value,d.expression),p=ut(u.value,d.expression),f=h(l,p);if(f!==0)return f}return 0};r.sort(o);const a=r.map(c=>c.key);return t!==void 0?a.slice(0,t):a}function ut(s,e){if(e.type==="ref"){const t=e;let n=s;for(const i of t.path)n=n?.[i];return n}else return e.type==="val"?e.value:Et(e)(s)}class dt{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,i=this.sortedKeys.length;if(!this.comparator){for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=Ye(e,o);if(a<0)i=r;else if(a>0)n=r+1;else return r}return n}for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=this.map.get(o),c=this.comparator(t,a);if(c<0)i=r;else if(c>0)n=r+1;else{const u=Ye(e,o);if(u<0)i=r;else if(u>0)n=r+1;else return r}}return n}set(e,t){if(this.map.has(e)){const i=this.map.get(e),r=this.indexOf(e,i);this.sortedKeys.splice(r,1)}const n=this.indexOf(e,t);return this.sortedKeys.splice(n,0,e),this.map.set(e,t),this}get(e){return this.map.get(e)}delete(e){if(this.map.has(e)){const t=this.map.get(e),n=this.indexOf(e,t);return this.sortedKeys.splice(n,1),this.map.delete(e)}return!1}has(e){return this.map.has(e)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(const e of this.sortedKeys)yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(const e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(const t of this.sortedKeys)e(this.map.get(t),t,this.map)}}const ye="__tanstack_db_direct";class fn{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.hydrationSeedKeys=new Set,this.hydratedKeys=new Set,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.preSyncVisibleState=new Map,this.preSyncVirtualState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isDrainingSyncTransactions=!1,this.syncSessionGeneration=0,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{if(this.isDrainingSyncTransactions)return;this.isDrainingSyncTransactions=!0;let t=!1,n;try{let i;do i=this.commitNextPendingTransactionBatch(),i.failure&&!t&&(t=!0,n=i.failure.error);while(i.processed)}finally{this.isDrainingSyncTransactions=!1}if(t)throw n},this.config=e,this.transactions=new dt((t,n)=>t.compareCreatedAt(n)),this.syncedData=new dt(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}isRowSynced(e){return this.isLocalOnly?!0:!this.optimisticUpserts.has(e)&&!this.optimisticDeletes.has(e)}getRowOrigin(e){return this.isLocalOnly||this.optimisticUpserts.has(e)||this.optimisticDeletes.has(e)?"local":this.rowOrigins.get(e)??"remote"}createVirtualPropsSnapshot(e,t){return{$synced:t?.$synced??this.isRowSynced(e),$origin:t?.$origin??this.getRowOrigin(e),$key:t?.$key??e,$collectionId:t?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(e,t){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(e,{$synced:!0,$origin:"local"});const n=t?.optimisticUpserts??this.optimisticUpserts,i=t?.optimisticDeletes??this.optimisticDeletes,r=n.has(e)||i.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!r,$origin:r?"local":(t?.rowOrigins??this.rowOrigins).get(e)??"remote"})}snapshotRowOriginsForKeys(e){const t=new Map;for(const n of e){const i=this.rowOrigins.get(n);i!==void 0&&t.set(n,i)}return t}enrichWithVirtualPropsSnapshot(e,t){const n=e,i=n.$synced??t.$synced,r=n.$origin??t.$origin,o=n.$key??t.$key,a=n.$collectionId??t.$collectionId,c=this.virtualPropsCache.get(e);if(c&&c.synced===i&&c.origin===r&&c.key===o&&c.collectionId===a)return c.enriched;const u={...e,$synced:i,$origin:r,$key:o,$collectionId:a};return this.virtualPropsCache.set(e,{synced:i,origin:r,key:o,collectionId:a,enriched:u}),u}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){const{__virtualProps:t}=e,n=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),i=e.previousValue?t?.previousValue?this.enrichWithVirtualPropsSnapshot(e.previousValue,t.previousValue):this.enrichWithVirtualProps(e.previousValue,e.key):void 0;return{key:e.key,type:e.type,value:n,previousValue:i,metadata:e.metadata}}getWithVirtualProps(e){const t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;if(!t.has(e))return n.has(e)?n.get(e):i.get(e)}has(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;return t.has(e)?!1:n.has(e)?!0:i.has(e)}*keys(){const{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(const i of e.keys())t.has(i)||(yield i);for(const i of n.keys())!e.has(i)&&!t.has(i)&&(yield i)}*values(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){for(const[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(const[n,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,n++));return t}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;const t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),i=this.rowOrigins;for(const h of this.transactions.values()){const l=h.metadata[ye]===!0;if(h.state==="completed"){for(const p of h.mutations)if(this.isThisCollection(p.collection)&&(this.pendingLocalOrigins.add(p.key),!!p.optimistic))switch(p.type){case"insert":case"update":this.pendingOptimisticUpserts.set(p.key,p.modified),this.pendingOptimisticDeletes.delete(p.key),l?(this.pendingOptimisticDirectUpserts.add(p.key),this.pendingOptimisticDirectDeletes.delete(p.key)):(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key));break;case"delete":this.pendingOptimisticUpserts.delete(p.key),this.pendingOptimisticDeletes.add(p.key),l?(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.add(p.key)):(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key));break}}else if(h.state==="failed")for(const p of h.mutations)this.isThisCollection(p.collection)&&(this.pendingLocalOrigins.delete(p.key),p.optimistic&&(this.pendingOptimisticUpserts.delete(p.key),this.pendingOptimisticDeletes.delete(p.key),this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();const r=new Set;for(const h of this.pendingSyncedTransactions)for(const l of h.operations)r.add(l.key);const o=[];for(const[h,l]of this.pendingOptimisticUpserts)r.has(h)||this.pendingOptimisticDirectUpserts.has(h)?this.optimisticUpserts.set(h,l):o.push(h);for(const h of o)this.pendingOptimisticUpserts.delete(h),this.pendingLocalOrigins.delete(h);const a=[];for(const h of this.pendingOptimisticDeletes)r.has(h)||this.pendingOptimisticDirectDeletes.has(h)?this.optimisticDeletes.add(h):a.push(h);for(const h of a)this.pendingOptimisticDeletes.delete(h),this.pendingLocalOrigins.delete(h);const c=[];for(const h of this.transactions.values())["completed","failed"].includes(h.state)||c.push(h);for(const h of c)for(const l of h.mutations)if(this.isThisCollection(l.collection)&&(this.pendingLocalChanges.add(l.key),l.optimistic))switch(l.type){case"insert":case"update":this.optimisticUpserts.set(l.key,l.modified),this.optimisticDeletes.delete(l.key);break;case"delete":this.optimisticUpserts.delete(l.key),this.optimisticDeletes.add(l.key);break}this.size=this.calculateSize();const u=[];this.collectOptimisticChanges(t,n,i,u);const d=u.filter(h=>!!(!this.recentlySyncedKeys.has(h.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){const h=new Set;for(const p of this.pendingSyncedTransactions)for(const f of p.operations)h.add(f.key);const l=d.filter(p=>!(p.type==="delete"&&h.has(p.key)&&!c.some(g=>g.mutations.some(w=>this.isThisCollection(w.collection)&&w.key===p.key))));l.length>0&&this.indexes.updateIndexes(l),this.changes.emitEvents(l,e)}else d.length>0&&this.indexes.updateIndexes(d),this.changes.emitEvents(d,e)}calculateSize(){const e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(i=>this.syncedData.has(i)&&!this.optimisticUpserts.has(i)).length,n=Array.from(this.optimisticUpserts.keys()).filter(i=>!this.syncedData.has(i)).length;return e-t+n}collectOptimisticChanges(e,t,n,i){const r=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(const o of r){const a=this.get(o),c=this.getPreviousValue(o,e,t),u=this.getVirtualPropsSnapshotForState(o,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),d=this.getVirtualPropsSnapshotForState(o);c!==void 0&&a===void 0?i.push({type:"delete",key:o,value:c,__virtualProps:{value:u}}):c===void 0&&a!==void 0?i.push({type:"insert",key:o,value:a,__virtualProps:{value:d}}):c!==void 0&&a!==void 0&&c!==a&&i.push({type:"update",key:o,value:a,previousValue:c,__virtualProps:{value:d,previousValue:u}})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}commitNextPendingTransactionBatch(){const e=this.syncSessionGeneration;let t=!1;for(const c of this.transactions.values())if(c.state==="persisting"){t=!0;break}const{committedSyncedTransactions:n,uncommittedSyncedTransactions:i,hasTruncateSync:r,hasImmediateSync:o,layoutChanged:a}=this.pendingSyncedTransactions.reduce((c,u)=>(u.committed?(c.committedSyncedTransactions.push(u),c.layoutChanged||=u.layoutChanged,u.truncate&&(c.hasTruncateSync=!0),u.immediate&&(c.hasImmediateSync=!0)):c.uncommittedSyncedTransactions.push(u),c),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1,layoutChanged:!1});if(n.length===0)return{processed:!1};if(!t||r||o){const c=a?[...this.keys()]:void 0;this.pendingSyncedTransactions=i;for(const m of n)m.applicationStarted=!0;this.isCommittingSyncTransactions=!0;const u=r?n.find(m=>m.truncate)?.optimisticSnapshot:null;let d,h;const l=new Set;for(const m of n){for(const S of m.operations)l.add(S.key);for(const[S]of m.rowMetadataWrites)l.add(S)}const p=new Set(l);for(const m of this.pendingOptimisticDirectUpserts)p.add(m);for(const m of this.pendingOptimisticDirectDeletes)p.add(m);const f=this.snapshotRowOriginsForKeys(p),g=new Map(this.optimisticUpserts),w=new Set(this.optimisticDeletes),b=new Set(this.pendingOptimisticDirectUpserts),x=new Set(this.pendingOptimisticDirectDeletes);let v=this.preSyncVisibleState;if(v.size===0){v=new Map;for(const m of l){const S=this.get(m);S!==void 0&&v.set(m,S)}}const k=[],M=this.config.sync.rowUpdateMode||"partial",T=new Map;for(const m of this.transactions.values())if(m.state==="completed")for(const S of m.mutations)this.isThisCollection(S.collection)&&S.optimistic&&T.set(S.key,{type:S.type,value:S.modified});for(const m of n){if(m.truncate){const S=new Set([...this.syncedData.keys(),...u?.upserts.keys()||[]]);for(const y of S){if(u?.deletes.has(y))continue;const O=u?.upserts.get(y)||this.syncedData.get(y);O!==void 0&&k.push({type:"delete",key:y,value:O})}d=new Set(this.pendingLocalChanges),h=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState();for(const y of l)v.delete(y);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(const S of m.operations){const y=S.key,O=(d?.has(y)===!0||h?.has(y)===!0)&&!b.has(y)&&!x.has(y),C=this.isLocalOnly||this.pendingLocalChanges.has(y)||this.pendingLocalOrigins.has(y)||O?"local":"remote";switch(S.type){case"insert":this.syncedData.set(y,S.value),this.rowOrigins.set(y,C),this.pendingLocalChanges.delete(y),this.pendingLocalOrigins.delete(y),this.pendingOptimisticUpserts.delete(y),this.pendingOptimisticDeletes.delete(y),this.pendingOptimisticDirectUpserts.delete(y),this.pendingOptimisticDirectDeletes.delete(y);break;case"update":{if(M==="partial"){const A=Object.assign({},this.syncedData.get(y),S.value);this.syncedData.set(y,A)}else this.syncedData.set(y,S.value);this.rowOrigins.set(y,C),this.pendingLocalChanges.delete(y),this.pendingLocalOrigins.delete(y),this.pendingOptimisticUpserts.delete(y),this.pendingOptimisticDeletes.delete(y),this.pendingOptimisticDirectUpserts.delete(y),this.pendingOptimisticDirectDeletes.delete(y);break}case"delete":this.syncedData.delete(y),this.syncedMetadata.delete(y),this.rowOrigins.delete(y),this.pendingLocalChanges.delete(y),this.pendingLocalOrigins.delete(y),this.pendingOptimisticUpserts.delete(y),this.pendingOptimisticDeletes.delete(y),this.pendingOptimisticDirectUpserts.delete(y),this.pendingOptimisticDirectDeletes.delete(y);break}m.preserveHydrationSeedKeys||(this.hydrationSeedKeys.delete(y),this.hydratedKeys.delete(y))}for(const[S,y]of m.rowMetadataWrites){if(y.type==="delete"){this.syncedMetadata.delete(S);continue}this.syncedMetadata.set(S,y.value)}for(const[S,y]of m.collectionMetadataWrites){if(y.type==="delete"){this.syncedCollectionMetadata.delete(S);continue}this.syncedCollectionMetadata.set(S,y.value)}}if(r){const m=new Set;for(const O of n)for(const C of O.operations)(C.type==="insert"||C.type==="update")&&m.add(C.key);const S=new Map(u.upserts),y=new Set(u.deletes);for(const O of b)l.has(O)&&S.delete(O);for(const O of x)l.has(O)&&y.delete(O);for(const[O,C]of S)if(!y.has(O))if(m.has(O)){let A=!1;for(let V=k.length-1;V>=0;V--){const R=k[V];if(R.key===O&&R.type==="insert"){R.value=C,A=!0;break}}A||k.push({type:"insert",key:O,value:C})}else k.push({type:"insert",key:O,value:C});if(k.length>0&&y.size>0){const O=[];for(const C of k)C.type==="insert"&&y.has(C.key)||O.push(C);k.length=0,k.push(...O)}this.lifecycle.status!=="ready"&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&u){for(const[m,S]of u.upserts)b.has(m)&&l.has(m)||this.optimisticUpserts.set(m,S);for(const m of u.deletes)x.has(m)&&l.has(m)||this.optimisticDeletes.add(m)}for(const m of this.transactions.values())if(!["completed","failed"].includes(m.state)){for(const S of m.mutations)if(this.isThisCollection(S.collection)&&S.optimistic)switch(S.type){case"insert":case"update":this.optimisticUpserts.set(S.key,S.modified),this.optimisticDeletes.delete(S.key);break;case"delete":this.optimisticUpserts.delete(S.key),this.optimisticDeletes.add(S.key);break}}for(const m of this.pendingOptimisticDirectUpserts)if(!l.has(m)){if(l.add(m),!v.has(m)){const S=g.get(m);S!==void 0&&v.set(m,S)}this.pendingOptimisticUpserts.delete(m),this.pendingLocalOrigins.delete(m)}for(const m of this.pendingOptimisticDirectDeletes)l.has(m)||l.add(m),this.pendingOptimisticDeletes.delete(m),this.pendingLocalOrigins.delete(m);this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear();for(const m of l){const S=v.get(m),y=this.get(m),O=this.preSyncVirtualState.get(m)??this.getVirtualPropsSnapshotForState(m,{rowOrigins:f,optimisticUpserts:g,optimisticDeletes:w,completedOptimisticKeys:T}),C=this.getVirtualPropsSnapshotForState(m),A=O.$synced!==C.$synced||O.$origin!==C.$origin,V=S!==void 0?lt(S,m,this.collection.id,()=>O.$synced,()=>O.$origin):void 0,R=T.get(m);let D=!1;R&&(R.type==="delete"&&S!==void 0&&y===void 0&&K(R.value,S)||y!==void 0&&K(R.value,y))&&(D=!0);const Y=A&&S!==void 0&&y!==void 0&&K(S,y);if(!(D&&!Y))if(S===void 0&&y!==void 0){const re=T.get(m);if(re){const Ce=re.value,Re=lt(Ce,m,this.collection.id,()=>O.$synced,()=>O.$origin);k.push({type:"update",key:m,value:y,previousValue:Re})}else k.push({type:"insert",key:m,value:y})}else S!==void 0&&y===void 0?k.push({type:"delete",key:m,value:V??S}):S!==void 0&&y!==void 0&&(!K(S,y)||Y)&&k.push({type:"update",key:m,value:y,previousValue:V??S})}this.size=this.calculateSize(),k.length>0&&this.indexes.updateIndexes(k);let E;try{const m=c!==void 0&&(c.length!==this.size||[...this.keys()].some((S,y)=>S!==c[y]));this.changes.emitEvents(k,!0,m)}catch(m){E={error:m}}this.syncSessionGeneration===e&&(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),Promise.resolve().then(()=>{this.syncSessionGeneration===e&&this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0));for(const m of n)m.applied.resolve();return{processed:!0,failure:E}}return{processed:!1}}cancelPendingSyncedTransaction(e){if(e.applicationStarted)return;const t=this.pendingSyncedTransactions.indexOf(e);if(t===-1)return;this.pendingSyncedTransactions.splice(t,1),e.applied.reject(new tt);const n=new Set;for(const i of this.pendingSyncedTransactions)for(const r of i.operations)n.add(r.key);for(const i of e.operations){const r=i.key;n.has(r)||(this.recentlySyncedKeys.delete(r),this.preSyncVisibleState.delete(r),this.preSyncVirtualState.delete(r))}this.pendingSyncedTransactions.length===0?(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.changes.emitEvents([],!0)):this.recomputeOptimisticState(!1)}scheduleTransactionCleanup(e){if(e.state==="completed"){this.transactions.delete(e.id);return}e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;const e=new Set;for(const t of this.pendingSyncedTransactions)for(const n of t.operations)e.add(n.key);for(const t of e)this.recentlySyncedKeys.add(t);for(const t of e)if(!this.preSyncVisibleState.has(t)){const n=this.get(t);n!==void 0&&(this.preSyncVisibleState.set(t,n),this.preSyncVirtualState.set(t,this.getVirtualPropsSnapshotForState(t)))}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncSessionGeneration++;for(const e of this.pendingSyncedTransactions)e.applied.reject(new tt);this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.hasReceivedFirstCommit=!1}}function Z(s){let e;for(const t of s)try{t()}catch(n){e??={error:n}}if(e)throw e.error}function pn(s){return typeof s=="object"&&s!==null&&typeof s.hasPendingGraphRun=="function"}class yn{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(e){let t=this.contexts.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:i}){if(typeof e>"u"){i();return}const r=this.getOrCreateContext(e);if(r.jobs.has(t)||r.queue.push(t),r.jobs.set(t,i),n){const o=new Set(n);o.delete(t),r.dependencies.set(t,o)}else r.dependencies.has(t)||r.dependencies.set(t,new Set)}flush(e){const t=this.contexts.get(e);if(!t)return;const{queue:n,jobs:i,dependencies:r}=t;for(;n.length>0;){let o=!1;const a=n.length;for(let c=0;c<a;c++){const u=n.shift(),d=i.get(u);if(!d){r.delete(u);continue}const h=r.get(u);let l=!h;if(h){l=!0;for(const p of h){if(p===u)continue;const f=pn(p)&&p.hasPendingGraphRun(e);if(i.has(p)||f){l=!1;break}}}l?(i.delete(u),r.delete(u),d(),o=!0):n.push(u)}if(!o)throw new Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}clear(e){this.contexts.delete(e),Z([...this.clearListeners].map(t=>()=>t(e)))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}}const ue=new yn;let me,be;function ht(){return be}function ft(s){if(me===void 0)throw s;be??={error:s}}function pt(s){if(me!==void 0)return s();const e=Symbol("collection-publication");me=e,be=void 0;let t,n;try{t=s(),ue.flush(e),n=ht()}catch(i){try{ue.clear(e)}catch{}const r=ht();throw r?r.error:i}finally{me=void 0,be=void 0}if(n)throw n.error;return t}function _t(){const s=new Map;function e(t){const n=t.join(".");if(s.has(n))return s.get(n);const i=new Proxy({},{get(r,o,a){if(o==="__refProxy")return!0;if(o==="__path")return t;if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(r,o,a);const c=[...t,String(o)];return e(c)},has(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?!0:Reflect.has(r,o)},ownKeys(r){return Reflect.ownKeys(r)},getOwnPropertyDescriptor(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(r,o)}});return s.set(n,i),i}return e([])}function L(s){if(mn(s))return new Rt(s.__path);if(s&&typeof s=="object"&&(s.__brand==="ToArrayWrapper"||s.__brand==="ConcatToArrayWrapper"||s.__brand==="CaseWhenWrapper"||s.__brand==="MaterializeWrapper")){const e=s.__brand==="ToArrayWrapper"?"toArray()":s.__brand==="ConcatToArrayWrapper"?"concat(toArray())":s.__brand==="CaseWhenWrapper"?"caseWhen()":"materialize()";throw new Error(`${e} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${e} directly as a select field value instead.`)}return s&&typeof s=="object"&&"type"in s&&(s.type==="func"||s.type==="ref"||s.type==="val"||s.type==="agg")?s:new Q(s)}function mn(s){return s&&typeof s=="object"&&s.__refProxy===!0}function Mt(s,e){return new j("eq",[L(s),L(e)])}function gn(s,e){return new j("gt",[L(s),L(e)])}function Sn(s,e){return new j("gte",[L(s),L(e)])}function Lt(s,e){return new j("lt",[L(s),L(e)])}function Me(s,e,...t){const n=[s,e,...t];return new j("and",n.map(i=>L(i)))}function Kt(s,e,...t){const n=[s,e,...t];return new j("or",n.map(i=>L(i)))}function bn(s){return new j("not",[L(s)])}function wn(s){return new j("isUndefined",[L(s)])}function vn(s){return new j("isNull",[L(s)])}class Ft{constructor(){this.listeners=new Map,this.onceCallbacks=new WeakMap}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Map);const n=this.listeners.get(e),i=t;let r=n.get(i);return r||(r={},n.set(i,r)),()=>{const o=this.listeners.get(e);o?.get(i)===r&&o.delete(i)}}once(e,t){let n=()=>{};const i=r=>{n(),t(r)};return this.onceCallbacks.set(i,t),n=this.on(e,i),n}off(e,t){const n=this.listeners.get(e);if(n)for(const i of n.keys())(i===t||this.onceCallbacks.get(i)===t)&&n.delete(i)}waitFor(e,t){return new Promise((n,i)=>{let r;const o=this.on(e,a=>{r&&(clearTimeout(r),r=void 0),n(a),o()});t&&(r=setTimeout(()=>{r=void 0,o(),i(new Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.emitInnerWhile(e,t,()=>!0)}emitInnerWhile(e,t,n){const i=this.listeners.get(e);if(i)for(const[r,o]of[...i]){if(!n())break;if(this.listeners.get(e)?.get(r)===o)try{r(t)}catch(a){queueMicrotask(()=>{throw a})}}}clearListeners(){this.listeners.clear()}}function Vt(s){return Kt(vn(s),wn(s))}function kn(s,e){const t=Vt(s.expression);if(e==null)return s.compareOptions.nulls==="first"?bn(t):new Q(!1);const i=(s.compareOptions.direction==="asc"?gn:Lt)(s.expression,new Q(e));return s.compareOptions.nulls==="last"?Kt(i,t):i}function Cn(s,e){if(e.length!==0){if(s.length!==1||e.length!==1)throw new Error("Only single-column cursors are supported");return kn(s[0],e[0])}}function Rn(s,e){const{expression:t}=s[0]??{};if(!t||e.length===0)return;const n=e[0];if(n==null)return Vt(t);if(n instanceof Date)return Number.isFinite(n.getTime())?Me(Sn(t,new Q(n)),Lt(t,new Q(new Date(n.getTime()+1)))):void 0;if(typeof n!="object")return Mt(t,new Q(n))}const W=s=>{try{return s instanceof Error?s:new Error(String(s))}catch{return new Error("Unknown error")}};function se(){let s,e,t=!0;return{promise:new Promise((i,r)=>{s=o=>{t=!1,i(o)},e=o=>{t=!1,r(o)}}),resolve:s,reject:e,isPending:()=>t}}function yt(){const s=se();return s.promise.catch(()=>{}),s}function oe(s){s.abortController?.abort(),s.removeRequestAbortListener?.()}class On extends Ft{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.subsetDemands=[],this.primaryFailureDeliveryDepth=0,this.requestedSubsetWhere=new WeakMap,this.sentKeys=new Set,this.publishedRows=new Map,this.stalePublishedRows=new Map,this.limitedSnapshotRowCount=0,this._status="ready",this.statusRevision=0,this.pendingLoadSubsetParticipants=new Set,this.loadSubsetPromiseErrors=new WeakMap,this.truncateReplacementPending=!1,this.unsubscribed=!1,n.onUnsubscribe&&this.on("unsubscribed",n.onUnsubscribe),n.onLoadSubsetError&&this.on("loadSubset:error",n.onLoadSubsetError),n.whereExpression&&on(n.whereExpression,this.collection);const i=r=>{this.trackPublishedRows(r),this.trackSentKeys(r),t(r)};this.callback=i,this.filteredCallback=n.whereExpression?dn(this.callback,n):r=>(this.callback(r),!0),this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()}),this.collectionCleanup=this.collection.on("status:cleaned-up",()=>{this.handleCollectionCleanup()}),this.collectionRestartCleanup=this.collection.on("status:change",({status:r})=>{if(r!=="loading"&&r!=="ready")return;const o=this.collection._sync.getLoadSubsetSession(),a=this.truncateReplaySession;this.subsetDemands.some(c=>c.acquisitionState==="detached")&&this.setStatus("loadingSubset"),queueMicrotask(()=>{this.truncateReplaySession===a&&this.restartDetachedDemands(o)})})}get status(){return this._status}get lastError(){return this._lastError}handleCollectionCleanup(){this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.pendingLoadSubsetParticipants.clear();for(const e of[...this.subsetDemands])if(e.initialResult?.reject(new $),oe(e.acquisition),e.acquisitionState==="starting"){const t=this.subsetDemands.indexOf(e);t!==-1&&this.subsetDemands.splice(t,1)}else e.acquisitionState="detached",e.acquisition={options:e.requestOptions,loadSubsetSession:e.acquisition.loadSubsetSession};this.setReadyIfIdle()}restartDetachedDemands(e){if(this.unsubscribed||!this.isLoadSubsetSessionCurrent(e))return;if(this.collection.status==="error"||this.collection._sync.syncLoadSubsetFn===null){this.setReadyIfIdle();return}const t=this.subsetDemands.filter(r=>r.acquisitionState==="detached"&&!r.requestOptions.signal?.aborted);if(t.length===0){this.setReadyIfIdle();return}const n=this.createTruncateReplaySession(e,()=>{const r=this.collection.currentStateAsChanges({optimizedOnly:!1});return new Map((r??[]).filter(o=>o.type!=="delete").map(o=>[o.key,o.value]))}),i=n.currentAttempt;this.truncateReplaySession=n,this.setStatus("loadingSubset"),this.truncateReplaySession===n&&this.startTruncateReplayAttempt(n,i,t)}handleTruncate(){const t=this.collection._sync.syncLoadSubsetFn!==null?[...this.subsetDemands]:[];if(t.length===0&&this.stalePublishedRows.size===0){this.resetSnapshotTracking();return}let n=this.truncateReplaySession;n?(n.completion.isPending()||(n.completion=yt()),n.pendingSetups++,n.failures.clear(),n.currentAttempt={pendingCount:0,setupComplete:!1}):(n=this.createTruncateReplaySession(this.collection._sync.getLoadSubsetSession(),()=>new Map(this.publishedRows)),this.truncateReplaySession=n);const i=n.currentAttempt;if(this.setStatus("loadingSubset"),this.truncateReplaySession===n){this.options.truncateReplayPublication&&(this.truncateReplacementPending=!0,this.options.truncateReplayPublication.start());for(const r of t)r.acquisition.abortController?.abort();this.resetSnapshotTracking(),queueMicrotask(()=>{if(this.truncateReplaySession===n){if(!this.isLoadSubsetSessionCurrent(n.loadSubsetSession)){this.retireStaleTruncateReplay(n);return}this.startTruncateReplayAttempt(n,i,n.currentAttempt===i?t:[])}})}}startTruncateReplayDemand(e,t,n){const i=()=>this.truncateReplaySession===e&&e.currentAttempt===t,r=()=>i()&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.isDemandActive(n),o=h=>{r()&&e.failures.set(n,W(h))};n.initialResult&&e.completion.promise.then(n.initialResult.resolve,n.initialResult.reject);const a=n.acquisition,c=n.acquisitionState==="active";if(n.acquisitionState="detached",c)try{this.releaseAcquisition(a)}catch(h){o(h);return}if(!r()||n.requestOptions.signal?.aborted)return;const u=this.createSubsetAcquisition(n);n.acquisition=u,n.acquisitionState="starting";let d;try{d=this.loadSubset(u.options,r)}catch(h){n.acquisition===u&&(n.acquisitionState="detached"),oe(u),o(h);return}if(!r()){n.acquisition===u&&(n.acquisitionState="detached");try{this.releaseAcquisition(u)}catch(h){o(h)}return}n.acquisitionState="active",this.trackTruncateReplayParticipant(e,t,n,d),this.observeLoadSubsetResult(d,n,u.options,!0,()=>r()&&!u.options.signal?.aborted)}settleTruncateReplay(e,t){try{if(this.truncateReplaySession!==e)return;if(!this.isLoadSubsetSessionCurrent(e.loadSubsetSession)){this.retireStaleTruncateReplay(e);return}e.pending.delete(t)&&t.attempt.pendingCount--,this.checkTruncateReplayComplete(e)}catch(n){queueMicrotask(()=>{throw n})}}trackTruncateReplayParticipant(e,t,n,i){if(this.truncateReplaySession!==e||e.currentAttempt!==t&&t.setupComplete&&t.pendingCount===0||!(i instanceof Promise))return;const r={demand:n,attempt:t};t.pendingCount++,e.pending.add(r),i.then(()=>this.settleTruncateReplay(e,r),o=>{if(this.truncateReplaySession===e&&e.currentAttempt===t&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.subsetDemands.includes(n)){const a=this.normalizeLoadSubsetPromiseError(i,o);e.failures.set(n,a)}this.settleTruncateReplay(e,r)})}removeTruncateReplayParticipant(e){const t=this.truncateReplaySession;if(t){t.failures.delete(e);for(const n of t.pending)n.demand===e&&(t.pending.delete(n),n.attempt.pendingCount--)}}checkTruncateReplayComplete(e){if(this.truncateReplaySession!==e||e.pendingSetups>0||e.pending.size>0)return;const t=[...e.failures].find(([n])=>this.subsetDemands.includes(n));try{t?this.abandonTruncateReplay(e,t[1]):this.flushTruncateReplay(e)}finally{this.setReadyIfIdle()}}abandonTruncateReplay(e,t){if(this.truncateReplaySession!==e||(e.completion.reject(t),!e.privateRows))return;const n=e.publicationState;this.loadedInitialState=n.loadedInitialState,this.snapshotSent=n.snapshotSent,this.limitedSnapshotRowCount=n.limitedSnapshotRowCount,this.lastSentKey=n.lastSentKey}flushTruncateReplay(e){if(this.truncateReplaySession!==e)return;this.truncateReplaySession=void 0,this.truncateReplacementPending=!1;const{privateRows:t}=e;for(const n of this.stalePublishedRows.keys())t?.delete(n);this.stalePublishedRows.clear();try{if(t){const n=this.createStateDiff(this.publishedRows,t);n.length>0&&this.filteredCallback(n)}}finally{this.restorePublishedSnapshotTracking(),e.completion.resolve(),this.options.truncateReplayPublication?.succeed()}}restorePublishedSnapshotTracking(){if(this.sentKeys=new Set(this.publishedRows.keys()),!this.orderByIndex)return;this.limitedSnapshotRowCount=this.sentKeys.size;const e=this.orderByIndex.takeFromStart(this.sentKeys.size,t=>this.sentKeys.has(t));this.lastSentKey=e.at(-1)}bufferPrivately(e){const t=this.truncateReplaySession?.privateRows;if(!t)return!1;for(const n of e)n.type==="delete"?t.delete(n.key):t.set(n.key,n.value);return!0}createStateDiff(e,t){const n=[];for(const[i,r]of e){const o=t.get(i);o===void 0?n.push({type:"delete",key:i,value:r}):K(o,r)||n.push({type:"update",key:i,value:o,previousValue:r})}for(const[i,r]of t)e.has(i)||n.push({type:"insert",key:i,value:r});return n}get isBufferingForTruncate(){return this.truncateReplaySession!==void 0}setReadyIfIdle(){const e=this.truncateReplaySession,t=e&&(e.pendingSetups>0||e.pending.size>0);this.pendingLoadSubsetParticipants.size===0&&!t&&this.setStatus("ready")}isLoadSubsetSessionCurrent(e){return e===this.collection._sync.getLoadSubsetSession()}retireStaleTruncateReplay(e){this.truncateReplaySession===e&&(this.discardTruncateReplay(),this.stalePublishedRows.clear())}discardTruncateReplay(){const e=this.truncateReplaySession;e?.completion.isPending()&&e.completion.reject(new $),this.truncateReplaySession=void 0,this.truncateReplacementPending=!1}resetSnapshotTracking(){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0}createTruncateReplaySession(e,t){return{loadSubsetSession:e,publicationState:{loadedInitialState:this.loadedInitialState,snapshotSent:this.snapshotSent,limitedSnapshotRowCount:this.limitedSnapshotRowCount,lastSentKey:this.lastSentKey},privateRows:this.options.truncateReplayPublication?void 0:t(),pending:new Set,pendingSetups:1,currentAttempt:{pendingCount:0,setupComplete:!1},failures:new Map,completion:yt()}}startTruncateReplayAttempt(e,t,n){for(const i of n)if(this.subsetDemands.includes(i)&&(this.startTruncateReplayDemand(e,t,i),this.truncateReplaySession!==e||e.currentAttempt!==t))break;t.setupComplete=!0,e.pendingSetups--,this.checkTruncateReplayComplete(e)}get hasPendingTruncateReplacement(){return this.truncateReplacementPending}get pendingTruncateReplacement(){const e=this.truncateReplaySession?.completion;return e?.isPending()?e.promise:void 0}get hasFailedTruncateReplacement(){const e=this.truncateReplaySession?.completion;return this.truncateReplacementPending&&e!==void 0&&!e.isPending()}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this.unsubscribed||this._status===e)return;const t=this._status;this._status=e;const n=++this.statusRevision;if(this.emitInnerWhile("status:change",{type:"status:change",subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n),this.statusRevision!==n)return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n)}observeLoadSubsetResult(e,t,n,i,r=()=>!0){if(!(e instanceof Promise))return;const o=this.collection._sync.getLoadSubsetSession(),a={demand:t,promise:e};i&&(this.pendingLoadSubsetParticipants.add(a),this.setStatus("loadingSubset"));const c=()=>{i&&(this.pendingLoadSubsetParticipants.delete(a),this.isLoadSubsetSessionCurrent(o)&&this.setReadyIfIdle())};e.then(c,u=>{this.isLoadSubsetSessionCurrent(o)&&r()&&this.recordLoadSubsetError(n,this.normalizeLoadSubsetPromiseError(e,u)),c()})}normalizeLoadSubsetPromiseError(e,t){const n=this.loadSubsetPromiseErrors.get(e);if(n)return n;const i=W(t);return this.loadSubsetPromiseErrors.set(e,i),i}stopDemandStatusParticipants(e){for(const t of this.pendingLoadSubsetParticipants)t.demand===e&&this.pendingLoadSubsetParticipants.delete(t);this.setReadyIfIdle()}loadSubset(e,t=()=>!0){try{return this.collection._sync.loadSubset(e)}catch(n){const i=W(n);throw t()&&this.recordLoadSubsetError(e,i),i}}createSubsetAcquisition(e){const t=new AbortController,n=e.requestOptions.signal;let i;if(n?.aborted)t.abort(n.reason);else if(n){const r=()=>t.abort(n.reason);n.addEventListener("abort",r,{once:!0}),i=()=>n.removeEventListener("abort",r)}return{options:{...e.requestOptions,signal:t.signal},loadSubsetSession:this.collection._sync.getLoadSubsetSession(),abortController:t,removeRequestAbortListener:i}}releaseAcquisition(e,t=this.primaryFailureDeliveryDepth===0){if(!e.releaseAttempted){e.releaseAttempted=!0;try{e.abortController?.abort(),this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.collection._sync.unloadSubset(e.options)}catch(n){throw t?this.recordLoadSubsetError(e.options,W(n),!0):W(n)}finally{e.removeRequestAbortListener?.()}}}startSubsetDemand(e){const t={requestOptions:e,acquisition:{options:e,loadSubsetSession:this.collection._sync.getLoadSubsetSession()},acquisitionState:"starting"};if(this.collection.status==="cleaned-up"||this.collection.config.syncMode==="on-demand"&&(this.collection.status==="error"||this.collection.status!=="idle"&&this.collection._sync.syncLoadSubsetFn===null)){t.acquisitionState="detached",this.subsetDemands.push(t);const c=se();t.initialResult=c;const u=()=>c.reject(new $);e.signal?.addEventListener("abort",u,{once:!0});const d=()=>{e.signal?.removeEventListener("abort",u),t.initialResult=void 0};return c.promise.then(d,d),{demand:t,result:c.promise,started:!1}}const n=this.createSubsetAcquisition(t);t.acquisition=n;const i=this.truncateReplaySession,r=i?.currentAttempt,o=this.collection._sync.getLoadSubsetSession();this.subsetDemands.push(t);let a;try{a=this.loadSubset(n.options,()=>this.isLoadSubsetSessionCurrent(o)&&this.subsetDemands.includes(t)&&(i===void 0||this.truncateReplaySession===i&&i.currentAttempt===r))}catch(c){const u=this.subsetDemands.indexOf(t);throw u!==-1&&(i&&r&&this.truncateReplaySession===i&&i.currentAttempt===r&&i.failures.set(t,W(c)),this.subsetDemands.splice(u,1)),oe(n),c}if(!this.isLoadSubsetSessionCurrent(o)){const c=this.subsetDemands.indexOf(t);return c!==-1&&this.subsetDemands.splice(c,1),oe(n),{demand:t,result:a,started:!0}}return t.acquisitionState="active",this.subsetDemands.includes(t)?(i&&r&&this.trackTruncateReplayParticipant(i,r,t,a),{demand:t,result:a,started:!0}):(this.releaseAcquisition(n),{demand:t,result:a,started:!0})}isDemandActive(e){return!this.unsubscribed&&this.subsetDemands.includes(e)}recordLoadSubsetError(e,t,n=!1){const i=W(t);if(e.signal?.aborted&&!n)return i;this._lastError=i,this.primaryFailureDeliveryDepth++;try{this.emitInner("loadSubset:error",{type:"loadSubset:error",subscription:this,options:e,error:i})}finally{this.primaryFailureDeliveryDepth--}return i}emitEvents(e){if(this.unsubscribed)return!1;const t=this.filterAndFlipChanges(e);return e.length>0&&t.length===0||this.bufferPrivately(t)?!1:this.filteredCallback(t)}publishSnapshot(e){this.bufferPrivately(e)||this.callback(e)}requestSnapshot(e){if(this.unsubscribed||e?.signal?.aborted||this.loadedInitialState)return!1;const t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if("where"in e){const d=e.where;if(t.where){const h=t.where,l=Me(h,d);t.where=l}else t.where=d}}else this.loadedInitialState=!0;const n={where:t.where,signal:e?.signal,subscription:this,orderBy:e?.orderBy,limit:e?.limit},{demand:i,result:r,started:o}=this.startSubsetDemand(n);if(!this.isDemandActive(i)||(e?.where&&this.requestedSubsetWhere.set(n,e.where),e?.onLoadSubsetResult?.(r,i.acquisition.options,d=>this.releaseDemand(i,d)),!this.isDemandActive(i))||(o&&this.observeLoadSubsetResult(r,i,i.acquisition.options,e?.trackLoadSubsetPromise??!0),!this.isDemandActive(i)))return!1;let a;if(e?.onUnoptimized){if(a=this.collection.currentStateAsChanges({...t,optimizedOnly:!0}),a===void 0){if(e.onUnoptimized(),this.unsubscribed)return!1;a=this.collection.currentStateAsChanges({...t,optimizedOnly:!1})}}else a=this.collection.currentStateAsChanges(t);if(this.unsubscribed||a===void 0)return!1;const c=this.truncateReplaySession?.privateRows??this.publishedRows,u=a.filter(d=>!this.isBufferingForTruncate&&this.stalePublishedRows.has(d.key)||!this.sentKeys.has(d.key)&&!c.has(d.key));for(const d of u)this.sentKeys.add(d.key);return this.snapshotSent=!0,this.publishSnapshot(this.isBufferingForTruncate?u:this.reconcileStalePublishedChanges(u)),!0}releaseSnapshot(e){const t=this.subsetDemands.findIndex(n=>n.requestOptions.where===e||this.requestedSubsetWhere.get(n.requestOptions)===e);t!==-1&&this.releaseDemandAt(t)}releaseDemand(e,t){if(!t){const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n);return}try{this.recordLoadSubsetError(e.acquisition.options,t.error,!0)}finally{const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n,!1)}}releaseDemandAt(e,t=this.primaryFailureDeliveryDepth===0){const n=this.subsetDemands[e];if(!n)return;const i=this.truncateReplaySession,r=n.acquisition;this.subsetDemands.splice(e,1),n.initialResult?.reject(new $);const o=[()=>this.removeTruncateReplayParticipant(n),...n.acquisitionState==="active"?[()=>this.releaseAcquisition(r,t)]:[],()=>this.retireEmptyReplay(),()=>{i&&this.checkTruncateReplayComplete(i)},()=>this.stopDemandStatusParticipants(n)];Z(o)}retireEmptyReplay(){this.subsetDemands.length!==0||!this.truncateReplaySession||(this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.restorePublishedSnapshotTracking(),this.options.truncateReplayPublication?.succeed())}readOrderedSnapshot(e){const t=[this.options.whereExpression,e.where,e.cursor?.whereFrom].filter(i=>i!==void 0),n=this.collection.currentStateAsChanges({orderBy:e.orderBy,limit:e.limit,where:t.length>0?t.reduce((i,r)=>Me(i,r)):void 0});return Array.isArray(n)?n:[]}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:i,trackLoadSubsetPromise:r=!0,onLoadSubsetResult:o}){if(this.unsubscribed)return;if(!t)throw new Error("limit is required");if(!this.orderByIndex)throw new Error("Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.");const a=n?Cn(e,n):void 0,c=n!==void 0&&n.length>0,d=n?.[0],h=this.orderByIndex,l=this.options.whereExpression,p=l?te(l):void 0,f=C=>{if(C!==void 0&&this.sentKeys.has(C))return!1;const A=this.collection.get(C);return A===void 0?!1:p?.(A)??!0};let g=d;const w=[];let b=[];if(c){const{expression:C}=e[0],A=this.collection.currentStateAsChanges({where:Mt(C,new Q(d))});if(A){const V=A.map(D=>D.key).filter(D=>!this.sentKeys.has(D)&&f(D));b.push(...V);const R=h.take(t-b.length,d,f);b.push(...R)}else b=h.take(t,d,f)}else b=h.takeFromStart(t,f);const x=()=>Math.max(t-w.length,0),v=()=>b.length===0,k=e[0].expression,M=k.type==="ref"?zs(new Rt(k.path),!0):null;for(;x()>0&&!v();){for(const C of b){const A=this.collection.get(C);w.push({type:"insert",key:C,value:A}),g=M?M(A):A}b=h.take(x(),g,f)}const T=this.limitedSnapshotRowCount;for(const C of w)this.sentKeys.add(C.key);if(this.publishSnapshot(w),this.unsubscribed)return;this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,T+w.length),w.length>0&&(this.lastSentKey=w[w.length-1].key);let E;if(a&&n){const C=Rn(e,n);C&&(E={whereFrom:a,whereCurrent:C,lastKey:this.lastSentKey})}const m={where:l,limit:t,orderBy:e,cursor:E,offset:i??T,subscription:this},{demand:S,result:y,started:O}=this.startSubsetDemand(m);this.isDemandActive(S)&&(o?.(y,S.acquisition.options,C=>this.releaseDemand(S,C)),this.isDemandActive(S)&&(O&&this.observeLoadSubsetResult(y,S,S.acquisition.options,r),this.isDemandActive(S)))}filterAndFlipChanges(e){if(e=this.reconcileStalePublishedChanges(e),this.loadedInitialState||this.skipFiltering)return e;const t=this.isBufferingForTruncate,n=[];for(const i of e){let r=i;if(this.sentKeys.has(i.key)){if(i.type==="insert")continue;i.type==="delete"&&this.sentKeys.delete(i.key)}else if(i.type==="update")r={...i,type:"insert",previousValue:void 0},this.sentKeys.add(i.key);else if(i.type==="delete"){if(!t)continue}else this.sentKeys.add(i.key);n.push(r)}return n}reconcileStalePublishedChanges(e){if(this.stalePublishedRows.size===0)return e;const t=[];for(const n of e){const i=this.stalePublishedRows.get(n.key);if(i===void 0){t.push(n);continue}this.stalePublishedRows.delete(n.key),n.type==="delete"?t.push({...n,value:i,previousValue:void 0}):K(i,n.value)||t.push({...n,type:"update",previousValue:i})}if(this.collection.config.syncMode!=="on-demand"&&!this.isBufferingForTruncate)for(const[n,i]of this.stalePublishedRows)this.collection.has(n)||(this.stalePublishedRows.delete(n),t.push({type:"delete",key:n,value:i}));return t}trackPublishedRows(e){for(const t of e)t.type==="delete"?this.publishedRows.delete(t.key):this.publishedRows.set(t.key,t.value)}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(const t of e)t.type==="delete"?this.sentKeys.delete(t.key):this.sentKeys.add(t.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){if(this.unsubscribed)return;this.unsubscribed=!0,this.statusRevision++;const e=[this.truncateCleanup,this.collectionCleanup,this.collectionRestartCleanup];this.truncateCleanup=void 0,this.collectionCleanup=void 0,this.collectionRestartCleanup=void 0,Z([...e.map(t=>()=>t?.()),()=>{this.discardTruncateReplay(),this.stalePublishedRows.clear();const t=this.subsetDemands.filter(n=>n.acquisitionState==="active").map(n=>n.acquisition);for(const n of this.subsetDemands)n.initialResult?.reject(new $),this.stopDemandStatusParticipants(n),n.acquisitionState==="starting"&&oe(n.acquisition);this.subsetDemands=[],Z(t.map(n=>()=>this.releaseAcquisition(n)))},()=>this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),()=>this.clearListeners()])}}class Tn{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1,this.publicationDeferralDepth=0,this.discardDeferredPublications=!1,this.deferredStateRevision=0,this.deferredLayoutRevision=0,this.deferredPublications=[],this.layoutChangeListeners=new Set,this.stateRevision=0,this.layoutRevision=0}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){pt(()=>{try{Z([...this.changeSubscriptions].map(e=>()=>e.emitEvents([])))}catch(e){ft(e)}})}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1,n=!1){if(e.length>0&&this.stateRevision++,n&&this.layoutRevision++,this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let i=e;if(t){if(this.batchedEvents.length>0){const r=new Map(this.batchedEvents.map(o=>[o.key,o]));for(const o of e){const a=r.get(o.key);r.set(o.key,a?.type==="delete"&&o.type==="insert"?{...o,type:"update",previousValue:a.value}:o)}i=[...r.values()]}this.batchedEvents=[],this.shouldBatchEvents=!1}if(this.publicationDeferralDepth>0){this.deferredPublications.push({changes:i,layoutChanged:n});return}this.publishEvents(i,n)}deferPublication(){this.publicationDeferralDepth===0&&(this.deferredStateRevision=this.stateRevision,this.deferredLayoutRevision=this.layoutRevision),this.publicationDeferralDepth++;let e=!1;const t=n=>{if(e||(e=!0,this.publicationDeferralDepth===0)||(this.discardDeferredPublications||=n,this.publicationDeferralDepth--,this.publicationDeferralDepth>0))return;const i=this.deferredPublications;if(this.deferredPublications=[],this.discardDeferredPublications){this.discardDeferredPublications=!1,this.stateRevision=this.deferredStateRevision,this.layoutRevision=this.deferredLayoutRevision;return}this.publishEvents(i.flatMap(({changes:r})=>r),i.some(({layoutChanged:r})=>r))};return{publish:()=>t(!1),discard:()=>t(!0)}}publishEvents(e,t){if(e.length===0&&!t)return;const n=e.map(o=>this.enrichChangeWithVirtualProps(o)),i=[...this.layoutChangeListeners],r=[...this.changeSubscriptions];pt(()=>{const o=r.map(a=>()=>a.emitEvents(n));e.length===0&&o.unshift(...i);try{Z(o)}catch(a){ft(a)}})}subscribeLayoutChanges(e){return this.layoutChangeListeners.add(e),()=>this.layoutChangeListeners.delete(e)}subscribeChanges(e,t={}){if(t.where&&t.whereExpression)throw new Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");const{where:n,...i}=t;let r=i.whereExpression;if(n){const c=_t(),u=n(c);r=L(u)}this.addSubscriber();let o;const a={closed:!1};try{o=new On(this.collection,e,{...i,whereExpression:r,onUnsubscribe:()=>{a.closed=!0,this.removeSubscriber(),o&&this.changeSubscriptions.delete(o)}}),t.onStatusChange&&o.on("status:change",t.onStatusChange),t.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&o.markAllStateAsSeen(),a.closed||this.changeSubscriptions.add(o)}catch(c){if(o)try{o.unsubscribe()}catch{}else this.removeSubscriber();throw c}return o}addSubscriber(){const e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer();try{(this.lifecycle.status==="cleaned-up"||this.lifecycle.status==="idle")&&this.sync.startSync()}catch(t){throw this.activeSubscribersCount=e,this.activeSubscribersCount===0&&this.lifecycle.startGCTimer(),t}this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){const e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new rs;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1,this.deferredPublications=[],this.publicationDeferralDepth=0}}const xn=s=>setTimeout(()=>{s({didTimeout:!0,timeRemaining:()=>50})},0),En=s=>{clearTimeout(s)},Dn=typeof window<"u"&&"requestIdleCallback"in window?(s,e)=>window.requestIdleCallback(s,e):(s,e)=>xn(s),Pe=typeof window<"u"&&"cancelIdleCallback"in window?s=>window.cancelIdleCallback(s):En,Ut=class ae{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}schedule(e,t,n){const i=Date.now()+t;this.tasks.set(e,{executeAt:i,callback:n}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(e){this.tasks.delete(e)}updateTimeout(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let e=1/0;for(const n of this.tasks.values())n.executeAt<e&&(e=n.executeAt);const t=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;const e=Date.now();for(const[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(i){console.error("Error in CleanupQueue task:",i)}}this.tasks.size>0&&this.updateTimeout()}};Ut.instance=null;let Ie=Ut;class Pn{constructor(e,t){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.statusRevision=0,this.cleaningUp=!1,this.config=e,this.id=t}setDeps(e){this.indexes=e.indexes,this.events=e.events,this.changes=e.changes,this.sync=e.sync,this.state=e.state}validateStatusTransition(e,t){if(e===t)return;if(!{idle:["loading","error","cleaned-up"],loading:["ready","error","cleaned-up"],ready:["cleaned-up","error"],error:["ready","cleaned-up","idle"],"cleaned-up":["loading","error"]}[e].includes(t))throw new ns(e,t,this.id)}setStatus(e,t=!1){if(e==="ready"&&!t)throw new ie(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);const n=++this.statusRevision,i=this.status;this.status=e,this.events.emitStatusChange(e,i,()=>this.statusRevision===n)}validateCollectionUsable(e){switch(this.status){case"error":throw new ss(e,this.id);case"cleaned-up":this.sync.startSync();break}}markReady(){const e=this.applyReadyTransition();if(e)throw e.error}markReadyDuringSyncStart(){return this.applyReadyTransition()}applyReadyTransition(){if(this.validateStatusTransition(this.status,"ready"),this.status==="loading"||this.status==="error"){this.syncError=void 0;const e=this.statusRevision+1;if(this.setStatus("ready",!0),this.status!=="ready"||this.statusRevision!==e)return;const t=[];this.hasBeenReady||(this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0),t.push(...this.onFirstReadyCallbacks),this.onFirstReadyCallbacks=[]),t.push(()=>this.changes.emitEmptyReadyEvent());try{Z(t)}catch(n){return{error:n}}}}markError(e){this.validateStatusTransition(this.status,"error"),this.syncError=e,this.setStatus("error")}getSyncError(){return this.syncError}assertCanStartSync(){if(this.cleaningUp)throw new ie(`Cannot start collection "${this.id}" during cleanup. Restart after cleanup() completes.`)}startGCTimer(){const e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Ie.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Ie.getInstance().cancel(this),this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Pe(this.idleCallbackId),this.idleCallbackId=Dn(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(this.cleaningUp)return!0;if(!e||e.timeRemaining()>0||e.didTimeout){this.cleaningUp=!0;try{this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Ie.getInstance().cancel(this),this.hasBeenReady=!1,this.syncError=void 0,this.onFirstReadyCallbacks=[]}finally{this.cleaningUp=!1}return this.setStatus("cleaned-up"),this.changes.activeSubscribersCount===0&&this.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(e){return this.hasBeenReady?(e(),()=>{}):(this.onFirstReadyCallbacks.push(e),()=>{const t=this.onFirstReadyCallbacks.indexOf(e);t!==-1&&this.onFirstReadyCallbacks.splice(t,1)})}cleanup(){this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const In=Symbol("liveQueryInternal");class An{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.loadSubsetOperations=new Set,this.syncStartDeferred=!1,this.syncStartRequested=!1,this.deferredLoadSubsets=[],this.syncEpoch=0,this.loadSubsetSession=0,this.config=e,this.id=t,this.syncMode=e.syncMode??"eager"}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this._events=e.events}markLayoutChange(){this.getActivePendingSyncTransaction().layoutChanged=!0}startSync(){if(this.lifecycle.assertCanStartSync(),this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up")return;if(this.syncStartDeferred){this.syncStartRequested=!0;return}const e=++this.syncEpoch,t=()=>e===this.syncEpoch;if(this.lifecycle.setStatus("loading"),!t())return;let n=!0,i;try{const r=_n(this.config.sync.sync({collection:this.collection,begin:o=>{if(!t())return;const a=se();a.promise.catch(()=>{}),this.state.pendingSyncedTransactions.push({committed:!1,applicationStarted:!1,layoutChanged:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:o?.immediate,applied:a})},write:o=>{if(!t())return;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new Te;if(a.committed)throw new xe;let c;"key"in o?c=o.key:c=this.config.getKey(o.value),this.state.pendingLocalChanges.has(c)&&this.state.pendingLocalOrigins.add(c);let u=o.type;if(o.type==="insert"){const h=this.state.syncedData.has(c),l=a.deletedKeys.has(c),p=a.truncate===!0;if(h&&!l&&!p){const f=this.state.syncedData.get(c);if(f!==void 0&&K(f,o.value)||this.state.hydrationSeedKeys.has(c))u="update";else{const b=this.config.utils?.[In];throw new ls(c,this.id,{hasCustomGetKey:b?.hasCustomGetKey??!1,hasJoins:b?.hasJoins??!1,hasDistinct:b?.hasDistinct??!1})}}}const d={...o,type:u,key:c};a.operations.push(d),u==="delete"?(a.deletedKeys.add(c),a.rowMetadataWrites.set(c,{type:"delete"})):u==="insert"?d.metadata!==void 0?a.rowMetadataWrites.set(c,{type:"set",value:d.metadata}):a.rowMetadataWrites.set(c,{type:"delete"}):d.metadata!==void 0&&a.rowMetadataWrites.set(c,{type:"set",value:d.metadata})},commit:o=>{if(!t())return!0;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new Cs;if(a.committed)throw new Rs;if(o?.aborted)return this.state.cancelPendingSyncedTransaction(a),a.applied.promise;a.committed=!0;const c=()=>{this.state.cancelPendingSyncedTransaction(a)};if(o?.addEventListener("abort",c,{once:!0}),this.state.commitPendingTransactions(),!a.applied.isPending())return o?.removeEventListener("abort",c),!0;const u=a.applied.promise;if(o){const d=()=>{o.removeEventListener("abort",c)};u.then(d,d)}return u},markReady:()=>{t()&&(n?i??=this.lifecycle.markReadyDuringSyncStart():this.lifecycle.markReady())},markError:o=>{t()&&this.lifecycle.markError(o)},truncate:()=>{if(!t())return;const o=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!o)throw new Te;if(o.committed)throw new xe;o.operations=[],o.deletedKeys.clear(),o.rowMetadataWrites.clear(),o.truncate=!0,o.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi(t)}));if(n=!1,!t()){if(r?.cleanup?.(),i)throw i.error;return}if(this.syncCleanupFn=r?.cleanup??null,this.syncLoadSubsetFn=r?.loadSubset??null,this.syncUnloadSubsetFn=r?.unloadSubset??null,this.syncMode==="on-demand"&&!this.syncLoadSubsetFn)throw new ee(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(r){throw n=!1,t()&&this.lifecycle.markError(r),r}if(i)throw i.error}deferStart(){return this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up"?!1:(this.syncStartDeferred=!0,!0)}resumeStart(){if(!this.syncStartDeferred)return;this.syncStartDeferred=!1;const e=this.syncStartRequested||this.deferredLoadSubsets.length>0;this.syncStartRequested=!1;const t=this.deferredLoadSubsets;this.deferredLoadSubsets=[];const n=this.loadSubsetSession;try{e&&this.startSync()}catch(i){for(const{deferred:r}of t)r.reject(i);throw i}for(const{options:i,deferred:r}of t){const o=this.syncLoadSubsetFn;try{if(n!==this.loadSubsetSession||i.signal?.aborted)throw new $;const a=o?.(i)??!0;a instanceof Promise?a.then(c=>r.resolve(c),c=>r.reject(c)):r.resolve(void 0)}catch(a){r.reject(a)}}}getActivePendingSyncTransaction(){const e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Te;if(e.committed)throw new xe;return e}createSyncMetadataApi(e){return{row:{get:t=>{if(!e())return;const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],i=n?.rowMetadataWrites.get(t);if(i)return i.type==="delete"?void 0:i.value;if(!n?.truncate)return this.state.syncedMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"delete"})}},collection:{get:t=>{if(!e())return;const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(t);return i?i.type==="delete"?void 0:i.value:this.state.syncedCollectionMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"delete"})},list:t=>{if(!e())return[];const n=new Map(this.state.syncedCollectionMetadata),i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(i)for(const[r,o]of i.collectionMetadataWrites)o.type==="delete"?n.delete(r):n.set(r,o.value);return Array.from(n.entries()).filter(([r])=>t?r.startsWith(t):!0).map(([r,o])=>({key:r,value:o}))}}}}preload(){try{this.lifecycle.assertCanStartSync()}catch(t){return Promise.reject(t)}if(this.preloadPromise)return this.preloadPromise;this.syncMode==="on-demand"&&console.warn(`${this.id?`[${this.id}] `:""}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`);const e=new Promise((t,n)=>{if(this.lifecycle.status==="ready"){t();return}if(this.lifecycle.status==="error"){n(this.getPreloadError());return}let i=!1;const r={active:!1,ready:!1};let o=()=>{},a=()=>{};const c=()=>{if(r.active){r.ready=!0;return}i||(i=!0,o(),a(),this.rejectPreload===u&&(this.rejectPreload=void 0),t())},u=d=>{i||(i=!0,o(),a(),this.rejectPreload===u&&(this.rejectPreload=void 0),n(d))};if(this.rejectPreload=u,a=this.lifecycle.onFirstReady(c),o=this.collection.on("status:error",()=>{r.active||u(this.getPreloadError())}),this.lifecycle.status==="idle"||this.lifecycle.status==="cleaned-up"){r.active=!0;let d;try{this.startSync()}catch(h){d={error:h}}finally{r.active=!1}this.collection.status==="error"?u(this.getPreloadError()):r.ready?c():d&&u(d.error)}});return this.preloadPromise=e,e.then(void 0,()=>{this.preloadPromise===e&&(this.preloadPromise=null)}),e}getPreloadError(){const e=this.lifecycle.getSyncError();return e===void 0?new is:e}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}beginLoadSubsetOperation(){const e=this.activeLoadSubsetOperation,t={pending:new Set,waiting:!1,completed:!1,hasError:!1};return this.activeLoadSubsetOperation=t,this.loadSubsetOperations.add(t),{wait:()=>this.waitForLoadSubsetOperation(t),cancel:()=>{t.completed=!0,this.loadSubsetOperations.delete(t),this.activeLoadSubsetOperation===t&&(this.activeLoadSubsetOperation=e?.completed?void 0:e)}}}waitForLoadSubsetOperation(e){return e.waiting=!0,e.pending.size===0?(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?Promise.reject(e.error):!0):(e.deferred=se(),e.deferred.promise)}settleLoadSubsetOperation(e,t,n){e.completed||(e.pending.delete(t),!n.ok&&!e.hasError&&(e.hasError=!0,e.error=n.error),!(!e.waiting||e.pending.size>0)&&queueMicrotask(()=>{e.completed||e.pending.size>0||(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?e.deferred.reject(e.error):e.deferred.resolve())}))}trackLoadSubsetOperationPromise(e){const t=this.activeLoadSubsetOperation;!t||t.pending.has(e)||(t.pending.add(e),e.then(()=>this.settleLoadSubsetOperation(t,e,{ok:!0}),n=>this.settleLoadSubsetOperation(t,e,{ok:!1,error:n})))}trackLoadPromise(e){const t=this.loadSubsetSession,n=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),this.trackLoadSubsetOperationPromise(e),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:"start"});const i=()=>{if(t!==this.loadSubsetSession)return;const r=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),r&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"})};e.then(i,i)}getLoadSubsetSession(){return this.loadSubsetSession}loadSubset(e){if(e.signal?.aborted)return Promise.reject(new $);if(this.syncMode==="eager")return!0;if(this.syncStartDeferred){this.syncStartRequested=!0;const t=se();return this.deferredLoadSubsets.push({options:e,deferred:t}),this.trackLoadPromise(t.promise),t.promise}if(this.syncLoadSubsetFn){const t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){if(this.syncMode!=="eager"){if(this.syncStartDeferred){this.deferredLoadSubsets=this.deferredLoadSubsets.filter(t=>t.options!==e?!0:(t.deferred.reject(new $),!1));return}this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}}cleanup(){const e=++this.syncEpoch;this.loadSubsetSession++,this.rejectPreload?.(new Es);const t=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null;try{t?.()}catch(r){this.syncEpoch===e&&(this.syncCleanupFn=t),queueMicrotask(()=>{if(r instanceof Error){const o=new et(this.id,r);throw o.cause=r,o.stack=r.stack,o}else throw new et(this.id,r)})}this.preloadPromise=null,this.syncStartDeferred=!1,this.syncStartRequested=!1;const n=this.pendingLoadSubsetPromises.size>0;this.pendingLoadSubsetPromises.clear(),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"}),this.activeLoadSubsetOperation=void 0;for(const r of this.loadSubsetOperations)r.completed||(r.completed=!0,r.pending.clear(),r.hasError=!0,r.error=new $,r.deferred?.reject(r.error));this.loadSubsetOperations.clear();const i=this.deferredLoadSubsets;this.deferredLoadSubsets=[];for(const r of i)r.deferred.reject(new $)}}function _n(s){if(typeof s=="function")return{cleanup:s};if(typeof s=="object")return s}const mt=1;function ge(s,e){return s===e?0:s<e?-1:1}function Mn(s){return{kind:"constructor",...s.name?{name:s.name}:{}}}function B(s){if(s==null)return s;switch(typeof s){case"string":case"boolean":return s;case"number":return Number.isFinite(s)?s:null;case"bigint":return{__type:"bigint",value:s.toString()};case"function":case"symbol":return;case"undefined":return}if(Array.isArray(s))return s.map(n=>B(n)??null);if(s instanceof Date)return{__type:"date",value:s.toISOString()};if(s instanceof Set)return{__type:"set",values:Array.from(s).map(i=>B(i)??null).sort((i,r)=>ge(J(i),J(r)))};if(s instanceof Map)return{__type:"map",entries:Array.from(s.entries()).map(([i,r])=>({key:B(i)??null,value:B(r)??null})).sort((i,r)=>ge(J(i.key),J(r.key)))};if(s instanceof RegExp)return{__type:"regexp",value:s.toString()};const e={},t=Object.entries(s).sort(([n],[i])=>ge(n,i));for(const[n,i]of t){const r=B(i);r!==void 0&&(e[n]=r)}return e}function J(s){return s===null?"null":Array.isArray(s)?`[${s.map(J).join(",")}]`:typeof s!="object"?JSON.stringify(s):`{${Object.keys(s).sort((n,i)=>ge(n,i)).map(n=>`${JSON.stringify(n)}:${J(s[n])}`).join(",")}}`}function Ln(s,e,t,n,i){const r=Mn(n),o=B(e)??null,a=B(i),u=B({signatureVersion:mt,expression:o,options:a??null})??null,d=J(u);return{signatureVersion:mt,signature:d,indexId:s,name:t,expression:e,resolver:r,...a===void 0?{}:{options:a}}}function Le(s){if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(t=>Le(t));const e={};for(const[t,n]of Object.entries(s))e[t]=Le(n);return e}function Kn(s){return JSON.parse(JSON.stringify(s))}class Fn{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle,this.defaultIndexType=e.defaultIndexType,this.events=e.events}createIndex(e,t={}){this.lifecycle.validateCollectionUsable("createIndex");const n=++this.indexCounter,i=_t(),r=e(i),o=L(r),a=t.indexType??this.defaultIndexType;if(!a)throw new ee(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
|
|
3
|
+
import { BasicIndex } from '@tanstack/db'
|
|
4
|
+
createCollection({ defaultIndexType: BasicIndex, ... })`);const c=new a(n,o,t.name,t.options);c.build(this.state.entries()),this.indexes.set(n,c);const u=Ln(n,o,t.name,a,t.options);return this.indexMetadata.set(n,u),this.events.emitIndexAdded(u),c}removeIndex(e){this.lifecycle.validateCollectionUsable("removeIndex");const t=typeof e=="number"?e:e.id,n=this.indexes.get(t);if(!n||typeof e!="number"&&n!==e)return!1;this.indexes.delete(t);const i=this.indexMetadata.get(t);return this.indexMetadata.delete(t),i&&this.events.emitIndexRemoved(i),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:Kn(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:Le(e.options)}}))}updateIndexes(e){for(const t of this.indexes.values())for(const n of e)switch(n.type){case"insert":t.add(n.key,n.value);break;case"update":n.previousValue?t.update(n.key,n.previousValue,n.value):t.add(n.key,n.value);break;case"delete":t.remove(n.key,n.value);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}}const $t=new WeakMap;function Vn(s){return s!==null&&typeof s=="object"?$t.get(s)??s:s}const Un=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),$n=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),zn=new Set(["entries","keys","values","forEach"]);function de(s){return s!==null&&typeof s=="object"&&!(s instanceof Date)&&!(s instanceof RegExp)&&!z(s)}function qn(s,e,t,n){if(Un.has(s))return function(...i){const r=i[0];if(typeof r!="function")return e.apply(t.copy_,i);const o=(u,d)=>{if(de(u)){const h={tracker:t,prop:String(d)},{proxy:l}=n(u,h);return l}return u},a=function(u,d,h){const l=o(u,d);return r.call(this,l,d,h)};if(s==="reduce"||s==="reduceRight"){const u=function(d,h,l,p){const f=o(h,l);return r.call(this,d,f,l,p)};return e.apply(t.copy_,[u,...i.slice(1)])}const c=e.apply(t.copy_,[a,...i.slice(1)]);if((s==="find"||s==="findLast")&&c&&typeof c=="object"){const u=t.copy_.indexOf(c);if(u!==-1)return o(c,u)}return s==="filter"&&Array.isArray(c)?c.map(u=>{const d=t.copy_.indexOf(u);return d!==-1?o(u,d):u}):c}}function jn(s,e){return function(){const t=s.copy_;let n=0;return{next(){if(n>=t.length)return{done:!0,value:void 0};const i=t[n];let r=i;if(de(i)){const o={tracker:s,prop:String(n)},{proxy:a}=e(i,o);r=a}return n++,{done:!1,value:r}},[Symbol.iterator](){return this}}}}function gt(s,e,t){return function(...n){const i=s.apply(e.copy_,n);return t(e),i}}function Nn(s,e,t,n,i){if(!(!zn.has(s)&&e!==Symbol.iterator))return(...r)=>{const o=t.copy_,a=o instanceof Map;if(a&&s==="keys")return o.keys();const c=h=>de(h)?i(h,{tracker:t,prop:"",retainIdentity:!0}).proxy:h;if(s==="forEach"){const h=r[0];if(typeof h!="function")throw new TypeError("forEach callback must be a function");return o.forEach((l,p)=>{const f=c(l);h.call(r[1],f,a?p:f,n)})}const u=o.entries(),d=s==="entries"||a&&e===Symbol.iterator;return{next(){const h=u.next();if(h.done)return h;const[l,p]=h.value,f=c(p);return{done:!1,value:d?[a?l:f,f]:f}},[Symbol.iterator](){return this}}}}function U(s,e=new WeakMap){if(s==null||typeof s!="object")return s;if(e.has(s))return e.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(Array.isArray(s)){const i=[];return e.set(s,i),s.forEach((r,o)=>{i[o]=U(r,e)}),i}if(ArrayBuffer.isView(s)&&!(s instanceof DataView)){const i=Object.getPrototypeOf(s).constructor,r=new i(s.length);e.set(s,r);for(let o=0;o<s.length;o++)r[o]=s[o];return r}if(s instanceof Map){const i=new Map;return e.set(s,i),s.forEach((r,o)=>{i.set(o,U(r,e))}),i}if(s instanceof Set){const i=new Set;return e.set(s,i),s.forEach(r=>{i.add(U(r,e))}),i}if(z(s))return s;const t={};e.set(s,t);for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=U(s[i],e));const n=Object.getOwnPropertySymbols(s);for(const i of n)t[i]=U(s[i],e);return t}function je(s,e){const t=new Map;function n(l,p){if(t.has(l))return t.get(l);{const f=je(l,p);return t.set(l,f),f}}const i=new Map,r=e?.tracker.valueCopies??new WeakMap,o={valueCopies:r,copy_:e?r.get(s)??s:U(s,r),originalObject:U(s),modified:!1,assigned_:{},parent:e,target:s};function a(l){l.modified||(l.modified=!0),l.parent&&(l.parent.retainIdentity||(l.parent.tracker.copy_[l.parent.prop]=l.copy_,l.parent.tracker.assigned_[l.parent.prop]=!0),a(l.parent.tracker))}function c(l){if(l.copy_ instanceof Map||l.copy_ instanceof Set)return K(Array.from(l.copy_),Array.from(l.originalObject));if(Object.keys(l.assigned_).length===0&&Object.getOwnPropertySymbols(l.assigned_).length===0)return!0;for(const f in l.assigned_)if(l.assigned_[f]===!0){const g=l.copy_[f],w=l.originalObject[f];if(!K(g,w))return!1}else if(l.assigned_[f]===!1)return!1;const p=Object.getOwnPropertySymbols(l.assigned_);for(const f of p)if(l.assigned_[f]===!0){const g=l.copy_[f],w=l.originalObject[f];if(!K(g,w))return!1}else if(l.assigned_[f]===!1)return!1;return!0}function u(l){c(l)&&(l.modified=!1,l.assigned_={},l.parent&&u(l.parent.tracker))}function d(l){if(i.has(l))return i.get(l);const p=new Proxy(l,{get(f,g,w){const b=o.copy_[g]??o.originalObject[g];if(Object.getOwnPropertyDescriptor(f,g)?.get)return b;if(typeof b=="function"){if(Array.isArray(f)){const v=g.toString();if($n.has(v))return gt(b,o,a);const k=qn(v,b,o,n);if(k)return k;if(g===Symbol.iterator)return jn(o,n)}if(f instanceof Map||f instanceof Set){const v=g.toString(),k=T=>{const E=Vn(T);return E!==null&&typeof E=="object"?r.get(E)??E:E};if(v==="has"||v==="delete"||v==="add"||v==="set")return(...T)=>{f instanceof Set?T[0]=k(T[0]):v==="set"&&(T[1]=k(T[1]));const E=b.apply(f,T);return v!=="has"&&a(o),E===f?w:E};if(f instanceof Map&&v==="get")return T=>{const E=f.get(T);return de(E)?n(E,{tracker:o,prop:"",retainIdentity:!0}).proxy:E};if(v==="clear")return gt(b,o,a);const M=Nn(v,g,o,w,n);if(M)return M}return b.bind(f)}if(de(b)){const v={tracker:o,prop:String(g)},{proxy:k}=n(b,v);return i.set(b,k),k}return b},set(f,g,w){const b=o.copy_[g];if(!K(b,w)){const x=o.originalObject[g];K(w,x)?(delete o.assigned_[g.toString()],o.copy_[g]=U(x),c(o)?(o.modified=!1,o.assigned_={},e&&u(e.tracker)):o.modified=!0):(o.copy_[g]=w,o.assigned_[g.toString()]=!0,a(o))}return!0},defineProperty(f,g,w){const b=Reflect.defineProperty(f,g,w);return b&&"value"in w&&(o.copy_[g]=U(w.value),o.assigned_[g.toString()]=!0,a(o)),b},getOwnPropertyDescriptor(f,g){return Reflect.getOwnPropertyDescriptor(f,g)},preventExtensions(f){return Reflect.preventExtensions(f)},isExtensible(f){return Reflect.isExtensible(f)},deleteProperty(f,g){const w=typeof g=="symbol"?g.toString():g;if(w in f){const b=w in o.originalObject,x=Reflect.deleteProperty(f,g);return x&&(b?(o.assigned_[w]=!1,a(o)):(delete o.assigned_[w],Object.keys(o.assigned_).length===0&&Object.getOwnPropertySymbols(o.assigned_).length===0?o.modified=!1:o.modified=!0)),x}return!0}});return i.set(l,p),$t.set(p,o.copy_),p}return{proxy:d(o.copy_),getChanges:()=>{if(!o.modified)return{};if(typeof o.copy_!="object"||Array.isArray(o.copy_)||Object.keys(o.assigned_).length===0)return o.copy_;const l={},p=Object.keys(o.assigned_).some(f=>typeof o.copy_[f]=="object");for(const f in o.copy_){const g=o.copy_[f],w=o.originalObject[f];(o.assigned_[f]===!0||p&&o.copy_[f]!==o.copy_&&!K(g instanceof Set?Array.from(g):g,w instanceof Set?Array.from(w):w))&&f in o.copy_&&(l[f]=o.copy_[f])}return l}}}function Wn(s){const e=s.map(t=>je(t));return{proxies:e.map(t=>t.proxy),getChanges:()=>e.map(t=>t.getChanges())}}function Bn(s,e){const{proxy:t,getChanges:n}=je(s);return e(t),U(n())}function Hn(s,e){const{proxies:t,getChanges:n}=Wn(s);return e(t),U(n())}class Gn{constructor(){this.transactions=[],this.transactionStack=[],this.sequenceNumber=0}createTransaction(e){const t=new Xn(e,this,this.sequenceNumber++);return this.transactions.push(t),t}getActiveTransaction(){return this.transactionStack.at(-1)}getActiveTransactionForCollection(){const e=this.getActiveTransaction();if(e)return e;if(this!==we)return we.claimActiveTransaction(this)}claimActiveTransaction(e){const t=this.getActiveTransaction();if(!t)return;const n=ce(t);if(n===e)return t;if(n!==this)throw new Error("A transaction created with createTransaction() cannot mutate collections from multiple DbClient instances. Use dbClient.createTransaction() for explicit client scope.");return this.removeTransaction(t),e.transactions.push(t),e.transactionStack.push(t),t.sequenceNumber=e.sequenceNumber++,Ne.set(t,e),t}registerTransaction(e){ue.clear(e.id),this.transactionStack.push(e)}unregisterTransaction(e){try{ue.flush(e.id)}finally{this.transactionStack=this.transactionStack.filter(t=>t.id!==e.id)}}removeTransaction(e){const t=this.transactions.findIndex(n=>n.id===e.id);t!==-1&&this.transactions.splice(t,1)}rollbackConflictingTransactions(e,t){for(const n of[...this.transactions])n!==e&&n.state==="pending"&&n.mutations.some(i=>t.has(i.globalKey))&&n.rollback({isSecondaryRollback:!0})}clear(){const e=new Set([...this.transactions.map(t=>t.id),...this.transactionStack.map(t=>t.id)]);for(const t of e)ue.clear(t);this.transactions=[],this.transactionStack=[]}}const we=new Gn,Ne=new WeakMap,zt=new WeakMap;function ce(s){const e=Ne.get(s);if(!e)throw new Error("Transaction is not associated with a TransactionScope.");return e}function Yn(s){const e=zt.get(s);if(!e)throw new Error("Transaction is not associated with an ambient scope.");return e}function Jn(s,e){switch(`${s.type}-${e.type}`){case"insert-update":return{...s,type:"insert",original:{},modified:e.modified,changes:{...s.changes,...e.changes},key:s.key,globalKey:s.globalKey,metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata},mutationId:e.mutationId,updatedAt:e.updatedAt};case"insert-delete":return null;case"update-delete":return e;case"update-update":return{...e,original:s.original,changes:{...s.changes,...e.changes},metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata}};case"delete-delete":case"insert-insert":return e;default:{const t=`${s.type}-${e.type}`;throw new Error(`Unhandled mutation combination: ${t}`)}}}function Qn(s){return we.createTransaction(s)}function Zn(){return we.getActiveTransaction()}class Xn{constructor(e,t,n){if(typeof e.mutationFn>"u")throw new bs;this.id=e.id??le(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=se(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=n,this.metadata=e.metadata??{},Ne.set(this,t),zt.set(this,t)}setState(e){this.state=e,(e==="completed"||e==="failed")&&ce(this).removeTransaction(this)}mutate(e){if(this.state!=="pending")throw new ws;const t=ce(this),n=new Set([t,Yn(this)]);for(const i of n)i.registerTransaction(this);try{e()}finally{n.add(ce(this));for(const i of n)i.unregisterTransaction(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){const t=new Map;for(const n of this.mutations)t.set(n.globalKey,n);for(const n of e){const i=t.get(n.globalKey);if(i){const r=Jn(i,n);r===null?t.delete(n.globalKey):t.set(n.globalKey,r)}else t.set(n.globalKey,n)}this.mutations.length=0;for(const n of t.values())this.mutations.push(n)}rollback(e){const t=e?.isSecondaryRollback??!1;if(this.state==="completed")throw new vs;if(this.state==="failed")return this;if(this.setState("failed"),!t){const n=new Set(this.mutations.map(i=>i.globalKey));ce(this).rollbackConflictingTransactions(this,n)}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){const e=new Set;for(const t of this.mutations)e.has(t.collection.id)||(t.collection._state.onTransactionStateChange(),t.collection._state.pendingSyncedTransactions.length>0&&t.collection._state.commitPendingTransactions(),e.add(t.collection.id))}async commit(){if(this.state!=="pending")throw new ks;if(this.setState("persisting"),this.mutations.length===0)return this.setState("completed"),this.isPersisted.resolve(this),this;try{if(await this.mutationFn({transaction:this}),this.state!=="persisting")return this;this.setState("completed"),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){if(this.state!=="persisting")return this;const t=W(e);throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){const t=this.createdAt.getTime()-e.createdAt.getTime();return t!==0?t:this.sequenceNumber-e.sequenceNumber}}class ei{constructor(e,t){this.insert=(n,i)=>{this.lifecycle.validateCollectionUsable("insert");const r=this.state,o=this.getActiveTransaction();if(!o&&!this.config.onInsert)throw new ms;const a=Array.isArray(n)?n:[n],c=[],u=new Set;if(a.forEach(d=>{const h=this.validateData(d,"insert"),l=this.config.getKey(h);if(this.state.has(l)||u.has(l))throw new cs(l);u.add(l);const p=this.generateGlobalKey(l,d),f={mutationId:le(),original:{},modified:h,changes:Object.fromEntries(Object.keys(d).map(g=>[g,h[g]])),globalKey:p,key:l,metadata:i?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:i?.optimistic??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(f)}),o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;{const d=this.createTransaction({metadata:{[ye]:!0},mutationFn:async h=>await this.config.onInsert({transaction:h.transaction,collection:this.collection})});return d.applyMutations(c),this.markPendingLocalOrigins(c),d.commit().catch(()=>{}),r.transactions.set(d.id,d),r.scheduleTransactionCleanup(d),r.recomputeOptimisticState(!0),d}},this.delete=(n,i)=>{const r=this.state;this.lifecycle.validateCollectionUsable("delete");const o=this.getActiveTransaction();if(!o&&!this.config.onDelete)throw new Ss;if(Array.isArray(n)&&n.length===0)throw new ps;const a=Array.isArray(n)?n:[n],c=[];for(const d of a){if(!this.state.has(d))throw new ys(d);const h=this.generateGlobalKey(d,this.state.get(d)),l={mutationId:le(),original:this.state.get(d),modified:this.state.get(d),changes:this.state.get(d),globalKey:h,key:d,metadata:i?.metadata,syncMetadata:r.syncedMetadata.get(d)||{},optimistic:i?.optimistic??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(l)}if(o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;const u=this.createTransaction({autoCommit:!0,metadata:{[ye]:!0},mutationFn:async d=>this.config.onDelete({transaction:d.transaction,collection:this.collection})});return u.applyMutations(c),this.markPendingLocalOrigins(c),u.commit().catch(()=>{}),r.transactions.set(u.id,u),r.scheduleTransactionCleanup(u),r.recomputeOptimisticState(!0),u},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}setTransactionScope(e){this.transactionScope=e}getActiveTransaction(){return this.transactionScope?this.transactionScope.getActiveTransactionForCollection():Zn()}createTransaction(e){return this.transactionScope?this.transactionScope.createTransaction(e):Qn(e)}ensureStandardSchema(e){if(e&&"~standard"in e)return e;throw new ts}validateData(e,t,n){if(!this.config.schema)return e;const i=this.ensureStandardSchema(this.config.schema);if(t==="update"&&n){const o=this.state.get(n);if(o&&e&&typeof e=="object"&&typeof o=="object"){const a=Object.assign({},o,e),c=i["~standard"].validate(a);if(c instanceof Promise)throw new Xe;if("issues"in c&&c.issues){const l=c.issues.map(p=>({message:p.message,path:p.path?.map(f=>String(f))}));throw new Ze(t,l)}const u=c.value,d=Object.keys(e);return Object.fromEntries(d.map(l=>[l,u[l]]))}}const r=i["~standard"].validate(e);if(r instanceof Promise)throw new Xe;if("issues"in r&&r.issues){const o=r.issues.map(a=>({message:a.message,path:a.path?.map(c=>String(c))}));throw new Ze(t,o)}return r.value}generateGlobalKey(e,t){if(typeof e!="string"&&typeof e!="number")throw typeof e>"u"?new os(t):new as(e,t);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(const t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,n){if(typeof e>"u")throw new us;const i=this.state;this.lifecycle.validateCollectionUsable("update");const r=this.getActiveTransaction();if(!r&&!this.config.onUpdate)throw new gs;const o=Array.isArray(e),a=o?e:[e];if(o&&a.length===0)throw new ds;const c=typeof t=="function"?t:n,u=typeof t=="function"?{}:t,d=a.map(f=>{const g=this.state.get(f);if(!g)throw new hs(f);return g});let h;o?h=Hn(d,c):h=[Bn(d[0],c)];const l=a.map((f,g)=>{const w=h[g];if(!w||Object.keys(w).length===0)return null;const b=d[g],x=this.validateData(w,"update",f),v=Object.assign({},b,x),k=this.config.getKey(b),M=this.config.getKey(v);if(k!==M)throw new fs(k,M);const T=this.generateGlobalKey(M,v);return{mutationId:le(),original:b,modified:v,changes:Object.fromEntries(Object.keys(w).map(E=>[E,v[E]])),globalKey:T,key:f,metadata:u.metadata,syncMetadata:i.syncedMetadata.get(f)||{},optimistic:u.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(l.length===0){const f=this.createTransaction({mutationFn:async()=>{}});return f.commit().catch(()=>{}),i.scheduleTransactionCleanup(f),f}if(r)return r.applyMutations(l),i.transactions.set(r.id,r),i.scheduleTransactionCleanup(r),i.recomputeOptimisticState(!0),r;const p=this.createTransaction({metadata:{[ye]:!0},mutationFn:async f=>this.config.onUpdate({transaction:f.transaction,collection:this.collection})});return p.applyMutations(l),this.markPendingLocalOrigins(l),p.commit().catch(()=>{}),i.transactions.set(p.id,p),i.scheduleTransactionCleanup(p),i.recomputeOptimisticState(!0),p}}class ti extends Ft{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t,n){if(this.emitInnerWhile("status:change",{type:"status:change",collection:this.collection,previousStatus:t,status:e},n),!n())return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,collection:this.collection,previousStatus:t,status:e},n)}emitSubscribersChange(e,t){this.emit("subscribers:change",{type:"subscribers:change",collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}emitIndexAdded(e){this.emit("index:added",{type:"index:added",collection:this.collection,index:e})}emitIndexRemoved(e){this.emit("index:removed",{type:"index:removed",collection:this.collection,index:e})}cleanup(){this.clearListeners()}}function si(s){const e=new ni(s);return s.utils?e.utils=s.utils:e.utils={},e}class ni{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(t,n)=>this._mutations.insert(t,n),this.delete=(t,n)=>this._mutations.delete(t,n),!e)throw new Xt;if(!e.sync)throw new es;if(e.id?this.id=e.id:this.id=le(),this.config={...e,autoIndex:e.autoIndex??"off"},this.config.autoIndex==="eager"&&!e.defaultIndexType)throw new ee(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
|
|
5
|
+
import { BasicIndex } from '@tanstack/db'
|
|
6
|
+
createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);Qt(this),this._changes=new Tn,this._events=new ti,this._indexes=new Fn,this._lifecycle=new Pn(e,this.id),this._mutations=new ei(e,this.id),this._state=new fn(e),this._sync=new An(e,this.id),this.comparisonOpts=ii(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}get _stateRevision(){return this._changes.stateRevision}get _layoutRevision(){return this._changes.layoutRevision}_subscribeLayoutChanges(e){return this._changes.subscribeLayoutChanges(e)}_markLayoutChange(){this._sync.markLayoutChange()}_deferPublication(){return this._changes.deferPublication()}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status==="ready"}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}_setTransactionScope(e){this._mutations.setTransactionScope(e)}_hasHydratedKey(e){return this._state.hydratedKeys.has(e)}_deferSyncStart(){return this._sync.deferStart()}_resumeSyncStart(){this._sync.resumeStart()}preload(){return this._sync.preload()}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(const[n,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,n++));return t}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this._indexes.createIndex(e,t)}removeIndex(e){return this._indexes.removeIndex(e)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(e,t,n){return this._mutations.validateData(e,t,n)}get compareOptions(){return{...this.comparisonOpts}}update(e,t,n){return this._mutations.update(e,t,n)}get state(){const e=new Map;for(const[t,n]of this.entries())e.set(t,n);return e}stateWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return un(this,e)}subscribeChanges(e,t={}){return this._changes.subscribeChanges(e,t)}on(e,t){return this._events.on(e,t)}once(e,t){return this._events.once(e,t)}off(e,t){this._events.off(e,t)}waitFor(e,t){return this._events.waitFor(e,t)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}}function ii(s){if(s.defaultStringCollation){const e=s.defaultStringCollation;return{stringSort:e.stringSort??"locale",locale:e.stringSort==="locale"?e.locale:void 0,localeOptions:e.stringSort==="locale"?e.localeOptions:void 0}}else return{stringSort:"locale"}}function ri(s){const e=s.getMapping(),t=new Map;for(const[n,i]of Object.entries(e.columns))i.predicate!=="@id"&&t.set(n,i.predicate);return t}function We(s,e){const t=new Map;for(const[i,r]of ri(e))t.set(r,i);const n=new Map;for(const[i,r]of Object.entries(s.fields))n.set(i,{field:i,descriptor:r,column:t.get(r.predicate)});return n}function oi(s){return Wt(s.storage.resourceIdPattern)}function ai(s,e){const t=e.getType();if(s.class!==t)throw new F("mapping_class_mismatch",`descriptor ${s.uri} declares class ${s.class} but table ${e.config.name} reads ${t}`)}function Be(s){return new Set(Object.entries(s.fields).filter(([,e])=>e.secret===!0).map(([e])=>e))}function qt(s){const e=Be(s);return Object.entries(s.fields).filter(([t])=>!e.has(t)).sort(([,t],[,n])=>t.predicate<n.predicate?-1:t.predicate>n.predicate?1:0).map(([t])=>t)}function ci(s){return typeof s=="object"&&s!==null&&typeof s.termType=="string"&&typeof s.value=="string"}function li(s){const e=s.datatype;if(e)return typeof e=="string"?e:e.value}function St(s,e){if(e==null||e==="")return;const t=ci(e)?e:void 0,n=t?t.value:e,i=t?li(t):void 0;switch(s.type){case"uri":return t&&t.termType!=="NamedNode",String(n);case"string":case"text":return String(n);case"number":{if(typeof n=="number")return n;const r=Number(n);return Number.isFinite(r)?r:void 0}case"boolean":return typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:!!n;case"timestamp":{const r=n instanceof Date?n:new Date(String(n));return Number.isNaN(r.getTime())?void 0:r}case"json":{if(!t)return e;if(i&&!/#json(Array)?$/u.test(i)&&n==="")return;try{return JSON.parse(String(n))}catch{return n}}default:return n}}function ui(s,e){if(s.array){if(e==null)return;const n=(Array.isArray(e)?e:[e]).map(i=>St(s,i)).filter(i=>i!==void 0);return n.length>0?n:void 0}return St(s,e)}function di(s,e,t){const n=We(s,e),i=oi(s),r=Be(s),o=[];for(const a of t){const c=Nt(s,a);if(c===void 0)continue;const u={id:c};i!=="id"&&(u[i]=c);const d=a["@id"]??a.uri??a.subject;typeof d=="string"&&(u["@id"]=d);for(const h of n.values()){if(r.has(h.field)||h.column===void 0)continue;const l=ui(h.descriptor,a[h.column]);l!==void 0&&(u[h.field]=l)}o.push(u)}return o}function hi(s,e,t,n){const i=We(s,e),r={id:n.resourceId};for(const[o,a]of Object.entries(t)){if(o==="id"||o==="@id")continue;const c=i.get(o);!c||c.column===void 0||n.includeField&&!n.includeField(o)||(r[c.column]=a)}return r}function He(s){return s.array===!0&&s.type==="uri"}async function fi(s,e){return typeof s.isInitialized!="function"||s.isInitialized()||await e.init?.(s),await e.select().from(s).execute()}async function pi(s,e={}){return{etag:void 0,subjects:(await fi(s.table,s.database)).filter(n=>Bt(s.descriptor,s.document,s.podUrl,n))}}function yi(s){const t=s.getDialect?.()?.config?.session?.fetch;return typeof t=="function"?t:void 0}const mi=new Set;function ne(s){const e=s,t={};for(const[n,i]of Object.entries(e))n.startsWith("$")||(t[n]=i);return t}function X(s){if(s instanceof Date)return s.toISOString();if(Array.isArray(s))return s.map(e=>X(e));if(s&&typeof s=="object"){if(s instanceof Set)return[...s].map(t=>X(t));const e=Object.entries(s).filter(([,t])=>t!==void 0).sort(([t],[n])=>t<n?-1:t>n?1:0);return Object.fromEntries(e.map(([t,n])=>[t,X(n)]))}return s}function jt(s,e){const t=ne(s),n={};t.id!==void 0&&(n.id=X(t.id));for(const i of e)t[i]!==void 0&&(n[i]=X(t[i]));return JSON.stringify(n)}function gi(s,e){return s===void 0||e===void 0?s===e:JSON.stringify(X(s))===JSON.stringify(X(e))}function Si(s,e,t=mi){if(s===void 0)return!1;const n=ne(s),i=ne(e);for(const[r,o]of Object.entries(i))if(!(r==="@id"||o===void 0)&&!t.has(r)&&!gi(n[r],o))return!1;return!0}function bi(s){const e=new Set(s.presentKeys),t=[],n=[],i=[],r=o=>{const a=s.knownHash(o);if(a!==void 0)return a;const c=s.presentRow?.(o);return c===void 0?void 0:s.hashOf(c)};for(const[o,a]of s.next){if(s.pendingKeys.has(o)){e.has(o)&&r(o)!==s.hashOf(a)&&n.push({key:o,row:a});continue}if(!e.has(o)){t.push({key:o,row:a});continue}r(o)!==s.hashOf(a)&&n.push({key:o,row:a})}for(const o of e){if(s.next.has(o)||s.pendingKeys.has(o))continue;const a=s.presentRow?.(o);a!==void 0&&i.push({key:o,row:a})}return{inserts:t,updates:n,deletes:i}}function wi(){let s;return{promise:new Promise(t=>{s=()=>t()}),resolve:s}}function vi(s){const e=new Set,t=new Map,n=[],i=a=>{e.delete(a),t.delete(a)};return{keys:e,entries:t,conflicts:n,register:a=>{i(a.key);const c=wi(),u={...a,settled:!1,error:void 0,settledPromise:c.promise,resolveSettled:c.resolve};return t.set(a.key,u),e.add(a.key),u},clear:i,settle:(a,c)=>{a.settled||(a.error=c,a.settled=!0,a.resolveSettled())},isConfirmed:a=>t.get(a)?.settled===!0&&t.get(a)?.error===void 0,recordConflict:a=>{n.push(a),s?.(a)}}}function bt(s,e,t){s.recordConflict({key:e.key,server:t,local:e.localRow??e.intent??t,at:Date.now()}),s.settle(e,new F("write_conflict",`row ${e.key} was changed by someone else; server wins`))}function ki(s,e,t,n=Ci){for(const i of s.entries.values()){if(i.settled)continue;const r=e.get(i.key);if(i.intent===void 0){if(r===void 0){s.settle(i);continue}i.beforeHash!==void 0&&t(r)!==i.beforeHash&&bt(s,i,r);continue}if(Si(r,i.intent,n)){s.settle(i);continue}if(r!==void 0&&t(r)!==i.beforeHash){bt(s,i,r);continue}r===void 0&&i.beforeHash!==void 0&&s.settle(i,new F("write_conflict",`row ${i.key} disappeared before the write was confirmed; server wins`))}}const Ci=new Set;function wt(s,e){if(!(typeof s!="string"||s.length===0))return/^[a-z][a-z0-9+.-]*:/iu.test(s)?s:new URL(s,e).toString()}async function Ri(s,e,t){const n=s.descriptor.fields[e];if(!n||!He(n))throw new F("write_field_not_uri_array",`field ${e} is not array+uri; it must go through the ORM`);const i=Ht(s.document),r=(Array.isArray(t.previous)?t.previous:[t.previous]).map(h=>wt(h,i)).filter(h=>h!==void 0),o=(Array.isArray(t.next)?t.next:[t.next]).map(h=>wt(h,i)).filter(h=>h!==void 0),a=h=>h.map(l=>`<${t.subjectIri}> <${n.predicate}> <${l}> .`).join(`
|
|
7
|
+
`),c=[r.length>0?`DELETE DATA { ${a(r)} }`:void 0,o.length>0?`INSERT DATA { ${a(o)} }`:void 0].filter(h=>h!==void 0);if(c.length===0)return;const u=s.authenticatedFetch??yi(s.database);if(!u)throw new F("write_field_no_fetch","array+uri fields need an authenticated fetch (SolidAuthSession.fetch); none available");const d=await u(i,{method:"PATCH",headers:{"content-type":"application/sparql-update"},body:c.join(`;
|
|
8
|
+
`)});if(!d.ok)throw new F("write_field_rejected",`SPARQL PATCH for ${e} failed with HTTP ${d.status}`)}function Oi(s){const{descriptor:e,table:t,pending:n}=s,i=qt(e),r=d=>jt(d,i),o=new Set(Object.entries(e.fields).filter(([,d])=>He(d)).map(([d])=>d)),a=We(e,t),c=d=>a.get(d)?.column,u=async(d,h)=>{try{await h()}catch(l){throw n.clear(d),l instanceof Error?l:new F("write_failed",String(l),{cause:l})}try{await s.confirm(d)}finally{n.clear(d)}};return{onInsert:async({transaction:d})=>{for(const h of d.mutations){const l=h.modified,p=String(h.key),f=Oe(e,s.document,s.podUrl,p),g=Ge(e,s.document,p);n.register({key:p,intent:l,localRow:l,beforeHash:void 0}),await u(p,async()=>{const w=hi(e,t,l,{resourceId:f,includeField:b=>!o.has(b)});await s.database.insert(t).values(w).execute(),await vt(s,l,g,void 0,l)})}},onUpdate:async({transaction:d})=>{for(const h of d.mutations){const l=String(h.key),p=h.original,f=h.modified,g=h.changes,w=Oe(e,s.document,s.podUrl,l),b=Ge(e,s.document,l),x=p&&Object.keys(p).length>0?r(p):void 0;n.register({key:l,intent:f,localRow:f,beforeHash:x}),await u(l,async()=>{const v={};for(const[k,M]of Object.entries(g)){if(o.has(k))continue;const T=c(k);T!==void 0&&(v[T]=M)}if(Object.keys(v).length>0&&!await s.database.updateById(t,w,v))throw new F("write_rejected",`drizzle-solid did not update ${w}`);await vt(s,g,b,p,f)})}},onDelete:async({transaction:d})=>{for(const h of d.mutations){const l=String(h.key),p=h.original,f=Oe(e,s.document,s.podUrl,l);n.register({key:l,intent:void 0,localRow:p,beforeHash:p&&Object.keys(p).length>0?r(p):void 0}),await u(l,async()=>{await s.database.deleteById(t,f)})}}}}async function vt(s,e,t,n,i){for(const[r,o]of Object.entries(s.descriptor.fields))He(o)&&r in e&&await Ri(s,r,{subjectIri:t,previous:n?.[r],next:i?.[r]})}const Ae={available:!1,unsubscribe:()=>{}};function Ti(s,e,t){if(!s||typeof s.watch!="function")return Ae;try{const n=s.watch(e,t);if(typeof n!="function")return Ae;let i=!0;return{available:!0,unsubscribe:()=>{i&&(i=!1,n())}}}catch{return Ae}}const xi=75,Ei=2;function Di(s){return new Promise(e=>{setTimeout(e,s)})}function Pi(s){const{descriptor:e,table:t,database:n,document:i,podUrl:r,pending:o}=s,a=s.coalesceMs??xi,c=s.confirmRetries??Ei,u=qt(e),d=Be(e),h=R=>jt(R,u);let l,p,f=!1,g=!1,w=!1,b="initializing",x,v=[],k,M=!1,T=!1,E;async function m(){if(l)return l;const R=s.collection();if(!R)throw new F("sync_not_started","collection has not started syncing yet");if(await R.preload(),!l)throw new F("sync_not_started","collection sync did not start");return l}function S(){T||x!==void 0||(x=setTimeout(()=>{x=void 0,y().catch(()=>{b="degraded"})},a))}function y(){if(k)return M=!0,k;const R=(async()=>{try{do M=!1,await O();while(M&&!T)}finally{k=void 0}})();return k=R,R}async function O(){const R=await m();if(T)return;let D;try{D=await pi({descriptor:e,table:t,database:n,document:i,podUrl:r},{ifNoneMatch:E})}catch(P){b="degraded",!g&&!w&&(w=!0,R.markError(P));return}D.etag!==void 0&&(E=D.etag);const Y=di(e,t,D.subjects),re=new Map(Y.map(P=>[String(P.id),P])),Ce=[...R.collection.keys()].map(P=>String(P)),Re=P=>R.metadata?.row.get(P)?.hash,N=bi({next:re,presentKeys:Ce,pendingKeys:o.keys,knownHash:Re,hashOf:h,presentRow:P=>R.collection.get(P)});if(N.inserts.length+N.updates.length+N.deletes.length>0){R.begin({immediate:!0});for(const P of N.inserts)R.write({type:"insert",value:ne(P.row)});for(const P of N.updates)R.write({type:"update",value:ne(P.row)});for(const P of N.deletes)R.write({type:"delete",key:P.key,value:ne(P.row)});for(const P of[...N.inserts,...N.updates])R.metadata?.row.set(P.key,{hash:h(P.row)});await R.commit()}g||(g=!0,w=!1,R.markReady()),ki(o,re,h,d),b=f?"live":"unavailable"}async function C(R){const D=o.entries.get(R);if(D)for(let Y=0;;Y+=1){if(await y(),D.settled){if(D.error)throw D.error;return}if(Y>=c)throw new F("write_unconfirmed",`write to ${R} was not visible in the document after ${c+1} reads`);await Di(a)}}const A=R=>T?()=>{}:(l=R,p=Ti(s.feed,i,()=>{if(!g){v.push({topic:i});return}S()}),f=p.available,y().then(()=>{if(T)return;const D=v;v=[],D.length>0&&S()}).catch(()=>{b="degraded"}),()=>{V()});function V(){T||(T=!0,x!==void 0&&(clearTimeout(x),x=void 0),p?.unsubscribe(),p=void 0,v=[])}return{sync:A,refresh:()=>y(),confirmPending:C,state:()=>b,dispose:V,truncate:()=>{!l||T||(l.begin({immediate:!0}),l.truncate(),Promise.resolve(l.commit()).catch(()=>{}))}}}function Ii(s,e){ai(s,e.table);const t=Ct(s,{podUrl:e.podUrl,document:e.document,scope:e.scope}),n=vi(e.onConflict);let i;const r=Pi({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,feed:e.feed,coalesceMs:e.coalesceMs,confirmRetries:e.confirmRetries,pending:n,collection:()=>i}),o=Oi({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,pending:n,confirm:c=>r.confirmPending(c)}),a=si({id:`pod-collection:${s.uri}:${t}`,getKey:c=>c.id,sync:{sync:r.sync,rowUpdateMode:"full"},startSync:!0,onInsert:o.onInsert,onUpdate:o.onUpdate,onDelete:o.onDelete});return i=a,Object.assign(a,{tableDocument:t,pendingKeys:n.keys,conflicts:n.conflicts,refresh:()=>r.refresh(),syncState:()=>r.state(),dispose:()=>r.dispose(),truncateForTest:()=>r.truncate()})}function kt(s){const e=s;if(typeof e.syncState!="function"||typeof e.dispose!="function")throw new F("collection_not_from_define","collection was not created by definePodCollection()");return e}function Mi(s){const e=new Map,t=new Set;let n;const i=()=>{for(const a of[...t])a()},r=(a,c)=>`${a.uri}\0${c}`,o=(a,c)=>{const u=Ct(a,{podUrl:s.podUrl,document:c.document,scope:c.scope}),d=r(a,u),h=e.get(d);if(h)return h;const l=Ii(a,{...c,database:s.database,podUrl:s.podUrl,feed:s.feed});return e.set(d,l),l.preload().then(i,i),l};return{define:o,async load(a,c){return o(a,c)},syncState(a){return kt(a).syncState()},subscribeSyncState(a){return t.add(a),t.size===1&&typeof s.feed?.subscribeState=="function"&&(n=s.feed.subscribeState(i)),()=>{t.delete(a),t.size===0&&(n?.(),n=void 0)}},dispose(){for(const a of e.values())kt(a).dispose();e.clear(),n?.(),n=void 0,i()}}}export{Mi as createPodCollectionsCapability};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as t}from"./dashboard-
|
|
1
|
+
import{c as t}from"./dashboard-DWZ-fmCT.js";const c=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],o=t("rotate-ccw",c);export{o as R};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function d(t,e={}){return[{label:"Files",value:t.CSS_ROOT_FILE_PATH||"Runtime default",detail:"Authority file storage root"},{label:"Object storage",value:t.MINIO_ENDPOINT||t.XPOD_STORAGE_S3_ENDPOINT?"Configured":"Not configured",detail:t.MINIO_ENDPOINT||t.XPOD_STORAGE_S3_ENDPOINT||"Filesystem fallback"},{label:"Identity database",value:a(t,e,"CSS_IDENTITY_DB_URL"),detail:r(t.CSS_IDENTITY_DB_URL)},{label:"Cache / coordination",value:a(t,e,"REDIS_URL"),detail:t.REDIS_URL?"Redis":"Runtime fallback"},{label:"RDF / Quadstore",value:a(t,e,"CSS_SPARQL_ENDPOINT"),detail:o(t.CSS_SPARQL_ENDPOINT)}]}function u(t){return{cloud:t.registered||t.managed||t.domainAllocated}}function a(t,e,i){return t[i]||e[i]?.configured?"Configured":"Runtime default"}function r(t){return t?.startsWith("postgres")?"PostgreSQL":t?"SQLite / configured database":"SQLite default"}function o(t){return t?t.startsWith("postgres")?"PostgreSQL RDF":t.startsWith("sqlite")?"SQLite Quadstore":t.startsWith("http")?"Remote SPARQL endpoint":"Configured SPARQL endpoint":"Local Quadstore"}export{d as a,u as p};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as t,f as n}from"./dashboard-
|
|
1
|
+
import{j as t,f as n}from"./dashboard-DWZ-fmCT.js";function m({className:e,...s}){return t.jsx("div",{className:n("animate-pulse rounded-md bg-muted/50",e),...s})}export{m as S};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c}from"./dashboard-
|
|
1
|
+
import{c}from"./dashboard-DWZ-fmCT.js";const e=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],r=c("network",e);const t=[["path",{d:"m10.586 5.414-5.172 5.172",key:"4mc350"}],["path",{d:"m18.586 13.414-5.172 5.172",key:"8c96vv"}],["path",{d:"M6 12h12",key:"8npq4p"}],["circle",{cx:"12",cy:"20",r:"2",key:"144qzu"}],["circle",{cx:"12",cy:"4",r:"2",key:"muu5ef"}],["circle",{cx:"20",cy:"12",r:"2",key:"1xzzfp"}],["circle",{cx:"4",cy:"12",r:"2",key:"1hvhnz"}]],h=c("waypoints",t);export{r as N,h as W};
|
package/static/dashboard/assets/{workspace-layout-BUj3wZ_m.js → workspace-layout-DqIQeTBV.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as t,j as s,f as w}from"./dashboard-
|
|
1
|
+
import{r as t,j as s,f as w}from"./dashboard-DWZ-fmCT.js";const y=t.createContext(null);function P(){const e=t.useContext(y);if(!e)throw new Error("useWorkspaceLayout must be used inside TwoPaneLayout");return e}const g="(max-width: 767px)",v={gridTemplateColumns:"210px minmax(0, 1fr)"};function j(e){return e==="context"?"main":e}function C(e){if(typeof window>"u"||typeof window.matchMedia!="function")return()=>{};const a=window.matchMedia(g);return a.addEventListener("change",e),()=>a.removeEventListener("change",e)}function R(){return typeof window>"u"||typeof window.matchMedia!="function"?"split":window.matchMedia(g).matches?"stack":"split"}function L(){return"split"}function M(e){const a=t.useSyncExternalStore(C,R,L);return e==="auto"?a:e}function N({resolvedMode:e,history:a,resolvePane:l}){const[f,m]=t.useState("list"),c=t.useRef(null),b=t.useRef(null),i=t.useRef(null),r=t.useRef(null),u=t.useMemo(()=>({list:b,main:i,context:r}),[]),o=t.useCallback((n,h={})=>{const d=l?.(n)??n;m(d),e==="stack"&&(c.current=d,h.fromHistory||a?.push(d))},[a,l,e]),p=t.useCallback(()=>o("list"),[o]),x=t.useCallback(()=>o("main"),[o]),k=t.useCallback(()=>o("context"),[o]);return t.useLayoutEffect(()=>{if(e!=="stack"){c.current=null;return}const n=c.current;n&&(c.current=null,u[n].current?.focus())},[f,u,e]),t.useLayoutEffect(()=>{if(!(e!=="stack"||!a))return a.subscribe(n=>{o(n,{fromHistory:!0})})},[a,o,e]),{activePane:f,paneRefs:u,openList:p,openMain:x,openContext:k}}function S({listHeader:e,list:a,mainHeader:l,main:f,mode:m="auto",history:c,className:b}){const i=M(m),{activePane:r,paneRefs:u,openList:o,openMain:p,openContext:x}=N({resolvedMode:i,history:c,resolvePane:j}),k=t.useMemo(()=>({mode:i,activePane:r,openList:o,openMain:p,openContext:x}),[r,x,o,p,i]),n=i==="stack",h=n&&r!=="list",d=n&&r!=="main";return s.jsx(y.Provider,{value:k,children:s.jsx("section",{className:w("flex min-h-0 flex-1 flex-col bg-background",b),"data-workspace-layout":"two-pane","data-workspace-mode":i,children:s.jsxs("div",{className:w("grid min-h-0 flex-1",n?"grid-cols-1":null),style:n?void 0:v,"data-workspace-layout-mode":m,"data-workspace-active-pane":r,children:[s.jsxs("aside",{ref:u.list,className:w("min-h-0 flex-col overflow-hidden bg-layout-list-item @container",h?"hidden":"flex",n?"border-r-0":"border-r border-border"),"data-testid":"workspace-list-pane","data-workspace-pane":"list",hidden:h,tabIndex:n?-1:void 0,children:[s.jsx("header",{className:"h-12 shrink-0 border-b border-border bg-layout-list-header","data-workspace-list-header":"true",children:e}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:a})]}),s.jsxs("main",{ref:u.main,className:w("min-h-0 flex-col overflow-hidden bg-layout-content @container",d?"hidden":"flex"),"data-testid":"workspace-main-pane","data-workspace-pane":"main",hidden:d,tabIndex:n?-1:void 0,children:[s.jsx("header",{className:"h-12 shrink-0 border-b border-border bg-layout-content","data-workspace-main-header":"true",children:l}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[n?s.jsx("button",{type:"button",className:"inline-flex items-center px-4 py-3 text-sm text-muted-foreground hover:text-foreground",onClick:o,children:"返回列表"}):null,f]})]})]})})})}export{S as T,y as W,P as u};
|
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<script src="/dashboard/theme-init.js"></script>
|
|
7
7
|
<title>Xpod Dashboard</title>
|
|
8
|
-
<script type="module" crossorigin src="/dashboard/assets/dashboard-
|
|
9
|
-
<link rel="stylesheet" crossorigin href="/dashboard/assets/dashboard-
|
|
8
|
+
<script type="module" crossorigin src="/dashboard/assets/dashboard-DWZ-fmCT.js"></script>
|
|
9
|
+
<link rel="stylesheet" crossorigin href="/dashboard/assets/dashboard-rk080mvG.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body class="bg-background text-foreground">
|
|
12
12
|
<div id="root"></div>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{u as J,r as a,j as V,p as X}from"./settings-CJWpdbNC.js";import{a as $}from"./ai-connections-CryuHGKW.js";import{d as D}from"./XpodAiConnectionsPodStore-BkNQ8fZx.js";async function R(t){return k(t(h("/api/ai/config"),{method:"GET",credentials:"include",headers:{accept:"application/json"}}))}async function G(t,e){return k(t(h("/api/ai/config"),{method:"PATCH",credentials:"include",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify(e)}))}async function H(t,e){const o=await t(h("/api/ai/config/rebuild"),{method:"POST",credentials:"include",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({target:e})}),s=await o.json().catch(()=>{});if(!o.ok||!s?.job)throw new Error(s?.error??"Index rebuild request failed");return s.job}async function ee(t,e){const o=e.capabilities.some(i=>i.toLowerCase()==="embedding"),s=await t(h(o?"/v1/embeddings":"/v1/chat/completions"),{method:"POST",credentials:"include",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify(o?{model:e.id,input:"xpod readiness probe"}:{model:e.id,messages:[{role:"user",content:"Reply OK."}],max_tokens:1,stream:!1})});if(!s.ok){const i=await s.json().catch(()=>{}),d=typeof i?.error=="string"?i.error:i?.error?.message;throw new Error(d??"Model readiness probe failed")}await s.arrayBuffer()}function h(t){if(typeof window>"u")throw new Error("AI Config API requires the current browser origin");return new URL(t,window.location.origin).toString()}async function k(t){const e=await t,o=await e.json().catch(()=>{});if(!e.ok||!o?.config||!o.capabilities)throw new Error(o?.error??"AI Config request failed");return o}const L=a.createContext(void 0),K=2e3;function te({children:t}){const e=J(),[o,s]=a.useState(),[i,d]=a.useState(),[c,p]=a.useState([]),[y,g]=a.useState(),[O,v]=a.useState(!0),[C,M]=a.useState(!1),[I,P]=a.useState(!1),[S,u]=a.useState(),[N,T]=a.useState(0),q=!!(e.webId&&e.currentPod);a.useEffect(()=>{if(!e.webId||!e.currentPod)return;let r=!1;return queueMicrotask(()=>{if(r||!e.webId||!e.currentPod)return;v(!0),u(void 0);const n=$({webId:e.webId,podUrl:e.currentPod.podUrl,authenticatedFetch:e.fetch}),_=D({database:e.currentPod.database,authenticatedFetch:e.fetch,podUrl:e.currentPod.podUrl,webId:e.currentPod.webId}).listModels?.()?.catch(()=>[])??Promise.resolve([]);Promise.all([R(e.fetch),n.listModels().catch(()=>[]),_]).then(([l,B,F])=>{r||(s(l.config),d(l.capabilities),g(l.lifecycle),p(Q(z(F,B))))}).catch(l=>{r||u(l instanceof Error?l.message:String(l))}).finally(()=>{r||v(!1)})}),()=>{r=!0}},[N,e.currentPod,e.fetch,e.webId]);const A=a.useCallback(()=>{T(r=>r+1)},[]),j=y?.pending??0;a.useEffect(()=>{if(j<=0||!e.webId||!e.currentPod)return;let r=!1;const n=setInterval(()=>{R(e.fetch).then(f=>{r||g(f.lifecycle)}).catch(()=>{})},K);return()=>{r=!0,clearInterval(n)}},[j,e.currentPod,e.fetch,e.webId]);const b=a.useCallback(async r=>{M(!0),u(void 0);try{const n=await G(e.fetch,r);s(n.config),d(n.capabilities),g(n.lifecycle)}catch(n){throw u(n instanceof Error?n.message:String(n)),n}finally{M(!1)}},[e.fetch]),m=a.useCallback(async r=>{P(!0),u(void 0);try{const n=await H(e.fetch,r);g(f=>({configurationVersion:f?.configurationVersion,pending:(f?.pending??0)+1,recent:[n,...f?.recent??[]].slice(0,20)}))}catch(n){throw u(n instanceof Error?n.message:String(n)),n}finally{P(!1)}},[e.fetch]),E=a.useCallback(async(r,n)=>{await b(r),await m(n)},[m,b]),x=q?O:!1,U=a.useMemo(()=>({config:o,capabilities:i,lifecycle:y,models:c,loading:x,saving:C,rebuilding:I,error:S,reload:A,save:b,rebuild:m,saveAndRebuild:E}),[i,o,x,S,y,c,m,I,A,b,E,C]);return V.jsx(L.Provider,{value:U,children:t})}function z(t,e){const o=new Map,s=i=>`${i.provider}\0${w(i.id)}`;for(const i of[...t,...e]){const d=s(i),c=o.get(d);if(!c){o.set(d,{...i,id:w(i.id)});continue}const p=[...new Set([...c.capabilities??[],...i.capabilities??[]])];o.set(d,{...c,...i,id:w(i.id),resourceId:c.resourceId??i.resourceId,displayName:c.displayName??i.displayName,availability:c.availability==="available"?c.availability:i.availability,modelType:c.modelType??i.modelType,...p.length>0?{capabilities:p}:{},...c.inputModalities??i.inputModalities?{inputModalities:c.inputModalities??i.inputModalities}:{}})}return[...o.values()]}function w(t){const e=t.lastIndexOf("#");return e>=0?t.slice(e+1):t}function Q(t){return t.map(e=>({id:e.id,displayName:e.displayName,owner:e.provider,ref:X(e.provider,e.id),capabilities:e.capabilities??[]}))}function ie(t,e){const s={chatModel:["chat"],ocrModel:["ocr"],readerModel:["document-understanding","documentunderstanding"],embeddingModel:["embedding"],indexerModel:["indexing"],rerankerModel:["reranking","reranker"]}[e];return s?t.filter(i=>i.capabilities.some(d=>s.includes(d.toLowerCase()))):t}function ne(){const t=a.useContext(L);if(!t)throw new Error("useAiConfig must be used within AiConfigProvider");return t}export{te as A,ie as m,ee as t,ne as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as d,j as e,v as h,r as p,O as g,N as f,w as v,x as y}from"./settings-CJWpdbNC.js";import{P as b}from"./PaneListHeader-Bjh3hRdQ.js";import{A as j,u as k}from"./AiConfigContext-BB9KZySa.js";import{T as N,u as w}from"./workspace-layout-DV5QU30U.js";import"./ai-connections-CryuHGKW.js";import"./XpodAiConnectionsPodStore-BkNQ8fZx.js";import"./index-browser-BGpvHwD0.js";const M=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"11.5",cy:"14.5",r:"2.5",key:"1bq0ko"}],["path",{d:"M13.3 16.3 15 18",key:"2quom7"}]],C=d("file-search",M);const A=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M7 12H3",key:"13ou7f"}],["path",{d:"M7 19H3",key:"wbqt3n"}],["path",{d:"M12 18a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L11 14",key:"qth677"}],["path",{d:"M11 10v4h4",key:"172dkj"}]],I=d("list-restart",A);const L=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 8h8",key:"1jbsf9"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h6",key:"1vyc9m"}]],H=d("scan-text",L);const q=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],_=d("sliders-horizontal",q);function o(s,a,t,n,i){return{id:s,label:a,path:t,href:`/ai-config/${t}`,end:!0,description:n,icon:i}}const l=[o("model-assignments","Model Assignments","model-assignments","Choose the model used by each Xpod capability.",_),o("document-processing","Document Processing","document-processing","Control OCR and structured document reading.",H),o("search-indexing","Search & Indexing","search-indexing","Enable FTS, vector retrieval, and backend selection.",C),o("index-lifecycle","Index Lifecycle","index-lifecycle","Control automatic indexing and derived-index rebuilds.",I)];function K(){return e.jsx(j,{children:e.jsx(S,{})})}function S(){const s=h(),{config:a,loading:t,saving:n,error:i,reload:m}=k(),[u,c]=p.useState(!1),x=l.find(r=>s.pathname.endsWith(r.path))??l[0];return e.jsx(N,{mode:"auto",listHeader:e.jsx(b,{title:"AI Config"}),list:e.jsx(T,{}),mainHeader:e.jsx("div",{className:"flex h-full min-w-0 items-center px-4",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"text-sm font-semibold text-foreground",children:["AI Config · ",x.label]}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:"Pod-level AI and derived-index policy"})]})}),main:e.jsxs("section",{className:"min-h-full bg-background",children:[n&&e.jsx("div",{role:"status","aria-live":"polite",className:"border-b border-border px-6 py-2 text-xs text-muted-foreground",children:"Saving AI configuration…"}),i?e.jsx(z,{error:i,showTechnicalDetails:u,onToggleTechnicalDetails:()=>c(r=>!r),onRetry:()=>{c(!1),m()}}):t||!a?e.jsx(P,{}):e.jsx(g,{})]}),className:"min-h-full"})}function z({error:s,showTechnicalDetails:a,onToggleTechnicalDetails:t,onRetry:n}){return e.jsx("div",{className:"mx-auto w-full max-w-4xl p-6",children:e.jsxs("div",{role:"alert","aria-live":"assertive",className:"rounded-lg border border-destructive/30 bg-destructive/5 p-4",children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"AI configuration could not be loaded"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Xpod could not read this Pod’s AI settings. Your existing settings were not changed."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:n,className:"h-9 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground hover:bg-primary/90",children:"Try again"}),e.jsx("button",{type:"button","aria-expanded":a,onClick:t,className:"h-9 rounded-md border border-input bg-background px-3 text-sm font-medium text-foreground hover:bg-accent",children:a?"Hide details":"Show details"})]}),a&&e.jsx("p",{className:"mt-3 break-words font-mono text-xs text-muted-foreground",children:s})]})})}function P(){return e.jsxs("div",{role:"status","aria-live":"polite",className:"mx-auto w-full max-w-4xl p-6",children:[e.jsx("div",{className:"h-7 w-52 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"mt-3 h-4 w-80 max-w-full animate-pulse rounded bg-muted"}),e.jsx("div",{className:"mt-6 divide-y divide-border overflow-hidden rounded-xl border border-border",children:Array.from({length:4},(s,a)=>e.jsxs("div",{className:"grid gap-4 p-4 lg:grid-cols-[minmax(220px,1fr)_minmax(320px,440px)]",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"h-4 w-28 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-52 animate-pulse rounded bg-muted"})]}),e.jsx("div",{className:"h-10 animate-pulse rounded-md bg-muted"})]},a))}),e.jsx("span",{className:"sr-only",children:"Loading AI configuration…"})]})}function T(){const s=w();return e.jsx("aside",{className:"h-full border-r border-border bg-muted/20 py-2",children:e.jsx("nav",{"aria-label":"AI Config sections","data-list-navigation":!0,children:l.map(a=>{const t=a.icon;return e.jsxs(f,{to:a.path,end:a.end,onClick:()=>s.openMain(),onKeyDown:v,className:({isActive:n})=>y(n,{compact:!1}),children:[e.jsx(t,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:a.label}),e.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:a.description})]})]},a.id)})})})}export{K as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as u,j as a}from"./settings-CJWpdbNC.js";import{i as g,A as p}from"./ModelAssignmentsPanel-CSAryvWJ.js";import{u as x}from"./AiConfigContext-BB9KZySa.js";import"./dialog-Csq0vWUi.js";import"./index-COmVnZi2.js";import"./ai-connections-CryuHGKW.js";import"./XpodAiConnectionsPodStore-BkNQ8fZx.js";import"./index-browser-BGpvHwD0.js";function P(){const{config:o,save:t,saving:s}=x(),[e,r]=u.useState(o?.documentProcessing);if(u.useEffect(()=>{let n=!1;return queueMicrotask(()=>{n||r(o?.documentProcessing)}),()=>{n=!0}},[o]),!e)return null;const l=g(e,o?.documentProcessing),b=async n=>{n.preventDefault(),await t({documentProcessing:e})};return a.jsx(p,{title:"Document Processing",description:"Control when Xpod invokes OCR and structured document readers.",onSubmit:b,onRestore:()=>t({documentProcessing:{ocrEnabled:!0,automaticOcr:!0,imageRecognition:!0,pdfRecognition:!0,tableRecognition:!1,processingMode:"auto",ocrFallbackOrder:["ocr","reader","plain-text"],readerPolicy:"auto",readerPriority:"structure-first",maxFileSizeMb:64,maxPages:500,failureFallback:"plain-text"}}),saving:s,dirty:l,children:a.jsxs("div",{className:"space-y-4 rounded-xl border border-border p-4",children:[a.jsx(i,{label:"Enable OCR",description:"Read text from images and scanned documents.",checked:e.ocrEnabled,onChange:n=>r({...e,ocrEnabled:n})}),a.jsx(i,{label:"Automatic OCR",description:"Run OCR when indexed content has no usable text layer.",checked:e.automaticOcr,onChange:n=>r({...e,automaticOcr:n})}),a.jsx(i,{label:"Image recognition",description:"Allow OCR and readers to process image resources.",checked:e.imageRecognition,onChange:n=>r({...e,imageRecognition:n})}),a.jsx(i,{label:"PDF recognition",description:"Process native and scanned PDF resources.",checked:e.pdfRecognition,onChange:n=>r({...e,pdfRecognition:n})}),a.jsx(i,{label:"Table recognition",description:"Preserve detected table structure when the reader supports it.",checked:e.tableRecognition,onChange:n=>r({...e,tableRecognition:n})}),a.jsxs("label",{className:"block space-y-2 text-sm font-medium",children:["Processing mode",a.jsxs("select",{name:"processingMode",value:e.processingMode,onChange:n=>r({...e,processingMode:n.target.value}),className:"block h-10 w-full rounded-md border border-input bg-background px-3 text-sm sm:max-w-xs",children:[a.jsx("option",{value:"auto",children:"Auto"}),a.jsx("option",{value:"on-demand",children:"On demand"})]})]}),a.jsxs("label",{className:"block space-y-2 text-sm font-medium",children:["OCR fallback order",a.jsx("input",{value:e.ocrFallbackOrder.join(", "),onChange:n=>r({...e,ocrFallbackOrder:n.target.value.split(",").map(c=>c.trim()).filter(c=>["ocr","reader","plain-text"].includes(c))}),className:"block h-10 w-full rounded-md border border-input bg-background px-3 text-sm"})]}),a.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[a.jsx(d,{label:"Reader policy",value:e.readerPolicy,options:["auto","always","disabled"],onChange:n=>r({...e,readerPolicy:n})}),a.jsx(d,{label:"Reader priority",value:e.readerPriority,options:["structure-first","speed-first"],onChange:n=>r({...e,readerPriority:n})}),a.jsx(m,{label:"Maximum file size (MB)",value:e.maxFileSizeMb,min:1,max:1024,onChange:n=>r({...e,maxFileSizeMb:n})}),a.jsx(m,{label:"Maximum pages",value:e.maxPages,min:1,max:1e4,onChange:n=>r({...e,maxPages:n})}),a.jsx(d,{label:"Failure fallback",value:e.failureFallback,options:["plain-text","skip"],onChange:n=>r({...e,failureFallback:n})})]})]})})}function d({label:o,value:t,options:s,onChange:e}){return a.jsxs("label",{className:"block space-y-2 text-sm font-medium",children:[o,a.jsx("select",{value:t,onChange:r=>e(r.target.value),className:"block h-10 w-full rounded-md border border-input bg-background px-3 text-sm",children:s.map(r=>a.jsx("option",{value:r,children:r},r))})]})}function m({label:o,value:t,min:s,max:e,onChange:r}){return a.jsxs("label",{className:"block space-y-2 text-sm font-medium",children:[o,a.jsx("input",{type:"number",value:t,min:s,max:e,onChange:l=>r(l.target.valueAsNumber),className:"block h-10 w-full rounded-md border border-input bg-background px-3 text-sm"})]})}function i({label:o,description:t,checked:s,onChange:e}){return a.jsxs("label",{className:"flex items-start justify-between gap-4",children:[a.jsxs("span",{children:[a.jsx("span",{className:"block text-sm font-medium",children:o}),a.jsx("span",{className:"block text-xs text-muted-foreground",children:t})]}),a.jsx("input",{type:"checkbox",checked:s,onChange:r=>e(r.target.checked),className:"mt-1 h-4 w-4 rounded border-input"})]})}export{P as DocumentProcessingPanel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as l,j as e}from"./settings-CJWpdbNC.js";import{i as h,A as b}from"./ModelAssignmentsPanel-CSAryvWJ.js";import{u as g}from"./AiConfigContext-BB9KZySa.js";import"./dialog-Csq0vWUi.js";import"./index-COmVnZi2.js";import"./ai-connections-CryuHGKW.js";import"./XpodAiConnectionsPodStore-BkNQ8fZx.js";import"./index-browser-BGpvHwD0.js";function S(){const{config:r,capabilities:d,lifecycle:i,save:n,rebuild:u,saving:m,rebuilding:x}=g(),[s,a]=l.useState(r?.lifecycle);if(l.useEffect(()=>{let t=!1;return queueMicrotask(()=>{t||a(r?.lifecycle)}),()=>{t=!0}},[r]),!s)return null;const f=h(s,r?.lifecycle),p=async t=>{t.preventDefault(),await n({lifecycle:s})};return e.jsxs(b,{title:"Index Lifecycle",description:"Control automatic maintenance and explicitly schedule rebuilds of derived data.",onSubmit:p,onRestore:()=>n({lifecycle:{automaticIndexing:!0,refreshAfterSourceUpdate:!0,removeAfterSourceDeletion:!0}}),saving:m,dirty:f,children:[e.jsxs("div",{className:"divide-y divide-border rounded-xl border border-border",children:[e.jsxs("label",{className:"flex items-start justify-between gap-4 p-4",children:[e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-medium",children:"Automatically index changes"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Index new and updated resources, and remove derived entries after deletion."})]}),e.jsx("input",{name:"automaticIndexing",type:"checkbox",checked:s.automaticIndexing,onChange:t=>a({...s,automaticIndexing:t.target.checked}),className:"mt-1 h-4 w-4 rounded border-input"})]}),e.jsx(c,{label:"Refresh after source updates",checked:s.refreshAfterSourceUpdate,onChange:t=>a({...s,refreshAfterSourceUpdate:t})}),e.jsx(c,{label:"Remove derived entries after source deletion",checked:s.removeAfterSourceDeletion,onChange:t=>a({...s,removeAfterSourceDeletion:t})})]}),e.jsxs("section",{className:"rounded-xl border border-border p-4",children:[e.jsx("h2",{className:"text-sm font-medium",children:"Rebuild derived indexes"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Rebuild actions never modify authority data in the Pod."}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:["fts","vector","all"].map(t=>e.jsxs("button",{type:"button",disabled:!d?.rebuildTargets?.includes(t)||x,onClick:()=>u(t),className:"h-9 rounded-md border border-input px-3 text-sm font-medium disabled:opacity-50",children:["Rebuild ",t==="all"?"all":t.toUpperCase()]},t))})]}),e.jsxs("section",{className:"rounded-xl border border-border p-4",children:[e.jsx("h2",{className:"text-sm font-medium",children:"Lifecycle evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(o,{label:"Configuration version",value:i?.configurationVersion??r?.updatedAt??"Default"}),e.jsx(o,{label:"Pending queue",value:String(i?.pending??0)})]}),e.jsx("div",{className:"mt-4 space-y-2",children:i?.recent.length?i.recent.map(t=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border border-border p-3 text-sm",children:[e.jsxs("span",{children:[t.target.toUpperCase()," · ",t.status]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.progress??0,"% · ",new Date(t.createdAt).toLocaleString()]}),t.error?e.jsx("span",{className:"w-full text-xs text-destructive",children:t.error}):null]},t.id)):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No rebuild jobs have been scheduled."})})]})]})}function c({label:r,checked:d,onChange:i}){return e.jsxs("label",{className:"flex items-start justify-between gap-4 p-4",children:[e.jsx("span",{className:"text-sm font-medium",children:r}),e.jsx("input",{type:"checkbox",checked:d,onChange:n=>i(n.target.checked),className:"mt-1 h-4 w-4 rounded border-input"})]})}function o({label:r,value:d}){return e.jsxs("div",{className:"rounded-md border border-border p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:r}),e.jsx("div",{className:"mt-1 text-sm font-medium",children:d})]})}export{S as IndexLifecyclePanel};
|
package/static/settings/assets/{IndexSubjectPanel-73sM16Ma.js → IndexSubjectPanel-CFd0ay-r.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as l,j as e,B as g,R as j,C as p,a as y,b,d as S,e as N}from"./settings-
|
|
1
|
+
import{r as l,j as e,B as g,R as j,C as p,a as y,b,d as S,e as N}from"./settings-CJWpdbNC.js";import{g as C}from"./admin-C6qCRFiY.js";import{S as m}from"./skeleton-JDHYVe7t.js";function F({kind:r}){const[s,n]=l.useState(null),[d,t]=l.useState(!1),i=l.useCallback(async()=>{t(!0);try{n(await C())}finally{t(!1)}},[]);return l.useEffect(()=>{let c=!0;return Promise.resolve().then(()=>{c&&i()}),()=>{c=!1}},[i]),e.jsxs("div",{className:"space-y-4 p-6",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(g,{type:"button",size:"sm",variant:"outline",onClick:i,disabled:d,children:[e.jsx(j,{className:"mr-2 h-4 w-4"}),"Refresh"]})}),e.jsx("div",{role:"status","aria-live":"polite",className:"sr-only",children:d?"Refreshing index evidence…":s?"Index evidence refreshed.":"Waiting for index evidence."}),e.jsxs(p,{children:[e.jsxs(y,{children:[e.jsx(b,{children:w[r]}),e.jsx(S,{children:"Observed derived-index state; policy changes belong in AI Config."})]}),e.jsx(N,{children:d&&!s?e.jsx(B,{}):R(r,s)})]})]})}const w={overview:"Index Overview",fts:"FTS",vector:"Vector","retrieval-points":"Retrieval Points",cache:"Cache","slow-queries":"Slow Queries",benchmark:"Benchmark"};function R(r,s){if(!s)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Waiting for runtime evidence."});if(r==="benchmark"){const t=s.benchmarkReports;return e.jsx(a,{values:[["Reports",String(t?.reportCount??0)],["Skipped files",String(t?.skippedFiles??0)],["Errors",String(t?.errors.length??0)]]})}if(!s.available)return e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Unavailable: ",s.reason]});if(r==="overview"){const t=s.stats.lifecycle;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(a,{values:[["Engine",s.engine],["State",v(t?.status)],["Authority data",o(s.stats.factsBytes)],["Derived storage",o(s.stats.derivedBytes)],["Total storage",o(s.stats.totalBytes)],["Generated",f(s.generatedAt)]]}),e.jsx(x,{children:"Derived indexes are rebuildable runtime evidence; Pod RDF remains the authority data."})]})}if(r==="cache"){const t=s.stats.derivedCache;return t?e.jsx(a,{values:[["Cache bytes",o(t.cacheBytes)],["Limit",o(t.maxCacheBytes)],["Pressure",`${Math.round(t.cachePressure*100)}%`],["Evictions",String(t.evictionCount)]]}):e.jsx(u,{})}if(r==="slow-queries"){const t=s.stats.slowQueries;return t?e.jsxs("div",{className:"space-y-2",children:[e.jsx(a,{values:[["Captured",String(t.entryCount)],["Limit",String(t.maxEntries)]]}),t.entries.slice(0,10).map(i=>e.jsxs("div",{className:"rounded-lg border border-border p-3 text-sm",children:[e.jsxs("div",{className:"font-medium",children:[i.runtime.durationMs," ms · ",i.runtime.returnedRows," rows"]}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:i.reasons.join(", ")||i.queryKey})]},`${i.generatedAt}-${i.queryKey}`))]}):e.jsx(u,{})}if(r==="retrieval-points"){const t=s.stats.rdf3x;return t?e.jsx(a,{values:[["State",t.syncedWithFacts?"Synchronized":`${t.refreshLag} versions behind`],["Facts version",String(t.factsDataVersion)],["Retrieval version",String(t.rdf3xFactsDataVersion)],["Pending sources",String(t.pendingSources)]]}):e.jsx(u,{})}const n=s.stats.lifecycle,d=r==="fts"?n?.coldStart?.ownsTextIndex:n?.coldStart?.ownsVectorIndex;if((r==="fts"||r==="vector")&&d){const t=s.stats.pgAcceleration,i=s.stats.rdf3x;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(a,{values:[["State",v(n?.status)],["Ownership","Runtime managed"],["Backend",t?.provider?`${h(t.provider)}${t.version?` ${t.version}`:""}`:n?.driver??"Not reported"],["Freshness",i?i.syncedWithFacts?"Current":`${i.refreshLag} versions behind`:"Not reported"],["Indexes",t?.customIndexes?.map(c=>c.name).join(", ")||"Runtime managed"],["Last ready",f(n?.lastReadyAt)]]}),e.jsxs(x,{children:[r==="fts"?"Text retrieval":"Vector retrieval"," is derived from Pod authority data. Enablement and backend policy are configured in AI Config."]})]})}return e.jsx(u,{})}function a({values:r}){return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:r.map(([s,n])=>e.jsxs("div",{className:"rounded-lg border border-border p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:s}),e.jsx("div",{className:"mt-1 font-medium",children:n})]},s))})}function B(){return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","aria-hidden":"true",children:Array.from({length:4},(r,s)=>e.jsxs("div",{className:"rounded-lg border border-border p-3",children:[e.jsx(m,{className:"h-3 w-20"}),e.jsx(m,{className:"mt-2 h-5 w-28"})]},s))})}function u(){return e.jsx("p",{className:"text-sm text-muted-foreground",children:"This runtime does not report evidence for this index subject."})}function x({children:r}){return e.jsx("p",{className:"text-sm text-muted-foreground",children:r})}function o(r){return r<1024?`${r} B`:r<1024*1024?`${Math.round(r/1024)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}function f(r){return r?new Date(r).toLocaleString():"Not reported"}function v(r){return r?h(r):"Unknown"}function h(r){return r.charAt(0).toUpperCase()+r.slice(1)}export{F as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e,u as U,r as b}from"./settings-CJWpdbNC.js";import{m as z,u as L,t as q}from"./AiConfigContext-BB9KZySa.js";import{D as X,a as J,b as V,c as G,d as H,e as K}from"./dialog-Csq0vWUi.js";function Q(t,s){return N(t)!==N(s)}function N(t){return Array.isArray(t)?`[${t.map(N).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,s])=>s!==void 0).sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>`${JSON.stringify(s)}:${N(n)}`).join(",")}}`:JSON.stringify(t)}const k=[{label:"General / Chat",name:"chatModel",description:"Used for assistant conversations and general text tasks."},{label:"OCR",name:"ocrModel",description:"Reads text from images and scanned pages."},{label:"Document Reader",name:"readerModel",description:"Extracts structure and content from documents."},{label:"Embedding",name:"embeddingModel",description:"Creates vectors for semantic search."},{label:"Indexer / Summarizer",name:"indexerModel",description:"Prepares and summarizes content for indexes."},{label:"Reranker",name:"rerankerModel",description:"Reorders search results by relevance."}];function W(){const{config:t,capabilities:s,lifecycle:n,models:o,save:l,saveAndRebuild:c,saving:i,rebuilding:a}=L(),g=U(),[f,j]=b.useState({}),[u,v]=b.useState(),[y,w]=b.useState({}),[S,x]=b.useState(),[C,d]=b.useState();b.useEffect(()=>{let r=!1;return queueMicrotask(()=>{r||j(t?.models??{})}),()=>{r=!0}},[t]);const _=Q(f,t?.models??{}),M=T(f,t),h=R(n,a),A=()=>Object.fromEntries(k.map(({name:r})=>[r,f[r]||null])),F=async r=>{if(r.preventDefault(),M){if(h)return;x({models:A(),switch:M});return}await l({models:A()})},B=async()=>{const r=Object.fromEntries(k.map(({name:p})=>[p,null])),m=T(r,t);if(!m){await l({models:r});return}h||x({models:r,switch:m})},I=async()=>{const r=S;if(x(void 0),!r)return;const m=D(s);if(!m){await l({models:r.models}),d("模型已保存;此运行时不支持重建索引,请稍后手动重建。");return}await c({models:r.models},m),d(void 0)};return e.jsxs(e.Fragment,{children:[e.jsxs(P,{title:"Model Assignments",description:"Choose a connected model for each Xpod capability. Unassigned capabilities use the system default.",onSubmit:F,onRestore:()=>{B()},saving:i||a,dirty:_,children:[e.jsx("div",{className:"divide-y divide-border rounded-xl border border-border",children:k.map(r=>e.jsx(O,{...r,models:o,value:f[r.name],testing:u===r.name,testResult:y[r.name],disabled:r.name==="embeddingModel"&&h,notice:r.name!=="embeddingModel"?void 0:h?"索引重建进行中,完成后才能再次切换向量模型。":M?"切换向量模型会重建索引:保存前需要二次确认,确认后立即排队重建。":void 0,onChange:m=>j(p=>({...p,[r.name]:m})),onTest:async m=>{v(r.name);try{await q(g.fetch,m),w(p=>({...p,[r.name]:"ready"}))}catch{w(p=>({...p,[r.name]:"failed"}))}finally{v(void 0)}}},r.name))}),e.jsx(E,{lifecycle:n,fallbackNotice:C})]}),e.jsx(Z,{request:S?.switch,models:o,saving:i||a||h,onCancel:()=>x(void 0),onConfirm:()=>{I()}})]})}function T(t,s){const n=t.embeddingModel;if(n===void 0)return;const o=s?.models?.embeddingModel??"";return(n??"")===o?void 0:{from:o||void 0,to:n||void 0}}function R(t,s=!1){if(s)return!0;const n=$(t)?.phase;return n==="queued"||n==="running"}function D(t){const s=t?.rebuildTargets??[];if(s.includes("vector"))return"vector";if(s.includes("all"))return"all"}function $(t){if(!t)return;const s=t.recent[0];if(!s)return t.pending>0?{phase:"queued",pending:t.pending}:void 0;if(!(s.status==="queued"&&t.pending<=0))return{phase:s.status,pending:t.pending,target:s.target,...s.progress!==void 0?{progress:s.progress}:{},...s.error?{error:s.error}:{}}}const Y={queued:"索引重建已排队",running:"索引重建进行中",succeeded:"索引重建完成",failed:"索引重建失败"};function E({lifecycle:t,fallbackNotice:s}){const n=$(t);if(!n)return s?e.jsx("p",{role:"status",className:"text-xs text-amber-600",children:s}):null;const o=[n.progress!==void 0?`${n.progress}%`:void 0,n.pending>0?`队列 ${n.pending}`:void 0,n.error].filter(Boolean).join(" · ");return e.jsxs("p",{role:"status",className:`text-xs ${n.phase==="failed"?"text-destructive":"text-muted-foreground"}`,children:[Y[n.phase],o?` · ${o}`:""]})}function Z({request:t,models:s,saving:n,onCancel:o,onConfirm:l}){const c=i=>{if(!i)return"系统默认";const a=s.find(g=>g.ref===i);return a?`${a.displayName??a.id} · ${a.owner}`:i};return e.jsx(X,{open:!!t,onOpenChange:i=>{i||o()},children:e.jsxs(J,{"data-testid":"embedding-switch-dialog",children:[e.jsxs(V,{children:[e.jsx(G,{children:"切换向量模型并重建索引?"}),e.jsx(H,{children:"已建立的向量由原模型生成,切换后需要用新模型重建索引才能参与检索。重建期间检索只会返回文本命中。"})]}),t&&e.jsxs("dl",{className:"grid gap-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-muted-foreground",children:"当前"}),e.jsx("dd",{className:"min-w-0 break-all text-right",children:c(t.from)})]}),e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-muted-foreground",children:"切换为"}),e.jsx("dd",{className:"min-w-0 break-all text-right",children:c(t.to)})]})]}),e.jsxs(K,{children:[e.jsx("button",{type:"button",onClick:o,className:"h-9 rounded-md border border-input bg-background px-3 text-sm font-medium hover:bg-accent",children:"取消"}),e.jsx("button",{type:"button",disabled:n,onClick:l,className:"h-9 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground disabled:opacity-50",children:n?"提交中…":"确认切换并重建"})]})]})})}function O({label:t,name:s,description:n,models:o,value:l,testing:c,testResult:i,notice:a,disabled:g=!1,onChange:f,onTest:j}){const u=o.find(d=>d.ref===l),v=z(o,s),y=u?.capabilities.some(d=>["chat","embedding"].includes(d.toLowerCase()))===!0,x=[u?`Connected · credential ready · ${u.owner}`:l?"Selected model is no longer credential-ready":void 0,i==="ready"?"Probe succeeded":i==="failed"?"Probe failed; review AI Connection health":void 0].filter(Boolean).join(" · "),C=!!(l&&!u)||i==="failed";return e.jsxs("div",{"data-testid":"model-assignment-row",className:"grid gap-3 p-4 lg:grid-cols-[minmax(220px,1fr)_minmax(320px,440px)] lg:items-start",children:[e.jsxs("div",{className:"min-w-0 pt-1",children:[e.jsx("span",{className:"block text-sm font-medium text-foreground",children:t}),e.jsx("span",{className:"mt-0.5 block text-xs leading-5 text-muted-foreground",children:n})]}),e.jsxs("div",{"data-testid":"model-assignment-controls",className:"grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_4.5rem] sm:items-start",children:[e.jsxs("label",{className:"min-w-0",children:[e.jsxs("span",{className:"sr-only",children:[t," model"]}),e.jsxs("select",{name:s,value:l??"",disabled:g,onChange:d=>f(d.target.value),className:"h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground disabled:opacity-50",children:[e.jsx("option",{value:"",children:"System default"}),v.map(d=>e.jsxs("option",{value:d.ref,children:[d.displayName??d.id," · ",d.owner]},`${d.owner}:${d.id}`))]})]}),e.jsx("button",{type:"button","aria-label":`Test ${t} model`,disabled:g||!y||c,title:u?y?"Send a bounded readiness probe":"This model has no bounded probe endpoint":"Select a connected model first",onClick:()=>u&&void j(u),className:"h-10 w-full self-start rounded-md border border-input bg-background px-3 text-sm font-medium text-foreground hover:bg-accent disabled:opacity-50",children:c?"Testing…":"Test"}),x&&e.jsx("span",{role:"status",className:`text-xs sm:col-span-2 ${C?"text-destructive":"text-muted-foreground"}`,children:x}),a&&e.jsx("span",{"data-testid":"model-assignment-notice",className:"text-xs text-amber-600 sm:col-span-2",children:a})]})]})}function P({title:t,description:s,children:n,onSubmit:o,onRestore:l,footerActions:c,saving:i=!1,dirty:a=!0}){return e.jsxs("form",{onSubmit:o,className:"mx-auto flex w-full max-w-4xl flex-col gap-6 p-6",children:[e.jsxs("header",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:t}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm text-muted-foreground",children:s})]}),n,e.jsxs("div",{className:"flex justify-end gap-2 border-t border-border pt-4",children:[e.jsx("span",{role:"status",className:"mr-auto self-center text-xs text-muted-foreground",children:a?"Unsaved changes":"Applied"}),c,e.jsx("button",{type:"button",onClick:l,disabled:i||!l,className:"h-9 rounded-md border border-input bg-background px-3 text-sm font-medium hover:bg-accent disabled:opacity-50",children:"Restore defaults"}),e.jsx("button",{type:"submit",disabled:i||!o||!a,className:"h-9 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground disabled:opacity-50",children:i?"Saving…":"Save configuration"})]})]})}const ne=Object.freeze(Object.defineProperty({__proto__:null,AiConfigForm:P,ModelAssignmentRow:O,ModelAssignmentsPanel:W,RebuildStatusLine:E,embeddingModelSwitch:T,rebuildInFlight:R,rebuildStatusFrom:$,rebuildTargetForCapabilities:D},Symbol.toStringTag,{value:"Module"}));export{P as A,ne as M,Q as i};
|